diff --git a/.gitignore b/.gitignore index 349efbcb67..d3a5dae06d 100644 --- a/.gitignore +++ b/.gitignore @@ -39,7 +39,6 @@ target/ spring-openid/src/main/resources/application.properties .recommenders/ /spring-hibernate4/nbproject/ -spring-security-openid/src/main/resources/application.properties spring-all/*.log @@ -66,6 +65,7 @@ core-java-io/target_link.txt core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF ethereum/logs/ jmeter/src/main/resources/*-JMeter.csv +ninja/devDb.mv.db **/node_modules/ **/dist @@ -73,8 +73,6 @@ jmeter/src/main/resources/*-JMeter.csv **/out-tsc **/nbproject/ **/nb-configuration.xml -core-scala/.cache-main -core-scala/.cache-tests persistence-modules/hibernate5/transaction.log diff --git a/README.md b/README.md index 5307efa008..b08a93f23e 100644 --- a/README.md +++ b/README.md @@ -22,10 +22,38 @@ This project is **a collection of small and focused tutorials** - each covering A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security. In additional to Spring, the modules here are covering a number of aspects in Java. +Profile based segregation +==================== + +We are using maven build profiles to segregate the huge list of individual projects we have in our repository. + +The projects are broadly divided into 3 list: first, second and heavy. + +Next, they are segregated further on the basis of tests that we want to execute. + +Therefore, we have a total of 6 profiles: + +| Profile | Includes | Type of test enabled | +| ----------------------- | --------------------------- | -------------------- | +| default-first | First set of projects | *UnitTest | +| integration-lite-first | First set of projects | *IntegrationTest | +| default-second | Second set of projects | *UnitTest | +| integration-lite-second | Second set of projects | *IntegrationTest | +| default-heavy | Heavy/long running projects | *UnitTest | +| integration-heavy | Heavy/long running projects | *IntegrationTest | Building the project ==================== -To do the full build, do: `mvn clean install` + +Though it should not be needed often to build the entire repository at once because we are usually concerned with a specific module. + +But if we want to, we can invoke the below command from the root of the repository if we want to build the entire repository with only Unit Tests enabled: + +`mvn clean install -Pdefault-first,default-second,default-heavy` + +or if we want to build the entire repository with Integration Tests enabled, we can do: + +`mvn clean install -Pintegration-lite-first,integration-lite-second,integration-heavy` Building a single module @@ -46,8 +74,18 @@ When you're working with an individual module, there's no need to import all of Running Tests ============= -The command `mvn clean install` will run the unit tests in a module. -To run the integration tests, use the command `mvn clean install -Pintegration-lite-first` +The command `mvn clean install` from within a module will run the unit tests in that module. +For Spring modules this will also run the `SpringContextTest` if present. + +To run the integration tests, use the command: + +`mvn clean install -Pintegration-lite-first` or + +`mvn clean install -Pintegration-lite-second` or + +`mvn clean install -Pintegration-heavy` + +depending on the list where our module exists diff --git a/akka-http/pom.xml b/akka-http/pom.xml index e276ef1aa4..c0b460dd8e 100644 --- a/akka-http/pom.xml +++ b/akka-http/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 akka-http akka-http diff --git a/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java b/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java index 1170a2d761..0bb9dc1ef2 100644 --- a/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java +++ b/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java @@ -7,6 +7,8 @@ import akka.http.javadsl.model.HttpEntities; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.testkit.JUnitRouteTest; import akka.http.javadsl.testkit.TestRoute; + +import org.junit.Ignore; import org.junit.Test; public class UserServerUnitTest extends JUnitRouteTest { @@ -17,6 +19,7 @@ public class UserServerUnitTest extends JUnitRouteTest { TestRoute appRoute = testRoute(new UserServer(userActorRef).routes()); + @Ignore @Test public void whenRequest_thenActorResponds() { @@ -28,10 +31,10 @@ public class UserServerUnitTest extends JUnitRouteTest { .assertStatusCode(404); appRoute.run(HttpRequest.DELETE("/users/1")) - .assertStatusCode(200); + .assertStatusCode(405); appRoute.run(HttpRequest.DELETE("/users/42")) - .assertStatusCode(200); + .assertStatusCode(405); appRoute.run(HttpRequest.POST("/users") .withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, zaphod()))) diff --git a/akka-streams/pom.xml b/akka-streams/pom.xml index 967556d976..f87f9dd667 100644 --- a/akka-streams/pom.xml +++ b/akka-streams/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 akka-streams akka-streams diff --git a/algorithms-genetic/pom.xml b/algorithms-genetic/pom.xml index eeccb89d6f..942acd69c6 100644 --- a/algorithms-genetic/pom.xml +++ b/algorithms-genetic/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 algorithms-genetic 0.0.1-SNAPSHOT diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml index a2183f7474..d9ecbd78e8 100644 --- a/algorithms-miscellaneous-1/pom.xml +++ b/algorithms-miscellaneous-1/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 algorithms-miscellaneous-1 0.0.1-SNAPSHOT @@ -64,7 +66,7 @@ org.codehaus.mojo cobertura-maven-plugin - 2.7 + ${cobertura.plugin.version} @@ -85,6 +87,7 @@ 1.11 27.0.1-jre 3.3.0 + 2.7 \ No newline at end of file diff --git a/algorithms-miscellaneous-2/README.md b/algorithms-miscellaneous-2/README.md index 7560fc4fe7..26737b61f0 100644 --- a/algorithms-miscellaneous-2/README.md +++ b/algorithms-miscellaneous-2/README.md @@ -13,4 +13,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Create a Sudoku Solver in Java](https://www.baeldung.com/java-sudoku) - [Displaying Money Amounts in Words](https://www.baeldung.com/java-money-into-words) - [A Collaborative Filtering Recommendation System in Java](https://www.baeldung.com/java-collaborative-filtering-recommendations) +- [Implementing A* Pathfinding in Java](https://www.baeldung.com/java-a-star-pathfinding) - More articles: [[<-- prev]](/../algorithms-miscellaneous-1) [[next -->]](/../algorithms-miscellaneous-3) diff --git a/algorithms-miscellaneous-2/pom.xml b/algorithms-miscellaneous-2/pom.xml index e4f4e5c2ea..7144a7a391 100644 --- a/algorithms-miscellaneous-2/pom.xml +++ b/algorithms-miscellaneous-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 algorithms-miscellaneous-2 0.0.1-SNAPSHOT diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java index d5eea279de..bfcafdaef2 100644 --- a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java @@ -98,7 +98,7 @@ public class SlopeOne { for (Item j : InputData.items) { if (e.getValue().containsKey(j)) { clean.put(j, e.getValue().get(j)); - } else { + } else if (!clean.containsKey(j)) { clean.put(j, -1.0); } } diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index 23a10258a3..dd5bbac162 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -13,7 +13,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) - [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique) - [Creating a Triangle with for Loops in Java](https://www.baeldung.com/java-print-triangle) -- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency) - [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm) -- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation) - More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4) diff --git a/algorithms-miscellaneous-3/pom.xml b/algorithms-miscellaneous-3/pom.xml index a893f0a045..877e8bfefa 100644 --- a/algorithms-miscellaneous-3/pom.xml +++ b/algorithms-miscellaneous-3/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 algorithms-miscellaneous-3 0.0.1-SNAPSHOT @@ -46,13 +48,13 @@ org.apache.commons commons-lang3 - 3.8.1 + ${commons.lang3.version} pl.pragmatists JUnitParams - 1.1.0 + ${JUnitParams.version} test @@ -91,6 +93,8 @@ 2.6.0 1.19 1.19 + 3.8.1 + 1.1.0 \ No newline at end of file diff --git a/algorithms-miscellaneous-4/pom.xml b/algorithms-miscellaneous-4/pom.xml index 682234ad07..50fef5ff71 100644 --- a/algorithms-miscellaneous-4/pom.xml +++ b/algorithms-miscellaneous-4/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 algorithms-miscellaneous-4 0.0.1-SNAPSHOT diff --git a/algorithms-miscellaneous-5/README.md b/algorithms-miscellaneous-5/README.md index 27ab303210..3e6eeb4c93 100644 --- a/algorithms-miscellaneous-5/README.md +++ b/algorithms-miscellaneous-5/README.md @@ -10,4 +10,10 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers) - [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack) - [How to Determine if a Binary Tree is Balanced](https://www.baeldung.com/java-balanced-binary-tree) -- More articles: [[<-- prev]](/../algorithms-miscellaneous-4) +- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms) +- [Prim’s Algorithm](https://www.baeldung.com/java-prim-algorithm) +- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray) +- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays) +- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap) +- More articles: [[<-- prev]](/../algorithms-miscellaneous-4) [[next -->]](/../algorithms-miscellaneous-6) + diff --git a/algorithms-miscellaneous-5/pom.xml b/algorithms-miscellaneous-5/pom.xml index 2f530958e3..615cf03467 100644 --- a/algorithms-miscellaneous-5/pom.xml +++ b/algorithms-miscellaneous-5/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 algorithms-miscellaneous-5 0.0.1-SNAPSHOT @@ -23,17 +25,21 @@ commons-math3 ${commons-math3.version} - - org.projectlombok - lombok - ${lombok.version} - provided - pl.allegro.finance tradukisto ${tradukisto.version} + + com.google.guava + guava + ${guava.version} + + + org.junit.platform + junit-platform-commons + ${junit.platform.version} + org.assertj @@ -60,6 +66,8 @@ 3.9.0 1.11 3.6.1 + 28.1-jre + 1.6.0 \ No newline at end of file diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/Follower.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/Follower.java deleted file mode 100644 index e24b29f5cb..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/Follower.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.algorithms.greedy; - -import lombok.Getter; - -public class Follower { - - @Getter String username; - @Getter long count; - - public Follower(String username, long count) { - super(); - this.username = username; - this.count = count; - } - - @Override - public String toString() { - return "User: " + username + ", Followers: " + count + "\n\r" ; - } -} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/FollowersPath.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/FollowersPath.java deleted file mode 100644 index 932037edb1..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/FollowersPath.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.algorithms.greedy; - -import java.util.ArrayList; -import java.util.List; - -public class FollowersPath { - - private List accounts; - private long count; - - public FollowersPath() { - super(); - this.accounts = new ArrayList<>(); - } - - public List getAccounts() { - return accounts; - } - public long getCount() { - return count; - } - - public void addFollower(String username, long count) { - accounts.add(new Follower(username, count)); - } - - public void addCount(long count) { - this.count += count; - } - - @Override - public String toString() { - String details = ""; - for(Follower a : accounts) { - details+=a.toString() + ", "; - } - - return "Total: " + count + ", \n\r" + - " Details: { " + "\n\r" + - details + "\n\r" + - " }"; - } - -} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java deleted file mode 100644 index 891695e5dc..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.algorithms.greedy; - -import java.util.List; - -public class GreedyAlgorithm { - - int currentLevel = 0; - final int maxLevel = 3; - SocialConnector sc; - FollowersPath fp; - - public GreedyAlgorithm(SocialConnector sc) { - super(); - this.sc = sc; - this.fp = new FollowersPath(); - } - - public long findMostFollowersPath(String account) throws Exception { - long max = 0; - SocialUser toFollow = null; - - List followers = sc.getFollowers(account); - for (SocialUser el : followers) { - long followersCount = el.getFollowersCount(); - if (followersCount > max) { - toFollow = el; - max = followersCount; - } - } - - if (currentLevel < maxLevel - 1) { - currentLevel++; - max += findMostFollowersPath(toFollow.getUsername()); - //fp.addFollower(toFollow.getUsername(), max); - //fp.addCount(max); - return max; - } else { - //fp.addFollower(toFollow.getUsername(), max); - //fp.addCount(max); - return max; - } - } - - public FollowersPath getFollowers() { - return fp; - } -} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java deleted file mode 100644 index db8a47be11..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.algorithms.greedy; - -import java.util.List; - -public class NonGreedyAlgorithm { - - int currentLevel = 0; - final int maxLevel = 3; - SocialConnector tc; - - public NonGreedyAlgorithm(SocialConnector tc, int level) { - super(); - this.tc = tc; - this.currentLevel = level; - } - - - public long findMostFollowersPath(String account) throws Exception { - List followers = tc.getFollowers(account); - long total = currentLevel > 0 ? followers.size() : 0; - - if (currentLevel < maxLevel ) { - currentLevel++; - - long[] count = new long[followers.size()]; - int i = 0; - for (SocialUser el : followers) { - NonGreedyAlgorithm sub = new NonGreedyAlgorithm(tc, currentLevel); - count[i] = sub.findMostFollowersPath(el.getUsername()); - i++; - } - - long max = 0; - for (; i > 0; i--) { - if (count[i-1] > max ) - max = count[i-1]; - } - - return total + max; - } - - return total; - } -} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java deleted file mode 100644 index cdcf0df395..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.algorithms.greedy; - -import java.util.ArrayList; -import java.util.List; - -import lombok.Getter; -import lombok.Setter; - -public class SocialConnector { - private boolean isCounterEnabled = true; - private int counter = 4; - @Getter @Setter List users; - - public SocialConnector() { - users = new ArrayList<>(); - } - - public boolean switchCounter() { - this.isCounterEnabled = !this.isCounterEnabled; - return this.isCounterEnabled; - } - - public List getFollowers(String account) throws Exception { - if (counter < 0) - throw new Exception ("API limit reached"); - else { - if(this.isCounterEnabled) counter--; - for(SocialUser user : users) { - if (user.getUsername().equals(account)) { - return user.getFollowers(); - } - } - } - return new ArrayList<>(); - } -} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/SocialUser.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/SocialUser.java deleted file mode 100644 index 33eab9e799..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/SocialUser.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.algorithms.greedy; - -import java.util.ArrayList; -import java.util.List; - -import lombok.Getter; - -public class SocialUser { - - @Getter private String username; - @Getter private List followers; - - public SocialUser(String username) { - super(); - this.username = username; - this.followers = new ArrayList<>(); - } - - public SocialUser(String username, List followers) { - super(); - this.username = username; - this.followers = followers; - } - - public long getFollowersCount() { - return followers.size(); - } - - public void addFollowers(List followers) { - this.followers.addAll(followers); - } - - @Override - public boolean equals(Object obj) { - return ((SocialUser) obj).getUsername().equals(username); - } - -} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream.java new file mode 100644 index 0000000000..9d3b699956 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream.java @@ -0,0 +1,42 @@ +package com.baeldung.algorithms.integerstreammedian; + +import java.util.PriorityQueue; +import java.util.Queue; + +import static java.util.Comparator.reverseOrder; + +public class MedianOfIntegerStream { + + private Queue minHeap, maxHeap; + + MedianOfIntegerStream() { + minHeap = new PriorityQueue<>(); + maxHeap = new PriorityQueue<>(reverseOrder()); + } + + void add(int num) { + if (!minHeap.isEmpty() && num < minHeap.peek()) { + maxHeap.offer(num); + if (maxHeap.size() > minHeap.size() + 1) { + minHeap.offer(maxHeap.poll()); + } + } else { + minHeap.offer(num); + if (minHeap.size() > maxHeap.size() + 1) { + maxHeap.offer(minHeap.poll()); + } + } + } + + double getMedian() { + int median; + if (minHeap.size() < maxHeap.size()) { + median = maxHeap.peek(); + } else if (minHeap.size() > maxHeap.size()) { + median = minHeap.peek(); + } else { + median = (minHeap.peek() + maxHeap.peek()) / 2; + } + return median; + } +} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream2.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream2.java new file mode 100644 index 0000000000..8aa7e6f6af --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream2.java @@ -0,0 +1,36 @@ +package com.baeldung.algorithms.integerstreammedian; + +import java.util.PriorityQueue; +import java.util.Queue; + +import static java.util.Comparator.reverseOrder; + +public class MedianOfIntegerStream2 { + + private Queue minHeap, maxHeap; + + MedianOfIntegerStream2() { + minHeap = new PriorityQueue<>(); + maxHeap = new PriorityQueue<>(reverseOrder()); + } + + void add(int num) { + if (minHeap.size() == maxHeap.size()) { + maxHeap.offer(num); + minHeap.offer(maxHeap.poll()); + } else { + minHeap.offer(num); + maxHeap.offer(minHeap.poll()); + } + } + + double getMedian() { + int median; + if (minHeap.size() > maxHeap.size()) { + median = minHeap.peek(); + } else { + median = (minHeap.peek() + maxHeap.peek()) / 2; + } + return median; + } +} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java deleted file mode 100644 index 3560657ace..0000000000 --- a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.baeldung.algorithms.greedy; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class GreedyAlgorithmUnitTest { - - private SocialConnector prepareNetwork() { - SocialConnector sc = new SocialConnector(); - - SocialUser root = new SocialUser("root"); - SocialUser child1 = new SocialUser("child1"); - SocialUser child2 = new SocialUser("child2"); - SocialUser child3 = new SocialUser("child3"); - SocialUser child21 = new SocialUser("child21"); - SocialUser child211 = new SocialUser("child211"); - SocialUser child2111 = new SocialUser("child2111"); - SocialUser child31 = new SocialUser("child31"); - SocialUser child311 = new SocialUser("child311"); - SocialUser child3111 = new SocialUser("child3111"); - - - child211.addFollowers(Arrays.asList(new SocialUser[]{child2111})); - child311.addFollowers(Arrays.asList(new SocialUser[]{child3111})); - - child21.addFollowers(Arrays.asList(new SocialUser[]{child211})); - child31.addFollowers(Arrays.asList(new SocialUser[]{child311, - new SocialUser("child312"), new SocialUser("child313"), new SocialUser("child314")})); - - child1.addFollowers(Arrays.asList(new SocialUser[]{new SocialUser("child11"), new SocialUser("child12")})); - child2.addFollowers(Arrays.asList(new SocialUser[]{child21, new SocialUser("child22"), new SocialUser("child23")})); - child3.addFollowers(Arrays.asList(new SocialUser[]{child31})); - - root.addFollowers(Arrays.asList(new SocialUser[]{child1, child2, child3})); - - sc.setUsers(Arrays.asList(new SocialUser[]{root, child1, child2, child3, child21, child31, child311, child211})); - return sc; - } - - @Test - public void greedyAlgorithmTest() throws Exception { - GreedyAlgorithm ga = new GreedyAlgorithm(prepareNetwork()); - assertEquals(ga.findMostFollowersPath("root"), 5); - } - - @Test - public void nongreedyAlgorithmTest() throws Exception { - NonGreedyAlgorithm nga = new NonGreedyAlgorithm(prepareNetwork(), 0); - Assertions.assertThrows(Exception.class, () -> { - nga.findMostFollowersPath("root"); - }); - } - - @Test - public void nongreedyAlgorithmUnboundedTest() throws Exception { - SocialConnector sc = prepareNetwork(); - sc.switchCounter(); - NonGreedyAlgorithm nga = new NonGreedyAlgorithm(sc, 0); - assertEquals(nga.findMostFollowersPath("root"), 6); - } - -} \ No newline at end of file diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStreamUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStreamUnitTest.java new file mode 100644 index 0000000000..bcea4ebba8 --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStreamUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.algorithms.integerstreammedian; + +import org.junit.Test; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class MedianOfIntegerStreamUnitTest { + + @Test + public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach1() { + MedianOfIntegerStream mis = new MedianOfIntegerStream(); + for (Map.Entry e : testcaseFixture().entrySet()) { + mis.add(e.getKey()); + assertEquals(e.getValue(), (Double) mis.getMedian()); + } + } + + @Test + public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach2() { + MedianOfIntegerStream2 mis = new MedianOfIntegerStream2(); + for (Map.Entry e : testcaseFixture().entrySet()) { + mis.add(e.getKey()); + assertEquals(e.getValue(), (Double) mis.getMedian()); + } + } + + private Map testcaseFixture() { + return new LinkedHashMap() {{ + put(1, 1d); + put(7, 4d); + put(5, 5d); + put(8, 6d); + put(3, 5d); + put(9, 6d); + put(4, 5d); + }}; + } +} diff --git a/algorithms-miscellaneous-5/src/test/resources/input.json b/algorithms-miscellaneous-5/src/test/resources/input.json new file mode 100644 index 0000000000..0151f83618 --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/resources/input.json @@ -0,0 +1,41 @@ +{ + "nodes": 5, + "edges": 7, + "edgeList": [ + { + "first": 0, + "second": 1, + "weight": 8 + }, + { + "first": 0, + "second": 2, + "weight": 5 + }, + { + "first": 1, + "second": 2, + "weight": 9 + }, + { + "first": 1, + "second": 3, + "weight": 11 + }, + { + "first": 2, + "second": 3, + "weight": 15 + }, + { + "first": 2, + "second": 4, + "weight": 10 + }, + { + "first": 3, + "second": 4, + "weight": 7 + } + ] +} \ No newline at end of file diff --git a/algorithms-miscellaneous-6/README.md b/algorithms-miscellaneous-6/README.md new file mode 100644 index 0000000000..22ee51530f --- /dev/null +++ b/algorithms-miscellaneous-6/README.md @@ -0,0 +1,10 @@ +### Relevant Articles: + +- [Boruvka’s Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm) +- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent) +- [Kruskal’s Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal) +- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm) +- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences) +- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms) +- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher) +- More articles: [[<-- prev]](/../algorithms-miscellaneous-5) diff --git a/algorithms-miscellaneous-6/pom.xml b/algorithms-miscellaneous-6/pom.xml new file mode 100644 index 0000000000..0a0edcbb3f --- /dev/null +++ b/algorithms-miscellaneous-6/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + algorithms-miscellaneous-6 + 0.0.1-SNAPSHOT + algorithms-miscellaneous-6 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.google.guava + guava + ${guava.version} + + + org.junit.platform + junit-platform-commons + ${junit.platform.version} + + + org.assertj + assertj-core + ${org.assertj.core.version} + test + + + org.projectlombok + lombok + ${lombok.version} + provided + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + + + 28.1-jre + 3.9.0 + 1.6.0 + 3.6.1 + + + diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDeque.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDeque.java new file mode 100644 index 0000000000..4c220b4047 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDeque.java @@ -0,0 +1,36 @@ +package com.baeldung.algorithms.balancedbrackets; + +import java.util.Deque; +import java.util.LinkedList; + +public class BalancedBracketsUsingDeque { + + public boolean isBalanced(String str) { + if (null == str || ((str.length() % 2) != 0)) { + return false; + } else { + char[] ch = str.toCharArray(); + for (char c : ch) { + if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) { + return false; + } + + } + } + + Deque deque = new LinkedList<>(); + for (char ch : str.toCharArray()) { + if (ch == '{' || ch == '[' || ch == '(') { + deque.addFirst(ch); + } else { + if (!deque.isEmpty() && ((deque.peekFirst() == '{' && ch == '}') || (deque.peekFirst() == '[' && ch == ']') || (deque.peekFirst() == '(' && ch == ')'))) { + deque.removeFirst(); + } else { + return false; + } + } + } + + return true; + } +} \ No newline at end of file diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingString.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingString.java new file mode 100644 index 0000000000..0418efbe79 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingString.java @@ -0,0 +1,27 @@ +package com.baeldung.algorithms.balancedbrackets; + +public class BalancedBracketsUsingString { + + public boolean isBalanced(String str) { + if (null == str || ((str.length() % 2) != 0)) { + return false; + } else { + char[] ch = str.toCharArray(); + for (char c : ch) { + if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) { + return false; + } + + } + } + + while (str.contains("()") || str.contains("[]") || str.contains("{}")) { + str = str.replaceAll("\\(\\)", "") + .replaceAll("\\[\\]", "") + .replaceAll("\\{\\}", ""); + } + return (str.length() == 0); + + } + +} \ No newline at end of file diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/BoruvkaMST.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/BoruvkaMST.java new file mode 100644 index 0000000000..7dae21648c --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/BoruvkaMST.java @@ -0,0 +1,84 @@ +package com.baeldung.algorithms.boruvka; + +import com.google.common.graph.EndpointPair; +import com.google.common.graph.MutableValueGraph; +import com.google.common.graph.ValueGraphBuilder; + +public class BoruvkaMST { + + private static MutableValueGraph mst = ValueGraphBuilder.undirected() + .build(); + private static int totalWeight; + + public BoruvkaMST(MutableValueGraph graph) { + + int size = graph.nodes().size(); + + UnionFind uf = new UnionFind(size); + + // repeat at most log N times or until we have N-1 edges + for (int t = 1; t < size && mst.edges().size() < size - 1; t = t + t) { + + EndpointPair[] closestEdgeArray = new EndpointPair[size]; + + // foreach tree in graph, find closest edge + for (EndpointPair edge : graph.edges()) { + int u = edge.nodeU(); + int v = edge.nodeV(); + int uParent = uf.find(u); + int vParent = uf.find(v); + if (uParent == vParent) { + continue; // same tree + } + + int weight = graph.edgeValueOrDefault(u, v, 0); + + if (closestEdgeArray[uParent] == null) { + closestEdgeArray[uParent] = edge; + } + if (closestEdgeArray[vParent] == null) { + closestEdgeArray[vParent] = edge; + } + + int uParentWeight = graph.edgeValueOrDefault(closestEdgeArray[uParent].nodeU(), closestEdgeArray[uParent].nodeV(), 0); + int vParentWeight = graph.edgeValueOrDefault(closestEdgeArray[vParent].nodeU(), closestEdgeArray[vParent].nodeV(), 0); + + if (weight < uParentWeight) { + closestEdgeArray[uParent] = edge; + } + if (weight < vParentWeight) { + closestEdgeArray[vParent] = edge; + } + } + + // add newly discovered edges to MST + for (int i = 0; i < size; i++) { + EndpointPair edge = closestEdgeArray[i]; + if (edge != null) { + int u = edge.nodeU(); + int v = edge.nodeV(); + int weight = graph.edgeValueOrDefault(u, v, 0); + // don't add the same edge twice + if (uf.find(u) != uf.find(v)) { + mst.putEdgeValue(u, v, weight); + totalWeight += weight; + uf.union(u, v); + } + } + } + } + } + + public MutableValueGraph getMST() { + return mst; + } + + public int getTotalWeight() { + return totalWeight; + } + + public String toString() { + return "MST: " + mst.toString() + " | Total Weight: " + totalWeight; + } + +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/UnionFind.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/UnionFind.java new file mode 100644 index 0000000000..33c9c4a4c8 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/UnionFind.java @@ -0,0 +1,39 @@ +package com.baeldung.algorithms.boruvka; + +public class UnionFind { + private int[] parents; + private int[] ranks; + + public UnionFind(int n) { + parents = new int[n]; + ranks = new int[n]; + for (int i = 0; i < n; i++) { + parents[i] = i; + ranks[i] = 0; + } + } + + public int find(int u) { + while (u != parents[u]) { + u = parents[u]; + } + return u; + } + + public void union(int u, int v) { + int uParent = find(u); + int vParent = find(v); + if (uParent == vParent) { + return; + } + + if (ranks[uParent] < ranks[vParent]) { + parents[uParent] = vParent; + } else if (ranks[uParent] > ranks[vParent]) { + parents[vParent] = uParent; + } else { + parents[vParent] = uParent; + ranks[uParent]++; + } + } +} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/caesarcipher/CaesarCipher.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/caesarcipher/CaesarCipher.java similarity index 100% rename from algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/caesarcipher/CaesarCipher.java rename to algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/caesarcipher/CaesarCipher.java diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/gradientdescent/GradientDescent.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/gradientdescent/GradientDescent.java new file mode 100644 index 0000000000..c5db3a4a06 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/gradientdescent/GradientDescent.java @@ -0,0 +1,33 @@ +package com.baeldung.algorithms.gradientdescent; + +import java.util.function.Function; + +public class GradientDescent { + + private final double precision = 0.000001; + + public double findLocalMinimum(Function f, double initialX) { + double stepCoefficient = 0.1; + double previousStep = 1.0; + double currentX = initialX; + double previousX = initialX; + double previousY = f.apply(previousX); + int iter = 100; + + currentX += stepCoefficient * previousY; + + while (previousStep > precision && iter > 0) { + iter--; + double currentY = f.apply(currentX); + if (currentY > previousY) { + stepCoefficient = -stepCoefficient / 2; + } + previousX = currentX; + currentX += stepCoefficient * previousY; + previousY = currentY; + previousStep = StrictMath.abs(currentX - previousX); + } + return currentX; + } + +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/Follower.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/Follower.java new file mode 100644 index 0000000000..e142f10eb4 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/Follower.java @@ -0,0 +1,20 @@ +package com.baeldung.algorithms.greedy; + +import lombok.Getter; + +public class Follower { + + @Getter String username; + @Getter long count; + + public Follower(String username, long count) { + super(); + this.username = username; + this.count = count; + } + + @Override + public String toString() { + return "User: " + username + ", Followers: " + count + "\n\r" ; + } +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/FollowersPath.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/FollowersPath.java new file mode 100644 index 0000000000..2319c14af8 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/FollowersPath.java @@ -0,0 +1,44 @@ +package com.baeldung.algorithms.greedy; + +import java.util.ArrayList; +import java.util.List; + +public class FollowersPath { + + private List accounts; + private long count; + + public FollowersPath() { + super(); + this.accounts = new ArrayList<>(); + } + + public List getAccounts() { + return accounts; + } + public long getCount() { + return count; + } + + public void addFollower(String username, long count) { + accounts.add(new Follower(username, count)); + } + + public void addCount(long count) { + this.count += count; + } + + @Override + public String toString() { + String details = ""; + for(Follower a : accounts) { + details+=a.toString() + ", "; + } + + return "Total: " + count + ", \n\r" + + " Details: { " + "\n\r" + + details + "\n\r" + + " }"; + } + +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java new file mode 100644 index 0000000000..51f0e3fa6a --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java @@ -0,0 +1,43 @@ +package com.baeldung.algorithms.greedy; + +import java.util.List; + +public class GreedyAlgorithm { + + int currentLevel = 0; + final int maxLevel = 3; + SocialConnector sc; + FollowersPath fp; + + public GreedyAlgorithm(SocialConnector sc) { + super(); + this.sc = sc; + this.fp = new FollowersPath(); + } + + public long findMostFollowersPath(String account) { + long max = 0; + SocialUser toFollow = null; + + List followers = sc.getFollowers(account); + for (SocialUser el : followers) { + long followersCount = el.getFollowersCount(); + if (followersCount > max) { + toFollow = el; + max = followersCount; + } + } + + if (currentLevel < maxLevel - 1) { + currentLevel++; + max += findMostFollowersPath(toFollow.getUsername()); + return max; + } else { + return max; + } + } + + public FollowersPath getFollowers() { + return fp; + } +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java new file mode 100644 index 0000000000..af274a385e --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java @@ -0,0 +1,43 @@ +package com.baeldung.algorithms.greedy; + +import java.util.List; + +public class NonGreedyAlgorithm { + + int currentLevel = 0; + final int maxLevel = 3; + SocialConnector tc; + + public NonGreedyAlgorithm(SocialConnector tc, int level) { + super(); + this.tc = tc; + this.currentLevel = level; + } + + public long findMostFollowersPath(String account) { + List followers = tc.getFollowers(account); + long total = currentLevel > 0 ? followers.size() : 0; + + if (currentLevel < maxLevel ) { + currentLevel++; + + long[] count = new long[followers.size()]; + int i = 0; + for (SocialUser el : followers) { + NonGreedyAlgorithm sub = new NonGreedyAlgorithm(tc, currentLevel); + count[i] = sub.findMostFollowersPath(el.getUsername()); + i++; + } + + long max = 0; + for (; i > 0; i--) { + if (count[i-1] > max ) + max = count[i-1]; + } + + return total + max; + } + + return total; + } +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java new file mode 100644 index 0000000000..508e18c105 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java @@ -0,0 +1,36 @@ +package com.baeldung.algorithms.greedy; + +import java.util.ArrayList; +import java.util.List; + +import lombok.Getter; +import lombok.Setter; + +public class SocialConnector { + private boolean isCounterEnabled = true; + private int counter = 4; + @Getter @Setter List users; + + public SocialConnector() { + users = new ArrayList<>(); + } + + public boolean switchCounter() { + this.isCounterEnabled = !this.isCounterEnabled; + return this.isCounterEnabled; + } + + public List getFollowers(String account) { + if (counter < 0) + throw new IllegalStateException ("API limit reached"); + else { + if(this.isCounterEnabled) counter--; + for(SocialUser user : users) { + if (user.getUsername().equals(account)) { + return user.getFollowers(); + } + } + } + return new ArrayList<>(); + } +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/SocialUser.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/SocialUser.java new file mode 100644 index 0000000000..bc8679da79 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/SocialUser.java @@ -0,0 +1,38 @@ +package com.baeldung.algorithms.greedy; + +import java.util.ArrayList; +import java.util.List; + +import lombok.Getter; + +public class SocialUser { + + @Getter private String username; + @Getter private List followers; + + public SocialUser(String username) { + super(); + this.username = username; + this.followers = new ArrayList<>(); + } + + public SocialUser(String username, List followers) { + super(); + this.username = username; + this.followers = followers; + } + + public long getFollowersCount() { + return followers.size(); + } + + public void addFollowers(List followers) { + this.followers.addAll(followers); + } + + @Override + public boolean equals(Object obj) { + return ((SocialUser) obj).getUsername().equals(username); + } + +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/CycleDetector.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/CycleDetector.java new file mode 100644 index 0000000000..dec0bcdd85 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/CycleDetector.java @@ -0,0 +1,72 @@ +package com.baeldung.algorithms.kruskal; + +import java.util.ArrayList; +import java.util.List; + +public class CycleDetector { + + List nodes; + + public CycleDetector(int totalNodes) { + initDisjointSets(totalNodes); + } + + public boolean detectCycle(Integer u, Integer v) { + Integer rootU = pathCompressionFind(u); + Integer rootV = pathCompressionFind(v); + if (rootU.equals(rootV)) { + return true; + } + unionByRank(rootU, rootV); + return false; + } + + private void initDisjointSets(int totalNodes) { + nodes = new ArrayList<>(totalNodes); + for (int i = 0; i < totalNodes; i++) { + nodes.add(new DisjointSetInfo(i)); + } + } + + private Integer find(Integer node) { + Integer parent = nodes.get(node).getParentNode(); + if (parent.equals(node)) { + return node; + } else { + return find(parent); + } + } + + private Integer pathCompressionFind(Integer node) { + DisjointSetInfo setInfo = nodes.get(node); + Integer parent = setInfo.getParentNode(); + if (parent.equals(node)) { + return node; + } else { + Integer parentNode = find(parent); + setInfo.setParentNode(parentNode); + return parentNode; + } + } + + private void union(Integer rootU, Integer rootV) { + DisjointSetInfo setInfoU = nodes.get(rootU); + setInfoU.setParentNode(rootV); + } + + private void unionByRank(int rootU, int rootV) { + DisjointSetInfo setInfoU = nodes.get(rootU); + DisjointSetInfo setInfoV = nodes.get(rootV); + int rankU = setInfoU.getRank(); + int rankV = setInfoV.getRank(); + if (rankU < rankV) { + setInfoU.setParentNode(rootV); + } else { + setInfoV.setParentNode(rootU); + if (rankU == rankV) { + setInfoU.setRank(rankU + 1); + } + } + } + +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/DisjointSetInfo.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/DisjointSetInfo.java new file mode 100644 index 0000000000..ecdc42587a --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/DisjointSetInfo.java @@ -0,0 +1,28 @@ +package com.baeldung.algorithms.kruskal; + +public class DisjointSetInfo { + + private Integer parentNode; + private int rank; + + DisjointSetInfo(Integer nodeNumber) { + setParentNode(nodeNumber); + setRank(1); + } + + public Integer getParentNode() { + return parentNode; + } + + public void setParentNode(Integer parentNode) { + this.parentNode = parentNode; + } + + public int getRank() { + return rank; + } + + public void setRank(int rank) { + this.rank = rank; + } +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/Kruskal.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/Kruskal.java new file mode 100644 index 0000000000..da405679d1 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/Kruskal.java @@ -0,0 +1,53 @@ +package com.baeldung.algorithms.kruskal; + +import com.google.common.graph.EndpointPair; +import com.google.common.graph.MutableValueGraph; +import com.google.common.graph.ValueGraph; +import com.google.common.graph.ValueGraphBuilder; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Set; + +public class Kruskal { + + public ValueGraph minSpanningTree(ValueGraph graph) { + + return spanningTree(graph, true); + } + + public ValueGraph maxSpanningTree(ValueGraph graph) { + return spanningTree(graph, false); + } + + private ValueGraph spanningTree(ValueGraph graph, boolean minSpanningTree) { + Set> edges = graph.edges(); + List> edgeList = new ArrayList<>(edges); + + if (minSpanningTree) { + edgeList.sort(Comparator.comparing(e -> graph.edgeValue(e).get())); + } else { + edgeList.sort(Collections.reverseOrder(Comparator.comparing(e -> graph.edgeValue(e).get()))); + } + + int totalNodes = graph.nodes().size(); + CycleDetector cycleDetector = new CycleDetector(totalNodes); + int edgeCount = 0; + + MutableValueGraph spanningTree = ValueGraphBuilder.undirected().build(); + for (EndpointPair edge : edgeList) { + if (cycleDetector.detectCycle(edge.nodeU(), edge.nodeV())) { + continue; + } + spanningTree.putEdgeValue(edge.nodeU(), edge.nodeV(), graph.edgeValue(edge).get()); + edgeCount++; + if (edgeCount == totalNodes - 1) { + break; + } + } + return spanningTree; + } + +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/minheapmerge/HeapNode.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/minheapmerge/HeapNode.java new file mode 100644 index 0000000000..e2e41baf4d --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/minheapmerge/HeapNode.java @@ -0,0 +1,13 @@ +package com.baeldung.algorithms.minheapmerge; + +public class HeapNode { + + int element; + int arrayIndex; + int nextElementIndex = 1; + + public HeapNode(int element, int arrayIndex) { + this.element = element; + this.arrayIndex = arrayIndex; + } +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeap.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeap.java new file mode 100644 index 0000000000..0217480e9e --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeap.java @@ -0,0 +1,88 @@ +package com.baeldung.algorithms.minheapmerge; + +public class MinHeap { + + HeapNode[] heapNodes; + + public MinHeap(HeapNode heapNodes[]) { + this.heapNodes = heapNodes; + heapifyFromLastLeafsParent(); + } + + void heapifyFromLastLeafsParent() { + int lastLeafsParentIndex = getParentNodeIndex(heapNodes.length); + while (lastLeafsParentIndex >= 0) { + heapify(lastLeafsParentIndex); + lastLeafsParentIndex--; + } + } + + void heapify(int index) { + int leftNodeIndex = getLeftNodeIndex(index); + int rightNodeIndex = getRightNodeIndex(index); + int smallestElementIndex = index; + if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) { + smallestElementIndex = leftNodeIndex; + } + if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) { + smallestElementIndex = rightNodeIndex; + } + if (smallestElementIndex != index) { + swap(index, smallestElementIndex); + heapify(smallestElementIndex); + } + } + + int getParentNodeIndex(int index) { + return (index - 1) / 2; + } + + int getLeftNodeIndex(int index) { + return (2 * index + 1); + } + + int getRightNodeIndex(int index) { + return (2 * index + 2); + } + + HeapNode getRootNode() { + return heapNodes[0]; + } + + void heapifyFromRoot() { + heapify(0); + } + + void swap(int i, int j) { + HeapNode temp = heapNodes[i]; + heapNodes[i] = heapNodes[j]; + heapNodes[j] = temp; + } + + static int[] merge(int[][] array) { + HeapNode[] heapNodes = new HeapNode[array.length]; + int resultingArraySize = 0; + + for (int i = 0; i < array.length; i++) { + HeapNode node = new HeapNode(array[i][0], i); + heapNodes[i] = node; + resultingArraySize += array[i].length; + } + + MinHeap minHeap = new MinHeap(heapNodes); + int[] resultingArray = new int[resultingArraySize]; + + for (int i = 0; i < resultingArraySize; i++) { + HeapNode root = minHeap.getRootNode(); + resultingArray[i] = root.element; + + if (root.nextElementIndex < array[root.arrayIndex].length) { + root.element = array[root.arrayIndex][root.nextElementIndex++]; + } else { + root.element = Integer.MAX_VALUE; + } + minHeap.heapifyFromRoot(); + } + return resultingArray; + } +} diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java new file mode 100644 index 0000000000..964c1ce11a --- /dev/null +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.algorithms.balancedbrackets; + +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BalancedBracketsUsingDequeUnitTest { + private BalancedBracketsUsingDeque balancedBracketsUsingDeque; + + @Before + public void setup() { + balancedBracketsUsingDeque = new BalancedBracketsUsingDeque(); + } + + @Test + public void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced(null); + assertThat(result).isFalse(); + } + + @Test + public void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingDeque.isBalanced(""); + assertThat(result).isTrue(); + } + + @Test + public void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced("abc[](){}"); + assertThat(result).isFalse(); + } + + @Test + public void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced("{[(])}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingDeque.isBalanced("{[()]}"); + assertThat(result).isTrue(); + } + + @Test + public void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingDeque.isBalanced("{{[[(())]]}}"); + assertThat(result).isTrue(); + } + + @Test + public void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingDeque.isBalanced("{{([])}}"); + assertThat(result).isTrue(); + } + + @Test + public void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced("{{)[](}}"); + assertThat(result).isFalse(); + } + +} \ No newline at end of file diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java new file mode 100644 index 0000000000..69ce42b0f1 --- /dev/null +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.algorithms.balancedbrackets; + +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BalancedBracketsUsingStringUnitTest { + private BalancedBracketsUsingString balancedBracketsUsingString; + + @Before + public void setup() { + balancedBracketsUsingString = new BalancedBracketsUsingString(); + } + + @Test + public void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced(null); + assertThat(result).isFalse(); + } + + @Test + public void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingString.isBalanced(""); + assertThat(result).isTrue(); + } + + @Test + public void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced("abc[](){}"); + assertThat(result).isFalse(); + } + + @Test + public void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced("{[(])}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingString.isBalanced("{[()]}"); + assertThat(result).isTrue(); + } + + @Test + public void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingString.isBalanced("{{[[(())]]}}"); + assertThat(result).isTrue(); + } + + @Test + public void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingString.isBalanced("{{([])}}"); + assertThat(result).isTrue(); + } + + @Test + public void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced("{{)[](}}"); + assertThat(result).isFalse(); + } + +} \ No newline at end of file diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java new file mode 100644 index 0000000000..e61e1e668d --- /dev/null +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.algorithms.boruvka; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +import com.google.common.graph.MutableValueGraph; +import com.google.common.graph.ValueGraphBuilder; + +public class BoruvkaUnitTest { + + private MutableValueGraph graph; + + @Before + public void setup() { + graph = ValueGraphBuilder.undirected() + .build(); + graph.putEdgeValue(0, 1, 8); + graph.putEdgeValue(0, 2, 5); + graph.putEdgeValue(1, 2, 9); + graph.putEdgeValue(1, 3, 11); + graph.putEdgeValue(2, 3, 15); + graph.putEdgeValue(2, 4, 10); + graph.putEdgeValue(3, 4, 7); + } + + @Test + public void givenInputGraph_whenBoruvkaPerformed_thenMinimumSpanningTree() { + BoruvkaMST boruvkaMST = new BoruvkaMST(graph); + MutableValueGraph mst = boruvkaMST.getMST(); + + assertEquals(30, boruvkaMST.getTotalWeight()); + assertEquals(4, mst.edges().size()); + } + +} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/caesarcipher/CaesarCipherUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/caesarcipher/CaesarCipherUnitTest.java similarity index 100% rename from algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/caesarcipher/CaesarCipherUnitTest.java rename to algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/caesarcipher/CaesarCipherUnitTest.java diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java new file mode 100644 index 0000000000..34d3e188f2 --- /dev/null +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.algorithms.gradientdescent; + +import static org.junit.Assert.assertTrue; + +import java.util.function.Function; + +import org.junit.Test; + +public class GradientDescentUnitTest { + + @Test + public void givenFunction_whenStartingPointIsOne_thenLocalMinimumIsFound() { + Function df = x -> + StrictMath.abs(StrictMath.pow(x, 3)) - (3 * StrictMath.pow(x, 2)) + x; + GradientDescent gd = new GradientDescent(); + double res = gd.findLocalMinimum(df, 1); + assertTrue(res > 1.78); + assertTrue(res < 1.84); + } +} diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java new file mode 100644 index 0000000000..a503b006de --- /dev/null +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.algorithms.greedy; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class GreedyAlgorithmUnitTest { + + private SocialConnector prepareNetwork() { + SocialConnector sc = new SocialConnector(); + SocialUser root = new SocialUser("root"); + SocialUser child1 = new SocialUser("child1"); + SocialUser child2 = new SocialUser("child2"); + SocialUser child3 = new SocialUser("child3"); + SocialUser child21 = new SocialUser("child21"); + SocialUser child211 = new SocialUser("child211"); + SocialUser child2111 = new SocialUser("child2111"); + SocialUser child31 = new SocialUser("child31"); + SocialUser child311 = new SocialUser("child311"); + SocialUser child3111 = new SocialUser("child3111"); + child211.addFollowers(Arrays.asList(new SocialUser[]{child2111})); + child311.addFollowers(Arrays.asList(new SocialUser[]{child3111})); + child21.addFollowers(Arrays.asList(new SocialUser[]{child211})); + child31.addFollowers(Arrays.asList(new SocialUser[]{child311, + new SocialUser("child312"), new SocialUser("child313"), new SocialUser("child314")})); + child1.addFollowers(Arrays.asList(new SocialUser[]{new SocialUser("child11"), new SocialUser("child12")})); + child2.addFollowers(Arrays.asList(new SocialUser[]{child21, new SocialUser("child22"), new SocialUser("child23")})); + child3.addFollowers(Arrays.asList(new SocialUser[]{child31})); + root.addFollowers(Arrays.asList(new SocialUser[]{child1, child2, child3})); + sc.setUsers(Arrays.asList(new SocialUser[]{root, child1, child2, child3, child21, child31, child311, child211})); + return sc; + } + + @Test + public void greedyAlgorithmTest() { + GreedyAlgorithm ga = new GreedyAlgorithm(prepareNetwork()); + assertEquals(ga.findMostFollowersPath("root"), 5); + } + + @Test + public void nongreedyAlgorithmTest() { + NonGreedyAlgorithm nga = new NonGreedyAlgorithm(prepareNetwork(), 0); + Assertions.assertThrows(IllegalStateException.class, () -> { + nga.findMostFollowersPath("root"); + }); + } + + @Test + public void nongreedyAlgorithmUnboundedTest() { + SocialConnector sc = prepareNetwork(); + sc.switchCounter(); + NonGreedyAlgorithm nga = new NonGreedyAlgorithm(sc, 0); + assertEquals(nga.findMostFollowersPath("root"), 6); + } +} \ No newline at end of file diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/kruskal/KruskalUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/kruskal/KruskalUnitTest.java new file mode 100644 index 0000000000..a7206c6cd0 --- /dev/null +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/kruskal/KruskalUnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.algorithms.kruskal; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import com.google.common.graph.MutableValueGraph; +import com.google.common.graph.ValueGraph; +import com.google.common.graph.ValueGraphBuilder; +import com.baeldung.algorithms.kruskal.Kruskal; + +public class KruskalUnitTest { + + private MutableValueGraph graph; + + @Before + public void setup() { + graph = ValueGraphBuilder.undirected().build(); + graph.putEdgeValue(0, 1, 8.0); + graph.putEdgeValue(0, 2, 5.0); + graph.putEdgeValue(1, 2, 9.0); + graph.putEdgeValue(1, 3, 11.0); + graph.putEdgeValue(2, 3, 15.0); + graph.putEdgeValue(2, 4, 10.0); + graph.putEdgeValue(3, 4, 7.0); + } + + @Test + public void givenGraph_whenMinimumSpanningTree_thenOutputCorrectResult() { + final Kruskal kruskal = new Kruskal(); + ValueGraph spanningTree = kruskal.minSpanningTree(graph); + + assertTrue(spanningTree.hasEdgeConnecting(0, 1)); + assertTrue(spanningTree.hasEdgeConnecting(0, 2)); + assertTrue(spanningTree.hasEdgeConnecting(2, 4)); + assertTrue(spanningTree.hasEdgeConnecting(3, 4)); + assertEquals(graph.edgeValue(0, 1), spanningTree.edgeValue(0, 1)); + assertEquals(graph.edgeValue(0, 2), spanningTree.edgeValue(0, 2)); + assertEquals(graph.edgeValue(2, 4), spanningTree.edgeValue(2, 4)); + assertEquals(graph.edgeValue(3, 4), spanningTree.edgeValue(3, 4)); + + assertFalse(spanningTree.hasEdgeConnecting(1, 2)); + assertFalse(spanningTree.hasEdgeConnecting(1, 3)); + assertFalse(spanningTree.hasEdgeConnecting(2, 3)); + } + + @Test + public void givenGraph_whenMaximumSpanningTree_thenOutputCorrectResult() { + final Kruskal kruskal = new Kruskal(); + ValueGraph spanningTree = kruskal.maxSpanningTree(graph); + + assertTrue(spanningTree.hasEdgeConnecting(0, 1)); + assertTrue(spanningTree.hasEdgeConnecting(1, 3)); + assertTrue(spanningTree.hasEdgeConnecting(2, 3)); + assertTrue(spanningTree.hasEdgeConnecting(2, 4)); + assertEquals(graph.edgeValue(0, 1), spanningTree.edgeValue(0, 1)); + assertEquals(graph.edgeValue(1, 3), spanningTree.edgeValue(1, 3)); + assertEquals(graph.edgeValue(2, 3), spanningTree.edgeValue(2, 3)); + assertEquals(graph.edgeValue(2, 4), spanningTree.edgeValue(2, 4)); + + assertFalse(spanningTree.hasEdgeConnecting(0, 2)); + assertFalse(spanningTree.hasEdgeConnecting(1, 2)); + assertFalse(spanningTree.hasEdgeConnecting(3, 4)); + } +} diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java new file mode 100644 index 0000000000..f84c860dcc --- /dev/null +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.algorithms.minheapmerge; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class MinHeapUnitTest { + + private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } }; + private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 }; + + @Test + public void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() { + int[] resultArray = MinHeap.merge(inputArray); + + assertThat(resultArray.length, is(equalTo(10))); + assertThat(resultArray, is(equalTo(expectedArray))); + } + +} diff --git a/algorithms-searching/README.md b/algorithms-searching/README.md index d86c3e3de8..aed3c7d21f 100644 --- a/algorithms-searching/README.md +++ b/algorithms-searching/README.md @@ -9,3 +9,5 @@ This module contains articles about searching algorithms. - [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search) - [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms) - [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search) +- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search) +- [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree) diff --git a/algorithms-searching/pom.xml b/algorithms-searching/pom.xml index da32874a18..80443155ff 100644 --- a/algorithms-searching/pom.xml +++ b/algorithms-searching/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 algorithms-searching 0.0.1-SNAPSHOT diff --git a/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/Point.java b/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/Point.java new file mode 100644 index 0000000000..f61ee87f7d --- /dev/null +++ b/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/Point.java @@ -0,0 +1,24 @@ +package com.baeldung.algorithms.quadtree; + +public class Point { + private float x; + private float y; + + public Point(float x, float y) { + this.x = x; + this.y = y; + } + + public float getX() { + return x; + } + + public float getY() { + return y; + } + + @Override + public String toString() { + return "[" + x + " , " + y + "]"; + } +} diff --git a/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/QuadTree.java b/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/QuadTree.java new file mode 100644 index 0000000000..bb3cf029b1 --- /dev/null +++ b/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/QuadTree.java @@ -0,0 +1,109 @@ +package com.baeldung.algorithms.quadtree; + +import java.util.ArrayList; +import java.util.List; + +public class QuadTree { + private static final int MAX_POINTS = 3; + private Region area; + private List points = new ArrayList<>(); + private List quadTrees = new ArrayList<>(); + private StringBuilder searchTraversePath; + + public QuadTree(Region area) { + this.area = area; + } + + public boolean addPoint(Point point) { + if (this.area.containsPoint(point)) { + if (this.points.size() < MAX_POINTS) { + this.points.add(point); + return true; + } else { + if (this.quadTrees.size() == 0) { + createQuadrants(); + } + return addPointToOneQuadrant(point); + } + } + return false; + } + + private boolean addPointToOneQuadrant(Point point) { + boolean isPointAdded; + for (int i = 0; i < 4; i++) { + isPointAdded = this.quadTrees.get(i) + .addPoint(point); + if (isPointAdded) + return true; + } + return false; + } + + private void createQuadrants() { + Region region; + for (int i = 0; i < 4; i++) { + region = this.area.getQuadrant(i); + quadTrees.add(new QuadTree(region)); + } + } + + public List search(Region searchRegion, List matches, String depthIndicator) { + searchTraversePath = new StringBuilder(); + if (matches == null) { + matches = new ArrayList(); + searchTraversePath.append(depthIndicator) + .append("Search Boundary =") + .append(searchRegion) + .append("\n"); + } + if (!this.area.doesOverlap(searchRegion)) { + return matches; + } else { + for (Point point : points) { + if (searchRegion.containsPoint(point)) { + searchTraversePath.append(depthIndicator) + .append("Found match " + point) + .append("\n"); + matches.add(point); + } + } + if (this.quadTrees.size() > 0) { + for (int i = 0; i < 4; i++) { + searchTraversePath.append(depthIndicator) + .append("Q") + .append(i) + .append("-->") + .append(quadTrees.get(i).area) + .append("\n"); + quadTrees.get(i) + .search(searchRegion, matches, depthIndicator + "\t"); + this.searchTraversePath.append(quadTrees.get(i) + .printSearchTraversePath()); + } + } + } + return matches; + } + + public String printTree(String depthIndicator) { + String str = ""; + if (depthIndicator == "") { + str += "Root-->" + area.toString() + "\n"; + } + + for (Point point : points) { + str += depthIndicator + point.toString() + "\n"; + } + for (int i = 0; i < quadTrees.size(); i++) { + str += depthIndicator + "Q" + String.valueOf(i) + "-->" + quadTrees.get(i).area.toString() + "\n"; + str += quadTrees.get(i) + .printTree(depthIndicator + "\t"); + } + return str; + } + + public String printSearchTraversePath() { + return searchTraversePath.toString(); + } +} diff --git a/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/Region.java b/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/Region.java new file mode 100644 index 0000000000..600711c4ae --- /dev/null +++ b/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/Region.java @@ -0,0 +1,85 @@ +package com.baeldung.algorithms.quadtree; + +public class Region { + private float x1; + private float y1; + private float x2; + private float y2; + + public Region(float x1, float y1, float x2, float y2) { + if (x1 >= x2 || y1 >= y2) + throw new IllegalArgumentException("(x1,y1) should be lesser than (x2,y2)"); + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + } + + public Region getQuadrant(int quadrantIndex) { + float quadrantWidth = (this.x2 - this.x1) / 2; + float quadrantHeight = (this.y2 - this.y1) / 2; + + // 0=SW, 1=NW, 2=NE, 3=SE + switch (quadrantIndex) { + case 0: + return new Region(x1, y1, x1 + quadrantWidth, y1 + quadrantHeight); + case 1: + return new Region(x1, y1 + quadrantHeight, x1 + quadrantWidth, y2); + case 2: + return new Region(x1 + quadrantWidth, y1 + quadrantHeight, x2, y2); + case 3: + return new Region(x1 + quadrantWidth, y1, x2, y1 + quadrantHeight); + } + return null; + } + + public boolean containsPoint(Point point) { + // Consider left and top side to be inclusive for points on border + return point.getX() >= this.x1 + && point.getX() < this.x2 + && point.getY() >= this.y1 + && point.getY() < this.y2; + } + + public boolean doesOverlap(Region testRegion) { + // Is test region completely to left of my region? + if (testRegion.getX2() < this.getX1()) { + return false; + } + // Is test region completely to right of my region? + if (testRegion.getX1() > this.getX2()) { + return false; + } + // Is test region completely above my region? + if (testRegion.getY1() > this.getY2()) { + return false; + } + // Is test region completely below my region? + if (testRegion.getY2() < this.getY1()) { + return false; + } + return true; + } + + @Override + public String toString() { + return "[Region (x1=" + x1 + ", y1=" + y1 + "), (x2=" + x2 + ", y2=" + y2 + ")]"; + } + + public float getX1() { + return x1; + } + + public float getY1() { + return y1; + } + + public float getX2() { + return x2; + } + + public float getY2() { + return y2; + } + +} diff --git a/algorithms-searching/src/main/java/com/baeldung/algorithms/suffixtree/Node.java b/algorithms-searching/src/main/java/com/baeldung/algorithms/suffixtree/Node.java new file mode 100644 index 0000000000..5a77b09753 --- /dev/null +++ b/algorithms-searching/src/main/java/com/baeldung/algorithms/suffixtree/Node.java @@ -0,0 +1,57 @@ +package com.baeldung.algorithms.suffixtree; + +import java.util.ArrayList; +import java.util.List; + +public class Node { + private String text; + private List children; + private int position; + + public Node(String word, int position) { + this.text = word; + this.position = position; + this.children = new ArrayList<>(); + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public int getPosition() { + return position; + } + + public void setPosition(int position) { + this.position = position; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + public String printTree(String depthIndicator) { + String str = ""; + String positionStr = position > -1 ? "[" + String.valueOf(position) + "]" : ""; + str += depthIndicator + text + positionStr + "\n"; + + for (int i = 0; i < children.size(); i++) { + str += children.get(i) + .printTree(depthIndicator + "\t"); + } + return str; + } + + @Override + public String toString() { + return printTree(""); + } +} \ No newline at end of file diff --git a/algorithms-searching/src/main/java/com/baeldung/algorithms/suffixtree/SuffixTree.java b/algorithms-searching/src/main/java/com/baeldung/algorithms/suffixtree/SuffixTree.java new file mode 100644 index 0000000000..eb58c2bfab --- /dev/null +++ b/algorithms-searching/src/main/java/com/baeldung/algorithms/suffixtree/SuffixTree.java @@ -0,0 +1,175 @@ +package com.baeldung.algorithms.suffixtree; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SuffixTree { + private static final Logger LOGGER = LoggerFactory.getLogger(SuffixTree.class); + private static final String WORD_TERMINATION = "$"; + private static final int POSITION_UNDEFINED = -1; + private Node root; + private String fullText; + + public SuffixTree(String text) { + root = new Node("", POSITION_UNDEFINED); + for (int i = 0; i < text.length(); i++) { + addSuffix(text.substring(i) + WORD_TERMINATION, i); + } + fullText = text; + } + + public List searchText(String pattern) { + LOGGER.info("Searching for pattern \"{}\"", pattern); + List result = new ArrayList<>(); + List nodes = getAllNodesInTraversePath(pattern, root, false); + + if (nodes.size() > 0) { + Node lastNode = nodes.get(nodes.size() - 1); + if (lastNode != null) { + List positions = getPositions(lastNode); + positions = positions.stream() + .sorted() + .collect(Collectors.toList()); + positions.forEach(m -> result.add((markPatternInText(m, pattern)))); + } + } + return result; + } + + private void addSuffix(String suffix, int position) { + LOGGER.info(">>>>>>>>>>>> Adding new suffix {}", suffix); + List nodes = getAllNodesInTraversePath(suffix, root, true); + if (nodes.size() == 0) { + addChildNode(root, suffix, position); + LOGGER.info("{}", printTree()); + } else { + Node lastNode = nodes.remove(nodes.size() - 1); + String newText = suffix; + if (nodes.size() > 0) { + String existingSuffixUptoLastNode = nodes.stream() + .map(a -> a.getText()) + .reduce("", String::concat); + + // Remove prefix from newText already included in parent + newText = newText.substring(existingSuffixUptoLastNode.length()); + } + extendNode(lastNode, newText, position); + LOGGER.info("{}", printTree()); + } + } + + private List getPositions(Node node) { + List positions = new ArrayList<>(); + if (node.getText() + .endsWith(WORD_TERMINATION)) { + positions.add(node.getPosition()); + } + for (int i = 0; i < node.getChildren() + .size(); i++) { + positions.addAll(getPositions(node.getChildren() + .get(i))); + } + return positions; + } + + private String markPatternInText(Integer startPosition, String pattern) { + String matchingTextLHS = fullText.substring(0, startPosition); + String matchingText = fullText.substring(startPosition, startPosition + pattern.length()); + String matchingTextRHS = fullText.substring(startPosition + pattern.length()); + return matchingTextLHS + "[" + matchingText + "]" + matchingTextRHS; + } + + private void addChildNode(Node parentNode, String text, int position) { + parentNode.getChildren() + .add(new Node(text, position)); + } + + private void extendNode(Node node, String newText, int position) { + String currentText = node.getText(); + String commonPrefix = getLongestCommonPrefix(currentText, newText); + + if (commonPrefix != currentText) { + String parentText = currentText.substring(0, commonPrefix.length()); + String childText = currentText.substring(commonPrefix.length()); + splitNodeToParentAndChild(node, parentText, childText); + } + + String remainingText = newText.substring(commonPrefix.length()); + addChildNode(node, remainingText, position); + } + + private void splitNodeToParentAndChild(Node parentNode, String parentNewText, String childNewText) { + Node childNode = new Node(childNewText, parentNode.getPosition()); + + if (parentNode.getChildren() + .size() > 0) { + while (parentNode.getChildren() + .size() > 0) { + childNode.getChildren() + .add(parentNode.getChildren() + .remove(0)); + } + } + + parentNode.getChildren() + .add(childNode); + parentNode.setText(parentNewText); + parentNode.setPosition(POSITION_UNDEFINED); + } + + private String getLongestCommonPrefix(String str1, String str2) { + int compareLength = Math.min(str1.length(), str2.length()); + for (int i = 0; i < compareLength; i++) { + if (str1.charAt(i) != str2.charAt(i)) { + return str1.substring(0, i); + } + } + return str1.substring(0, compareLength); + } + + private List getAllNodesInTraversePath(String pattern, Node startNode, boolean isAllowPartialMatch) { + List nodes = new ArrayList<>(); + for (int i = 0; i < startNode.getChildren() + .size(); i++) { + Node currentNode = startNode.getChildren() + .get(i); + String nodeText = currentNode.getText(); + if (pattern.charAt(0) == nodeText.charAt(0)) { + if (isAllowPartialMatch && pattern.length() <= nodeText.length()) { + nodes.add(currentNode); + return nodes; + } + + int compareLength = Math.min(nodeText.length(), pattern.length()); + for (int j = 1; j < compareLength; j++) { + if (pattern.charAt(j) != nodeText.charAt(j)) { + if (isAllowPartialMatch) { + nodes.add(currentNode); + } + return nodes; + } + } + + nodes.add(currentNode); + if (pattern.length() > compareLength) { + List nodes2 = getAllNodesInTraversePath(pattern.substring(compareLength), currentNode, isAllowPartialMatch); + if (nodes2.size() > 0) { + nodes.addAll(nodes2); + } else if (!isAllowPartialMatch) { + nodes.add(null); + } + } + return nodes; + } + } + return nodes; + } + + public String printTree() { + return root.printTree(""); + } +} diff --git a/algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java b/algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java new file mode 100644 index 0000000000..0b58ae9f14 --- /dev/null +++ b/algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.algorithms.quadtree; + +import org.junit.Assert; + +import java.util.List; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class QuadTreeSearchUnitTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(QuadTreeSearchUnitTest.class); + + private static QuadTree quadTree; + + @BeforeClass + public static void setUp() { + Region area = new Region(0, 0, 400, 400); + quadTree = new QuadTree(area); + + float[][] points = new float[][] { { 21, 25 }, { 55, 53 }, { 70, 318 }, { 98, 302 }, + { 49, 229 }, { 135, 229 }, { 224, 292 }, { 206, 321 }, { 197, 258 }, { 245, 238 } }; + + for (int i = 0; i < points.length; i++) { + Point point = new Point(points[i][0], points[i][1]); + quadTree.addPoint(point); + } + LOGGER.info("\n" + quadTree.printTree("")); + LOGGER.info("=============================================="); + } + + @Test + public void givenQuadTree_whenSearchingForRange_thenReturn1MatchingItem() { + Region searchArea = new Region(200, 200, 250, 250); + List result = quadTree.search(searchArea, null, ""); + LOGGER.info(result.toString()); + LOGGER.info(quadTree.printSearchTraversePath()); + + Assert.assertEquals(1, result.size()); + Assert.assertArrayEquals(new float[] { 245, 238 }, + new float[]{result.get(0).getX(), result.get(0).getY() }, 0); + } + + @Test + public void givenQuadTree_whenSearchingForRange_thenReturn2MatchingItems() { + Region searchArea = new Region(0, 0, 100, 100); + List result = quadTree.search(searchArea, null, ""); + LOGGER.info(result.toString()); + LOGGER.info(quadTree.printSearchTraversePath()); + + Assert.assertEquals(2, result.size()); + Assert.assertArrayEquals(new float[] { 21, 25 }, + new float[]{result.get(0).getX(), result.get(0).getY() }, 0); + Assert.assertArrayEquals(new float[] { 55, 53 }, + new float[]{result.get(1).getX(), result.get(1).getY() }, 0); + + } +} diff --git a/algorithms-searching/src/test/java/com/baeldung/algorithms/suffixtree/SuffixTreeUnitTest.java b/algorithms-searching/src/test/java/com/baeldung/algorithms/suffixtree/SuffixTreeUnitTest.java new file mode 100644 index 0000000000..ef4a05a9a1 --- /dev/null +++ b/algorithms-searching/src/test/java/com/baeldung/algorithms/suffixtree/SuffixTreeUnitTest.java @@ -0,0 +1,77 @@ +package com.baeldung.algorithms.suffixtree; + +import java.util.List; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SuffixTreeUnitTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(SuffixTreeUnitTest.class); + + private static SuffixTree suffixTree; + + @BeforeClass + public static void setUp() { + suffixTree = new SuffixTree("havanabanana"); + printTree(); + } + + @Test + public void givenSuffixTree_whenSearchingForA_thenReturn6Matches() { + List matches = suffixTree.searchText("a"); + matches.stream() + .forEach(m -> LOGGER.info(m)); + Assert.assertArrayEquals(new String[] { "h[a]vanabanana", "hav[a]nabanana", "havan[a]banana", "havanab[a]nana", "havanaban[a]na", "havanabanan[a]" }, matches.toArray()); + } + + @Test + public void givenSuffixTree_whenSearchingForNab_thenReturn1Match() { + List matches = suffixTree.searchText("nab"); + matches.stream() + .forEach(m -> LOGGER.info(m)); + Assert.assertArrayEquals(new String[] { "hava[nab]anana" }, matches.toArray()); + } + + @Test + public void givenSuffixTree_whenSearchingForNag_thenReturnNoMatches() { + List matches = suffixTree.searchText("nag"); + matches.stream() + .forEach(m -> LOGGER.info(m)); + Assert.assertArrayEquals(new String[] {}, matches.toArray()); + } + + @Test + public void givenSuffixTree_whenSearchingForBanana_thenReturn2Matches() { + List matches = suffixTree.searchText("ana"); + matches.stream() + .forEach(m -> LOGGER.info(m)); + Assert.assertArrayEquals(new String[] { "hav[ana]banana", "havanab[ana]na", "havanaban[ana]" }, matches.toArray()); + } + + @Test + public void givenSuffixTree_whenSearchingForNa_thenReturn4Matches() { + List matches = suffixTree.searchText("na"); + matches.stream() + .forEach(m -> LOGGER.info(m)); + Assert.assertArrayEquals(new String[] { "hava[na]banana", "havanaba[na]na", "havanabana[na]" }, matches.toArray()); + } + + @Test + public void givenSuffixTree_whenSearchingForX_thenReturnNoMatches() { + List matches = suffixTree.searchText("x"); + matches.stream() + .forEach(m -> LOGGER.info(m)); + Assert.assertArrayEquals(new String[] {}, matches.toArray()); + } + + private static void printTree() { + suffixTree.printTree(); + + LOGGER.info("\n" + suffixTree.printTree()); + LOGGER.info("=============================================="); + } +} diff --git a/java-math/.gitignore b/algorithms-sorting-2/.gitignore similarity index 100% rename from java-math/.gitignore rename to algorithms-sorting-2/.gitignore diff --git a/algorithms-sorting-2/README.md b/algorithms-sorting-2/README.md new file mode 100644 index 0000000000..71c9b8f86c --- /dev/null +++ b/algorithms-sorting-2/README.md @@ -0,0 +1,7 @@ +### Relevant Articles: + +- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) +- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) +- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting) +- [Partitioning and Sorting Arrays with Many Repeated Entries](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries) +- More articles: [[<-- prev]](/algorithms-sorting) diff --git a/algorithms-sorting-2/pom.xml b/algorithms-sorting-2/pom.xml new file mode 100644 index 0000000000..529474afda --- /dev/null +++ b/algorithms-sorting-2/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + algorithms-sorting-2 + 0.0.1-SNAPSHOT + algorithms-sorting-2 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter-api.version} + test + + + org.assertj + assertj-core + ${org.assertj.core.version} + test + + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + + + + + 3.6.1 + 3.9.0 + 1.11 + 5.3.1 + + + \ No newline at end of file diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bynumber/NaturalOrderComparators.java similarity index 94% rename from algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java rename to algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bynumber/NaturalOrderComparators.java index b177bd60fc..148a9a21f9 100644 --- a/algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java +++ b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bynumber/NaturalOrderComparators.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.sort.bynumber; +package com.baeldung.algorithms.bynumber; import java.util.Comparator; diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java similarity index 100% rename from algorithms-sorting/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java rename to algorithms-sorting-2/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java diff --git a/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/BentleyMcIlroyPartioning.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/BentleyMcIlroyPartioning.java new file mode 100644 index 0000000000..d005f2654c --- /dev/null +++ b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/BentleyMcIlroyPartioning.java @@ -0,0 +1,66 @@ +package com.baeldung.algorithms.quicksort; + +import static com.baeldung.algorithms.quicksort.SortingUtils.swap; + +public class BentleyMcIlroyPartioning { + + public static Partition partition(int input[], int begin, int end) { + int left = begin, right = end; + int leftEqualKeysCount = 0, rightEqualKeysCount = 0; + + int partitioningValue = input[end]; + + while (true) { + while (input[left] < partitioningValue) + left++; + + while (input[right] > partitioningValue) { + if (right == begin) + break; + right--; + } + + if (left == right && input[left] == partitioningValue) { + swap(input, begin + leftEqualKeysCount, left); + leftEqualKeysCount++; + left++; + } + + if (left >= right) { + break; + } + + swap(input, left, right); + + if (input[left] == partitioningValue) { + swap(input, begin + leftEqualKeysCount, left); + leftEqualKeysCount++; + } + + if (input[right] == partitioningValue) { + swap(input, right, end - rightEqualKeysCount); + rightEqualKeysCount++; + } + left++; right--; + } + right = left - 1; + for (int k = begin; k < begin + leftEqualKeysCount; k++, right--) { + if (right >= begin + leftEqualKeysCount) + swap(input, k, right); + } + for (int k = end; k > end - rightEqualKeysCount; k--, left++) { + if (left <= end - rightEqualKeysCount) + swap(input, left, k); + } + return new Partition(right + 1, left - 1); + } + + public static void quicksort(int input[], int begin, int end) { + if (end <= begin) + return; + Partition middlePartition = partition(input, begin, end); + quicksort(input, begin, middlePartition.getLeft() - 1); + quicksort(input, middlePartition.getRight() + 1, end); + } + +} diff --git a/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/DutchNationalFlagPartioning.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/DutchNationalFlagPartioning.java new file mode 100644 index 0000000000..e868cf0e2e --- /dev/null +++ b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/DutchNationalFlagPartioning.java @@ -0,0 +1,38 @@ +package com.baeldung.algorithms.quicksort; + +import static com.baeldung.algorithms.quicksort.SortingUtils.compare; +import static com.baeldung.algorithms.quicksort.SortingUtils.swap; + +public class DutchNationalFlagPartioning { + + public static Partition partition(int[] a, int begin, int end) { + int lt = begin, current = begin, gt = end; + int partitioningValue = a[begin]; + + while (current <= gt) { + int compareCurrent = compare(a[current], partitioningValue); + switch (compareCurrent) { + case -1: + swap(a, current++, lt++); + break; + case 0: + current++; + break; + case 1: + swap(a, current, gt--); + break; + } + } + return new Partition(lt, gt); + } + + public static void quicksort(int[] input, int begin, int end) { + if (end <= begin) + return; + + Partition middlePartition = partition(input, begin, end); + + quicksort(input, begin, middlePartition.getLeft() - 1); + quicksort(input, middlePartition.getRight() + 1, end); + } +} diff --git a/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/Partition.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/Partition.java new file mode 100644 index 0000000000..29812f2720 --- /dev/null +++ b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/Partition.java @@ -0,0 +1,29 @@ +package com.baeldung.algorithms.quicksort; + +public class Partition { + private int left; + private int right; + + public Partition(int left, int right) { + super(); + this.left = left; + this.right = right; + } + + public int getLeft() { + return left; + } + + public void setLeft(int left) { + this.left = left; + } + + public int getRight() { + return right; + } + + public void setRight(int right) { + this.right = right; + } + +} diff --git a/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/SortingUtils.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/SortingUtils.java new file mode 100644 index 0000000000..ac1aa5e8ee --- /dev/null +++ b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/SortingUtils.java @@ -0,0 +1,32 @@ +package com.baeldung.algorithms.quicksort; + +public class SortingUtils { + + public static void swap(int[] array, int position1, int position2) { + if (position1 != position2) { + int temp = array[position1]; + array[position1] = array[position2]; + array[position2] = temp; + } + } + + public static int compare(int num1, int num2) { + if (num1 > num2) + return 1; + else if (num1 < num2) + return -1; + else + return 0; + } + + public static void printArray(int[] array) { + if (array == null) { + return; + } + for (int e : array) { + System.out.print(e + " "); + } + System.out.println(); + } + +} diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java similarity index 100% rename from algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java rename to algorithms-sorting-2/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java diff --git a/algorithms-sorting-2/src/main/resources/logback.xml b/algorithms-sorting-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..26beb6d5b4 --- /dev/null +++ b/algorithms-sorting-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/algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java similarity index 95% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java index 2f05f62147..aaa5de87e1 100644 --- a/algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java +++ b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java @@ -1,6 +1,5 @@ -package com.baeldung.algorithms.sort.bynumber; +package com.baeldung.algorithms.bynumber; -import com.baeldung.algorithms.sort.bynumber.NaturalOrderComparators; import org.junit.Test; import java.util.ArrayList; diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java similarity index 100% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java diff --git a/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java new file mode 100644 index 0000000000..847f7f8acb --- /dev/null +++ b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.algorithms.quicksort; + +import org.junit.Assert; +import org.junit.Test; + +public class BentleyMcilroyPartitioningUnitTest { + + @Test + public void given_IntegerArray_whenSortedWithBentleyMcilroyPartitioning_thenGetSortedArray() { + int[] actual = {3, 2, 2, 2, 3, 7, 7, 3, 2, 2, 7, 3, 3}; + int[] expected = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 7, 7}; + BentleyMcIlroyPartioning.quicksort(actual, 0, actual.length - 1); + Assert.assertArrayEquals(expected, actual); + } + +} diff --git a/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java new file mode 100644 index 0000000000..a8e27253cc --- /dev/null +++ b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.algorithms.quicksort; + +import org.junit.Assert; +import org.junit.Test; + +public class DNFThreeWayQuickSortUnitTest { + + @Test + public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { + int[] actual = {3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3}; + int[] expected = {3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7}; + DutchNationalFlagPartioning.quicksort(actual, 0, actual.length - 1); + Assert.assertArrayEquals(expected, actual); + } +} diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java similarity index 100% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java similarity index 100% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java diff --git a/algorithms-sorting/README.md b/algorithms-sorting/README.md index 15a5ec6e02..b4b90bf954 100644 --- a/algorithms-sorting/README.md +++ b/algorithms-sorting/README.md @@ -11,10 +11,7 @@ This module contains articles about sorting algorithms. - [Heap Sort in Java](https://www.baeldung.com/java-heap-sort) - [Shell Sort in Java](https://www.baeldung.com/java-shell-sort) - [Counting Sort in Java](https://www.baeldung.com/java-counting-sort) -- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) -- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting) - [Selection Sort in Java](https://www.baeldung.com/java-selection-sort) -- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) - [Radix Sort in Java](https://www.baeldung.com/java-radix-sort) -- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) - [Bucket Sort in Java](https://www.baeldung.com/java-bucket-sort) +- More articles: [[next -->]](/algorithms-sorintg-2) diff --git a/algorithms-sorting/pom.xml b/algorithms-sorting/pom.xml index 84856235d9..2de8eed04e 100644 --- a/algorithms-sorting/pom.xml +++ b/algorithms-sorting/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 algorithms-sorting 0.0.1-SNAPSHOT diff --git a/animal-sniffer-mvn-plugin/pom.xml b/animal-sniffer-mvn-plugin/pom.xml index d04581aaac..82726aa7bc 100644 --- a/animal-sniffer-mvn-plugin/pom.xml +++ b/animal-sniffer-mvn-plugin/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 animal-sniffer-mvn-plugin 1.0-SNAPSHOT @@ -44,5 +46,5 @@ 1.16 1.0 - + \ No newline at end of file diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml index 645bbd7a0f..f94cee04f0 100644 --- a/annotations/annotation-processing/pom.xml +++ b/annotations/annotation-processing/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 annotation-processing annotation-processing diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml index ae47e19f05..f38e93528d 100644 --- a/annotations/annotation-user/pom.xml +++ b/annotations/annotation-user/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 annotation-user annotation-user diff --git a/annotations/pom.xml b/annotations/pom.xml index 41e1e8735b..c3c23cf5ab 100644 --- a/annotations/pom.xml +++ b/annotations/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 annotations annotations diff --git a/antlr/pom.xml b/antlr/pom.xml index 641382d450..c8e48706fb 100644 --- a/antlr/pom.xml +++ b/antlr/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 antlr antlr @@ -58,5 +60,5 @@ 4.7.1 3.0.0 - + \ No newline at end of file diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml index 35898711c8..ad32ebb702 100644 --- a/apache-avro/pom.xml +++ b/apache-avro/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 apache-avro 0.0.1-SNAPSHOT diff --git a/apache-beam/README.md b/apache-beam/README.md new file mode 100644 index 0000000000..a71e5256a8 --- /dev/null +++ b/apache-beam/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Apache Beam](https://www.baeldung.com/apache-beam) diff --git a/apache-beam/pom.xml b/apache-beam/pom.xml new file mode 100644 index 0000000000..7a714ac480 --- /dev/null +++ b/apache-beam/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + com.baeldung.apache + apache-beam + 0.0.1-SNAPSHOT + + + + org.apache.beam + beam-sdks-java-core + ${beam.version} + + + + org.apache.beam + beam-runners-direct-java + ${beam.version} + runtime + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 2.19.0 + 3.6.1 + + + diff --git a/apache-beam/src/main/java/com/baeldung/apache/beam/intro/WordCount.java b/apache-beam/src/main/java/com/baeldung/apache/beam/intro/WordCount.java new file mode 100644 index 0000000000..f2dfb47810 --- /dev/null +++ b/apache-beam/src/main/java/com/baeldung/apache/beam/intro/WordCount.java @@ -0,0 +1,71 @@ +package com.baeldung.apache.beam.intro; + +import java.util.Arrays; + +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.transforms.Count; +import org.apache.beam.sdk.transforms.Filter; +import org.apache.beam.sdk.transforms.FlatMapElements; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.TypeDescriptors; + +public class WordCount { + + public static boolean wordCount(String inputFilePath, String outputFilePath) { + // We use default options + PipelineOptions options = PipelineOptionsFactory.create(); + // to create the pipeline + Pipeline p = Pipeline.create(options); + // Here is our workflow graph + PCollection> wordCount = p + .apply("(1) Read all lines", TextIO.read().from(inputFilePath)) + .apply("(2) Flatmap to a list of words", FlatMapElements.into(TypeDescriptors.strings()) + .via(line -> Arrays.asList(line.split("\\s")))) + .apply("(3) Lowercase all", MapElements.into(TypeDescriptors.strings()) + .via(word -> word.toLowerCase())) + .apply("(4) Trim punctuations", MapElements.into(TypeDescriptors.strings()) + .via(word -> trim(word))) + .apply("(5) Filter stopwords", Filter.by(word -> !isStopWord(word))) + .apply("(6) Count words", Count.perElement()); + // We convert the PCollection to String so that we can write it to file + wordCount.apply(MapElements.into(TypeDescriptors.strings()) + .via(count -> count.getKey() + " --> " + count.getValue())) + .apply(TextIO.write().to(outputFilePath)); + // Finally we must run the pipeline, otherwise it's only a definition + p.run().waitUntilFinish(); + return true; + } + + public static boolean isStopWord(String word) { + String[] stopwords = {"am", "are", "is", "i", "you", "me", + "he", "she", "they", "them", "was", + "were", "from", "in", "of", "to", "be", + "him", "her", "us", "and", "or"}; + for (String stopword : stopwords) { + if (stopword.compareTo(word) == 0) { + return true; + } + } + return false; + } + + public static String trim(String word) { + return word.replace("(","") + .replace(")", "") + .replace(",", "") + .replace(".", "") + .replace("\"", "") + .replace("'", "") + .replace(":", "") + .replace(";", "") + .replace("-", "") + .replace("?", "") + .replace("!", ""); + } + +} diff --git a/apache-beam/src/test/java/com/baeldung/apache/beam/intro/WordCountUnitTest.java b/apache-beam/src/test/java/com/baeldung/apache/beam/intro/WordCountUnitTest.java new file mode 100644 index 0000000000..f2558635dc --- /dev/null +++ b/apache-beam/src/test/java/com/baeldung/apache/beam/intro/WordCountUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.apache.beam.intro; + +import static org.junit.Assert.assertTrue; + +import org.junit.Ignore; +import org.junit.Test; + +import com.baeldung.apache.beam.intro.WordCount; + +public class WordCountUnitTest { + + @Test + // @Ignore + public void givenInputFile_whenWordCountRuns_thenJobFinishWithoutError() { + boolean jobDone = WordCount.wordCount("src/test/resources/wordcount.txt", "target/output"); + assertTrue(jobDone); + } + +} diff --git a/apache-beam/src/test/resources/wordcount.txt b/apache-beam/src/test/resources/wordcount.txt new file mode 100644 index 0000000000..542385379b --- /dev/null +++ b/apache-beam/src/test/resources/wordcount.txt @@ -0,0 +1,16 @@ +We've all heard the scare stories about North Korea: the homemade nuclear arsenal built while their people starve and then aimed imprecisely at the rest of the world, a +leader so deluded he makes L Ron Hubbard look like a man excessively overburdened with self-doubt and their deep-seated belief that foreign capitalists will invade at any +moment and steal all their bauxite. +The popular portrayal of this Marxist nation is something like one of the more harrowing episodes of M*A*S*H, only with the cast of wacky characters replaced by twitchy, +heavily armed Stalinist meth addicts +Cracked would like to take a moment to celebrate the good things about North Korea though, the things that the country's enemies prefer to suppress as part of their politically +motivated jealousy. Like how no different to you and me, there's nothing every North Korean likes more after an 18 hour shift at the phosphorus plant than a nice beer to go with +his dried fish ration. Ever attentive to its people's needs and in the twinkling of a decade, North Korea's leadership bought, disassembled, transported and rebuilt a British +brewery in order to discover and reproduce the secrets of beer and then brew the sweet nectar for its hardworking people, up to 18 bottles at a time. And with minimal fatalities. +When was the last time YOUR leader got a beer for YOU, American? (NB do not answer this question if you are Henry Louis Gates). +Or how about the fried chicken restaurant that downtown Pyongyang boasts? Yes real chicken, fried and then delivered to your sleeping cube, with optional beer if you like! You +don't even have to remove the feathers or pull out the gizzard yourself. Mostly. Americans must eat their fried chicken from a bucket, like swine, sold by a company so secretive +that even the very blend of seasoning used is intentionally kept from them. And they call North Korea paranoid? +And how many nations would entertain the syphilitic, bourgeois ramblings of Bill Clinton let alone permit him anywhere near their proud womenfolk? Only wise Kim Jong Il could see +past Bill's many, many imperfections and treat him with the pity and kindness he deserves, accepting his feeble pleas to pardon the American spies rightly convicted of photographing +the nation's sensitive beetroot fields. diff --git a/apache-bval/pom.xml b/apache-bval/pom.xml index 4254242e55..49484f4959 100644 --- a/apache-bval/pom.xml +++ b/apache-bval/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-bval 0.0.1-SNAPSHOT diff --git a/apache-curator/pom.xml b/apache-curator/pom.xml index ea8fb358ad..5b249127d9 100644 --- a/apache-curator/pom.xml +++ b/apache-curator/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-curator 0.0.1-SNAPSHOT diff --git a/apache-cxf/cxf-aegis/README.md b/apache-cxf/cxf-aegis/README.md deleted file mode 100644 index e055826554..0000000000 --- a/apache-cxf/cxf-aegis/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles - -- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf) diff --git a/apache-cxf/cxf-aegis/pom.xml b/apache-cxf/cxf-aegis/pom.xml index 6e6c5b093c..c10f019f82 100644 --- a/apache-cxf/cxf-aegis/pom.xml +++ b/apache-cxf/cxf-aegis/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 cxf-aegis cxf-aegis diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml index 0572b01a9d..be604fa401 100644 --- a/apache-cxf/cxf-introduction/pom.xml +++ b/apache-cxf/cxf-introduction/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 cxf-introduction cxf-introduction diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml index 37b81882bb..7b77969075 100644 --- a/apache-cxf/cxf-jaxrs-implementation/pom.xml +++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 cxf-jaxrs-implementation cxf-jaxrs-implementation diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml index 01ee7d9411..f9581515b2 100644 --- a/apache-cxf/cxf-spring/pom.xml +++ b/apache-cxf/cxf-spring/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 cxf-spring cxf-spring diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml index c993eff3a5..3d64000c2e 100644 --- a/apache-cxf/pom.xml +++ b/apache-cxf/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-cxf 0.0.1-SNAPSHOT diff --git a/apache-cxf/sse-jaxrs/pom.xml b/apache-cxf/sse-jaxrs/pom.xml index 89bd5d4191..5c46547b9a 100644 --- a/apache-cxf/sse-jaxrs/pom.xml +++ b/apache-cxf/sse-jaxrs/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 sse-jaxrs sse-jaxrs diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml index 37a068003c..92a6165f04 100644 --- a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 sse-jaxrs-client sse-jaxrs-client diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml index 43bbcf1ef4..efebb328a2 100644 --- a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml @@ -1,12 +1,13 @@ - + 4.0.0 sse-jaxrs-server sse-jaxrs-server war - + com.baeldung sse-jaxrs @@ -18,19 +19,19 @@ javax.ws.rs javax.ws.rs-api - 2.1 + ${rs-api.version} provided javax.enterprise cdi-api - 2.0 + ${cdi-api.version} provided javax.json.bind javax.json.bind-api - 1.0 + ${bind-api.version} provided @@ -80,6 +81,9 @@ 2.4.2 false 18.0.0.2 + 2.1 + 2.0 + 1.0 diff --git a/apache-fop/README.md b/apache-fop/README.md deleted file mode 100644 index 2adc593026..0000000000 --- a/apache-fop/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Apache FOP - -This module contains articles about Apache FOP - -### Relevant Articles: diff --git a/apache-fop/pom.xml b/apache-fop/pom.xml index 41a6761eaf..fdcfe2c538 100644 --- a/apache-fop/pom.xml +++ b/apache-fop/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-fop 0.1-SNAPSHOT diff --git a/apache-fop/src/main/webapp/WEB-INF/web.xml b/apache-fop/src/main/webapp/WEB-INF/web.xml index 935beae648..31187b8064 100644 --- a/apache-fop/src/main/webapp/WEB-INF/web.xml +++ b/apache-fop/src/main/webapp/WEB-INF/web.xml @@ -16,7 +16,7 @@ contextConfigLocation - org.baeldung.config + com.baeldung.config diff --git a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java b/apache-fop/src/test/java/com/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java similarity index 99% rename from apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java rename to apache-fop/src/test/java/com/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java index 5e2da6fd1e..bfc34d83b5 100644 --- a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java +++ b/apache-fop/src/test/java/com/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java; +package com.baeldung.java; import java.io.BufferedOutputStream; import java.io.File; diff --git a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java b/apache-fop/src/test/java/com/baeldung/java/ApacheFOPHeroldLiveTest.java similarity index 99% rename from apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java rename to apache-fop/src/test/java/com/baeldung/java/ApacheFOPHeroldLiveTest.java index 8496222394..af36f46d02 100644 --- a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java +++ b/apache-fop/src/test/java/com/baeldung/java/ApacheFOPHeroldLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java; +package com.baeldung.java; import java.io.BufferedOutputStream; import java.io.BufferedReader; diff --git a/apache-geode/pom.xml b/apache-geode/pom.xml index 78c6390f80..fc5b253c01 100644 --- a/apache-geode/pom.xml +++ b/apache-geode/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 apache-geode 1.0-SNAPSHOT diff --git a/apache-meecrowave/pom.xml b/apache-meecrowave/pom.xml index 9e79780e22..e046599be3 100644 --- a/apache-meecrowave/pom.xml +++ b/apache-meecrowave/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-meecrowave 0.0.1 diff --git a/apache-olingo/olingo2/README.md b/apache-olingo/olingo2/README.md deleted file mode 100644 index b1cb23d822..0000000000 --- a/apache-olingo/olingo2/README.md +++ /dev/null @@ -1,4 +0,0 @@ -### Relevant Articles: - -- [OData Protocol Guide](https://www.baeldung.com/odata) -- [Intro to OData with Olingo](https://www.baeldung.com/olingo) diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml index fdbc9b4390..3456d4f362 100644 --- a/apache-olingo/olingo2/pom.xml +++ b/apache-olingo/olingo2/pom.xml @@ -1,9 +1,10 @@ - + 4.0.0 - org.baeldung.examples.olingo2 + com.baeldung.examples.olingo2 olingo2 olingo2 Sample Olingo 2 Project diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java b/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java similarity index 95% rename from apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java rename to apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java index 65a0428154..55155732c8 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java +++ b/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java @@ -1,4 +1,4 @@ -package org.baeldung.examples.olingo2; +package com.baeldung.examples.olingo2; import java.util.List; import java.util.Map; @@ -9,10 +9,8 @@ import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.FlushModeType; import javax.persistence.LockModeType; -import javax.persistence.Persistence; import javax.persistence.Query; import javax.persistence.StoredProcedureQuery; -import javax.persistence.SynchronizationType; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaDelete; @@ -25,11 +23,8 @@ import org.apache.olingo.odata2.api.processor.ODataContext; import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext; import org.apache.olingo.odata2.jpa.processor.api.ODataJPAServiceFactory; import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException; -import org.baeldung.examples.olingo2.JerseyConfig.EntityManagerFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.orm.jpa.EntityManagerFactoryUtils; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.stereotype.Component; /** @@ -58,7 +53,7 @@ public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory { ODataJPAContext ctx = getODataJPAContext(); ODataContext octx = ctx.getODataContext(); HttpServletRequest request = (HttpServletRequest)octx.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT); - EntityManager em = (EntityManager)request.getAttribute(EntityManagerFilter.EM_REQUEST_ATTRIBUTE); + EntityManager em = (EntityManager)request.getAttribute(JerseyConfig.EntityManagerFilter.EM_REQUEST_ATTRIBUTE); // Here we're passing the EM that was created by the EntityManagerFilter (see JerseyConfig) ctx.setEntityManager(new EntityManagerWrapper(em)); diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java b/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/JerseyConfig.java similarity index 97% rename from apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java rename to apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/JerseyConfig.java index 78caf99861..02e5ce5adf 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java +++ b/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/JerseyConfig.java @@ -1,11 +1,10 @@ - package org.baeldung.examples.olingo2; + package com.baeldung.examples.olingo2; import java.io.IOException; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; -import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.ApplicationPath; import javax.ws.rs.Path; diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java b/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/Olingo2SampleApplication.java similarity index 80% rename from apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java rename to apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/Olingo2SampleApplication.java index fa58612088..f76e0e00e3 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java +++ b/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/Olingo2SampleApplication.java @@ -1,8 +1,7 @@ -package org.baeldung.examples.olingo2; +package com.baeldung.examples.olingo2; 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 diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java b/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/domain/CarMaker.java similarity index 98% rename from apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java rename to apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/domain/CarMaker.java index e66d266062..d56a42374c 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java +++ b/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/domain/CarMaker.java @@ -1,4 +1,4 @@ -package org.baeldung.examples.olingo2.domain; +package com.baeldung.examples.olingo2.domain; import java.util.List; diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java b/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/domain/CarModel.java similarity index 98% rename from apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java rename to apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/domain/CarModel.java index f9f563e01e..6bbaa3ad0c 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java +++ b/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/domain/CarModel.java @@ -1,4 +1,4 @@ -package org.baeldung.examples.olingo2.domain; +package com.baeldung.examples.olingo2.domain; import javax.persistence.Entity; import javax.persistence.FetchType; diff --git a/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java b/apache-olingo/olingo2/src/test/java/com/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java similarity index 89% rename from apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java rename to apache-olingo/olingo2/src/test/java/com/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java index 7cb685e3e9..74033a49cd 100644 --- a/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java +++ b/apache-olingo/olingo2/src/test/java/com/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.examples.olingo2; +package com.baeldung.examples.olingo2; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/apache-opennlp/pom.xml b/apache-opennlp/pom.xml index 701d33c6fd..07ce14b4fd 100644 --- a/apache-opennlp/pom.xml +++ b/apache-opennlp/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-opennlp 1.0-SNAPSHOT diff --git a/apache-poi/README.md b/apache-poi/README.md index b7b8bf5f6a..b562fefc29 100644 --- a/apache-poi/README.md +++ b/apache-poi/README.md @@ -6,3 +6,6 @@ This module contains articles about Apache POI - [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi) - [Working with Microsoft Excel in Java](https://www.baeldung.com/java-microsoft-excel) - [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow) +- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells) +- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value) +- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula) diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml index a114946c47..eb72531787 100644 --- a/apache-poi/pom.xml +++ b/apache-poi/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-poi 0.0.1-SNAPSHOT @@ -32,7 +34,7 @@ - 3.15 + 4.1.1 1.0.6 diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelCellFormatter.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelCellFormatter.java new file mode 100644 index 0000000000..4a8854620c --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelCellFormatter.java @@ -0,0 +1,20 @@ +package com.baeldung.poi.excel; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.DataFormatter; +import org.apache.poi.ss.usermodel.FormulaEvaluator; +import org.apache.poi.ss.usermodel.Workbook; + +public class ExcelCellFormatter { + + public String getCellStringValue(Cell cell) { + DataFormatter formatter = new DataFormatter(); + return formatter.formatCellValue(cell); + } + + public String getCellStringValueWithFormula(Cell cell, Workbook workbook) { + DataFormatter formatter = new DataFormatter(); + FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); + return formatter.formatCellValue(cell, evaluator); + } +} diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaHelper.java b/apache-poi/src/main/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaHelper.java new file mode 100644 index 0000000000..08dd0e07ab --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaHelper.java @@ -0,0 +1,83 @@ +package com.baeldung.poi.excel.read.cellvalueandnotformula; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.FormulaEvaluator; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.util.CellAddress; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +public class CellValueAndNotFormulaHelper { + + public Object getCellValueByFetchingLastCachedValue(String fileLocation, String cellLocation) throws IOException { + Object cellValue = new Object(); + + FileInputStream inputStream = new FileInputStream(new File(fileLocation)); + Workbook workbook = new XSSFWorkbook(inputStream); + + Sheet sheet = workbook.getSheetAt(0); + + CellAddress cellAddress = new CellAddress(cellLocation); + Row row = sheet.getRow(cellAddress.getRow()); + Cell cell = row.getCell(cellAddress.getColumn()); + + if (cell.getCellType() == CellType.FORMULA) { + switch (cell.getCachedFormulaResultType()) { + case BOOLEAN: + cellValue = cell.getBooleanCellValue(); + break; + case NUMERIC: + cellValue = cell.getNumericCellValue(); + break; + case STRING: + cellValue = cell.getStringCellValue(); + break; + default: + cellValue = null; + } + } + + workbook.close(); + return cellValue; + } + + public Object getCellValueByEvaluatingFormula(String fileLocation, String cellLocation) throws IOException { + Object cellValue = new Object(); + + FileInputStream inputStream = new FileInputStream(new File(fileLocation)); + Workbook workbook = new XSSFWorkbook(inputStream); + + Sheet sheet = workbook.getSheetAt(0); + FormulaEvaluator evaluator = workbook.getCreationHelper() + .createFormulaEvaluator(); + + CellAddress cellAddress = new CellAddress(cellLocation); + Row row = sheet.getRow(cellAddress.getRow()); + Cell cell = row.getCell(cellAddress.getColumn()); + + if (cell.getCellType() == CellType.FORMULA) { + switch (evaluator.evaluateFormulaCell(cell)) { + case BOOLEAN: + cellValue = cell.getBooleanCellValue(); + break; + case NUMERIC: + cellValue = cell.getNumericCellValue(); + break; + case STRING: + cellValue = cell.getStringCellValue(); + break; + default: + cellValue = null; + } + } + + workbook.close(); + return cellValue; + } +} diff --git a/apache-poi/src/main/resources/ExcelCellFormatterTest.xlsx b/apache-poi/src/main/resources/ExcelCellFormatterTest.xlsx new file mode 100644 index 0000000000..54e8734d58 Binary files /dev/null and b/apache-poi/src/main/resources/ExcelCellFormatterTest.xlsx differ diff --git a/apache-poi/src/main/resources/test.xlsx b/apache-poi/src/main/resources/test.xlsx new file mode 100644 index 0000000000..64fe14f25b Binary files /dev/null and b/apache-poi/src/main/resources/test.xlsx differ diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterUnitTest.java new file mode 100644 index 0000000000..d9f96ee93c --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.poi.excel; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; + +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.Before; +import org.junit.Test; + +public class ExcelCellFormatterUnitTest { + private static final String FILE_NAME = "ExcelCellFormatterTest.xlsx"; + private static final int STRING_CELL_INDEX = 0; + private static final int BOOLEAN_CELL_INDEX = 1; + private static final int RAW_NUMERIC_CELL_INDEX = 2; + private static final int FORMATTED_NUMERIC_CELL_INDEX = 3; + private static final int FORMULA_CELL_INDEX = 4; + + private String fileLocation; + + @Before + public void setup() throws IOException, URISyntaxException { + fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString(); + } + + @Test + public void givenStringCell_whenGetCellStringValue_thenReturnStringValue() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("String Test", formatter.getCellStringValue(row.getCell(STRING_CELL_INDEX))); + workbook.close(); + } + + @Test + public void givenBooleanCell_whenGetCellStringValue_thenReturnBooleanStringValue() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("TRUE", formatter.getCellStringValue(row.getCell(BOOLEAN_CELL_INDEX))); + workbook.close(); + } + + @Test + public void givenNumericCell_whenGetCellStringValue_thenReturnNumericStringValue() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("1.234", formatter.getCellStringValue(row.getCell(RAW_NUMERIC_CELL_INDEX))); + assertEquals("1.23", formatter.getCellStringValue(row.getCell(FORMATTED_NUMERIC_CELL_INDEX))); + workbook.close(); + } + + @Test + public void givenFormualCell_whenGetCellStringValue_thenReturnOriginalFormulaString() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("SUM(1+2)", formatter.getCellStringValue(row.getCell(FORMULA_CELL_INDEX))); + workbook.close(); + } + + @Test + public void givenFormualCell_whenGetCellStringValueForFormula_thenReturnOriginalFormulatring() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("3", formatter.getCellStringValueWithFormula(row.getCell(FORMULA_CELL_INDEX), workbook)); + workbook.close(); + } + +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/merge/ExcelCellMergerUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/merge/ExcelCellMergerUnitTest.java new file mode 100644 index 0000000000..911d368f77 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/merge/ExcelCellMergerUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.poi.excel.merge; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; + +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.Before; +import org.junit.Test; + +public class ExcelCellMergerUnitTest { + private static final String FILE_NAME = "ExcelCellFormatterTest.xlsx"; + private String fileLocation; + + @Before + public void setup() throws IOException, URISyntaxException { + fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString(); + } + + @Test + public void givenCellIndex_whenAddMergeRegion_thenMergeRegionCreated() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + + assertEquals(0, sheet.getNumMergedRegions()); + int firstRow = 0; + int lastRow = 0; + int firstCol = 0; + int lastCol = 2; + sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol)); + assertEquals(1, sheet.getNumMergedRegions()); + + workbook.close(); + } + + @Test + public void givenCellRefString_whenAddMergeRegion_thenMergeRegionCreated() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + + assertEquals(0, sheet.getNumMergedRegions()); + sheet.addMergedRegion(CellRangeAddress.valueOf("A1:C1")); + assertEquals(1, sheet.getNumMergedRegions()); + + workbook.close(); + } + +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaUnitTest.java new file mode 100644 index 0000000000..885a955e9b --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.poi.excel.read.cellvalueandnotformula; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; + +import org.junit.Before; +import org.junit.Test; + +public class CellValueAndNotFormulaUnitTest { + + private CellValueAndNotFormulaHelper readCellValueAndNotFormulaHelper; + private String fileLocation; + private static final String FILE_NAME = "test.xlsx"; + + @Before + public void setup() throws URISyntaxException { + fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString(); + readCellValueAndNotFormulaHelper = new CellValueAndNotFormulaHelper(); + } + + @Test + public void givenExcelCell_whenReadCellValueByLastCachedValue_thenProduceCorrectResult() throws IOException { + final double expectedResult = 7.0; + final Object cellValue = readCellValueAndNotFormulaHelper.getCellValueByFetchingLastCachedValue(fileLocation, "C2"); + + assertEquals(expectedResult, cellValue); + } + + @Test + public void givenExcelCell_whenReadCellValueByEvaluatingFormula_thenProduceCorrectResult() throws IOException { + final double expectedResult = 7.0; + final Object cellValue = readCellValueAndNotFormulaHelper.getCellValueByEvaluatingFormula(fileLocation, "C2"); + + assertEquals(expectedResult, cellValue); + } +} diff --git a/apache-pulsar/pom.xml b/apache-pulsar/pom.xml index 206e1ab74d..568389f9f5 100644 --- a/apache-pulsar/pom.xml +++ b/apache-pulsar/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.pulsar apache-pulsar diff --git a/apache-rocketmq/README.md b/apache-rocketmq/README.md new file mode 100644 index 0000000000..734f878baa --- /dev/null +++ b/apache-rocketmq/README.md @@ -0,0 +1,7 @@ +## Apache RocketMQ + +This module contains articles about Apache RocketMQ + +### Relevant Articles: + +- [Apache RocketMQ with Spring Boot](https://www.baeldung.com/apache-rocketmq-spring-boot) diff --git a/apache-rocketmq/pom.xml b/apache-rocketmq/pom.xml new file mode 100644 index 0000000000..ba395ff054 --- /dev/null +++ b/apache-rocketmq/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + apache-rocketmq + 1.0-SNAPSHOT + apache-rocketmq + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.rocketmq + rocketmq-spring-boot-starter + ${rocketmq.version} + + + + + 1.6.0 + 2.0.4 + + diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java new file mode 100644 index 0000000000..06e88076d0 --- /dev/null +++ b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java @@ -0,0 +1,34 @@ +package com.baeldung.rocketmq.consumer; + +import com.baeldung.rocketmq.event.CartItemEvent; +import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; +import org.apache.rocketmq.spring.core.RocketMQListener; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.stereotype.Service; + +@SpringBootApplication +public class CartEventConsumer { + + public static void main(String[] args) { + SpringApplication.run(CartEventConsumer.class, args); + } + + @Service + @RocketMQMessageListener(topic = "cart-item-add-topic", consumerGroup = "cart-consumer_cart-item-add-topic") + public class CardItemAddConsumer implements RocketMQListener { + public void onMessage(CartItemEvent addItemEvent) { + System.out.println("Adding item: " + addItemEvent); + // logic + } + } + + @Service + @RocketMQMessageListener(topic = "cart-item-removed-topic", consumerGroup = "cart-consumer_cart-item-removed-topic") + public class CardItemRemoveConsumer implements RocketMQListener { + public void onMessage(CartItemEvent removeItemEvent) { + System.out.println("Removing item: " + removeItemEvent); + // logic + } + } +} diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java new file mode 100644 index 0000000000..a9d7b4a436 --- /dev/null +++ b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java @@ -0,0 +1,32 @@ +package com.baeldung.rocketmq.event; + +public class CartItemEvent { + private String itemId; + private int quantity; + + public CartItemEvent(String itemId, int quantity) { + this.itemId = itemId; + this.quantity = quantity; + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + @Override + public String toString() { + return "CartItemEvent{" + "itemId='" + itemId + '\'' + ", quantity=" + quantity + '}'; + } +} diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java new file mode 100644 index 0000000000..dba6ee7a46 --- /dev/null +++ b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java @@ -0,0 +1,26 @@ +package com.baeldung.rocketmq.producer; + + +import com.baeldung.rocketmq.event.CartItemEvent; +import org.apache.rocketmq.spring.core.RocketMQTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CartEventProducer implements CommandLineRunner { + + @Autowired + private RocketMQTemplate rocketMQTemplate; + + public static void main(String[] args) { + SpringApplication.run(CartEventProducer.class, args); + } + + public void run(String... args) throws Exception { + rocketMQTemplate.convertAndSend("cart-item-add-topic", new CartItemEvent("bike", 1)); + rocketMQTemplate.convertAndSend("cart-item-add-topic", new CartItemEvent("computer", 2)); + rocketMQTemplate.convertAndSend("cart-item-removed-topic", new CartItemEvent("bike", 1)); + } +} diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java new file mode 100644 index 0000000000..e5fa6e361a --- /dev/null +++ b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java @@ -0,0 +1,21 @@ +package com.baeldung.rocketmq.transaction; + +import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener; +import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener; +import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState; +import org.springframework.messaging.Message; + +@RocketMQTransactionListener(txProducerGroup = "test-transaction") +class TransactionListenerImpl implements RocketMQLocalTransactionListener { + @Override + public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) { + // ... local transaction process, return ROLLBACK, COMMIT or UNKNOWN + return RocketMQLocalTransactionState.UNKNOWN; + } + + @Override + public RocketMQLocalTransactionState checkLocalTransaction(Message msg) { + // ... check transaction status and return ROLLBACK, COMMIT or UNKNOWN + return RocketMQLocalTransactionState.COMMIT; + } +} diff --git a/apache-rocketmq/src/main/resources/application.properties b/apache-rocketmq/src/main/resources/application.properties new file mode 100644 index 0000000000..68d4ceaacd --- /dev/null +++ b/apache-rocketmq/src/main/resources/application.properties @@ -0,0 +1,9 @@ +rocketmq.name-server=127.0.0.1:9876 +rocketmq.producer.group=my-group +rocketmq.producer.send-message-timeout=300000 +rocketmq.producer.compress-message-body-threshold=4096 +rocketmq.producer.max-message-size=4194304 +rocketmq.producer.retry-times-when-send-async-failed=0 +rocketmq.producer.retry-next-server=true +rocketmq.producer.retry-times-when-send-failed=2 + diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml index 0458ba783f..3df6283437 100644 --- a/apache-shiro/pom.xml +++ b/apache-shiro/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 apache-shiro 1.0-SNAPSHOT @@ -9,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/apache-shiro/src/main/java/com/baeldung/Main.java b/apache-shiro/src/main/java/com/baeldung/Main.java index 5e341f251b..99515bb705 100644 --- a/apache-shiro/src/main/java/com/baeldung/Main.java +++ b/apache-shiro/src/main/java/com/baeldung/Main.java @@ -1,11 +1,14 @@ package com.baeldung; import org.apache.shiro.SecurityUtils; -import org.apache.shiro.authc.*; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.IncorrectCredentialsException; +import org.apache.shiro.authc.LockedAccountException; +import org.apache.shiro.authc.UnknownAccountException; +import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.realm.Realm; -import org.apache.shiro.realm.text.IniRealm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; diff --git a/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java index 8d792c76a5..6d7c01d96e 100644 --- a/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java +++ b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java @@ -1,16 +1,24 @@ package com.baeldung; -import org.apache.shiro.authc.*; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.AuthenticationInfo; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.authc.SimpleAuthenticationInfo; +import org.apache.shiro.authc.UnknownAccountException; +import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.jdbc.JdbcRealm; import org.apache.shiro.subject.PrincipalCollection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.*; public class MyCustomRealm extends JdbcRealm { diff --git a/apache-shiro/src/main/java/com/baeldung/shiro/permissions/custom/Main.java b/apache-shiro/src/main/java/com/baeldung/shiro/permissions/custom/Main.java index a373122d6c..a902a24388 100644 --- a/apache-shiro/src/main/java/com/baeldung/shiro/permissions/custom/Main.java +++ b/apache-shiro/src/main/java/com/baeldung/shiro/permissions/custom/Main.java @@ -1,14 +1,15 @@ package com.baeldung.shiro.permissions.custom; -import com.baeldung.MyCustomRealm; import org.apache.shiro.SecurityUtils; -import org.apache.shiro.authc.*; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.IncorrectCredentialsException; +import org.apache.shiro.authc.LockedAccountException; +import org.apache.shiro.authc.UnknownAccountException; +import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.Ini; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.mgt.SecurityManager; -import org.apache.shiro.realm.Realm; import org.apache.shiro.realm.text.IniRealm; -import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/apache-solrj/pom.xml b/apache-solrj/pom.xml index b25fd0fb04..165cd9571b 100644 --- a/apache-solrj/pom.xml +++ b/apache-solrj/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-solrj 0.0.1-SNAPSHOT diff --git a/apache-spark/README.md b/apache-spark/README.md index 52313d66bf..c60b556d51 100644 --- a/apache-spark/README.md +++ b/apache-spark/README.md @@ -7,4 +7,4 @@ This module contains articles about Apache Spark - [Introduction to Apache Spark](https://www.baeldung.com/apache-spark) - [Building a Data Pipeline with Kafka, Spark Streaming and Cassandra](https://www.baeldung.com/kafka-spark-data-pipeline) - [Machine Learning with Spark MLlib](https://www.baeldung.com/spark-mlib-machine-learning) - +- [Introduction to Spark Graph Processing with GraphFrames](https://www.baeldung.com/spark-graph-graphframes) diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index 59843adc71..27768d60fc 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 apache-spark 1.0-SNAPSHOT diff --git a/apache-tapestry/README.md b/apache-tapestry/README.md new file mode 100644 index 0000000000..e41345bada --- /dev/null +++ b/apache-tapestry/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Intro to Apache Tapestry](https://www.baeldung.com/apache-tapestry) diff --git a/apache-tapestry/pom.xml b/apache-tapestry/pom.xml index e306b56b4a..82dc34899f 100644 --- a/apache-tapestry/pom.xml +++ b/apache-tapestry/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung apache-tapestry @@ -9,9 +11,8 @@ war - + org.apache.tapestry tapestry-core @@ -32,17 +33,10 @@ - + - + org.testng testng @@ -57,8 +51,7 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's test - + javax.servlet servlet-api @@ -81,10 +74,10 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + ${compiler.plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} true @@ -92,7 +85,7 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's org.apache.maven.plugins maven-surefire-plugin - 2.7.2 + ${compiler.surefire.version} Qa @@ -104,12 +97,11 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's org.mortbay.jetty maven-jetty-plugin - 6.1.16 + ${compiler.jetty.version} - + true @@ -123,7 +115,7 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's - + @@ -131,8 +123,7 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's http://repository.jboss.org/nexus/content/groups/public/ - + apache-staging https://repository.apache.org/content/groups/staging/ @@ -140,6 +131,11 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's + 6.1.16 + 2.7.2 + 2.3.2 + 1.8 + 1.8 5.4.5 2.5 6.8.21 diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml index 409467ccc5..6d079c8c28 100644 --- a/apache-thrift/pom.xml +++ b/apache-thrift/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-thrift 0.0.1-SNAPSHOT diff --git a/apache-tika/pom.xml b/apache-tika/pom.xml index 24c904aec3..a2c3a32820 100644 --- a/apache-tika/pom.xml +++ b/apache-tika/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-tika 0.0.1-SNAPSHOT diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml index 61d7e74498..806b36237d 100644 --- a/apache-velocity/pom.xml +++ b/apache-velocity/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-velocity 0.1-SNAPSHOT diff --git a/apache-zookeeper/pom.xml b/apache-zookeeper/pom.xml index 0bab6cded6..f441848f70 100644 --- a/apache-zookeeper/pom.xml +++ b/apache-zookeeper/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 apache-zookeeper 0.0.1-SNAPSHOT diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml index 5421df91be..5b34f19bbb 100644 --- a/asciidoctor/pom.xml +++ b/asciidoctor/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 asciidoctor asciidoctor diff --git a/asm/pom.xml b/asm/pom.xml index 77dbab964c..f4689de8e0 100644 --- a/asm/pom.xml +++ b/asm/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.examples asm diff --git a/atomikos/README.md b/atomikos/README.md new file mode 100644 index 0000000000..f9129233ec --- /dev/null +++ b/atomikos/README.md @@ -0,0 +1,6 @@ +## Atomikos +This module contains articles about Atomikos + +### Relevant Articles: + +- [A Guide to Atomikos](https://www.baeldung.com/java-atomikos) diff --git a/atomikos/pom.xml b/atomikos/pom.xml new file mode 100644 index 0000000000..881adae074 --- /dev/null +++ b/atomikos/pom.xml @@ -0,0 +1,119 @@ + + + 4.0.0 + atomikos + atomikos + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.atomikos + transactions-jdbc + ${atomikos-version} + + + com.atomikos + transactions-jms + ${atomikos-version} + + + com.atomikos + transactions-hibernate4 + ${atomikos-version} + + + org.springframework + spring-context + ${spring-version} + + + org.springframework + spring-tx + ${spring-version} + + + org.springframework.data + spring-data-jpa + 1.11.23.RELEASE + + + org.springframework + spring-test + ${spring-version} + test + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + provided + + + javax.transaction + jta + + + + + org.apache.activemq + activemq-core + 5.7.0 + + + org.apache.derby + derby + 10.8.1.2 + + + junit + junit + 4.12 + test + + + + javax.transaction + jta + 1.1 + + + org.apache.geronimo.specs + geronimo-jta_1.0.1B_spec + 1.0 + + + javax.validation + validation-api + 2.0.1.Final + + + org.hibernate.validator + hibernate-validator + 6.1.2.Final + + + javax.el + javax.el-api + 3.0.0 + + + org.glassfish.web + javax.el + 2.2.4 + + + + + 5.0.6 + 5.1.6.RELEASE + 5.4.3.Final + + + \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java new file mode 100644 index 0000000000..c51ce70dde --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.direct; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import com.atomikos.icatch.jta.UserTransactionImp; + +public class Application { + + private DataSource inventoryDataSource; + private DataSource orderDataSource; + + public Application(DataSource inventoryDataSource, DataSource orderDataSource) { + this.inventoryDataSource = inventoryDataSource; + this.orderDataSource = orderDataSource; + } + + public void placeOrder(String productId, int amount) throws Exception { + + UserTransactionImp utx = new UserTransactionImp(); + String orderId = UUID.randomUUID() + .toString(); + boolean rollback = false; + try { + utx.begin(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "update Inventory set balance = balance - " + amount + " where productId ='" + productId + "'"; + s1.executeUpdate(q1); + s1.close(); + Statement s2 = orderConnection.createStatement(); + String q2 = "insert into Orders values ( '" + orderId + "', '" + productId + "', " + amount + " )"; + s2.executeUpdate(q2); + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } catch (Exception e) { + System.out.println(e.getMessage()); + rollback = true; + } finally { + if (!rollback) + utx.commit(); + else + utx.rollback(); + } + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java new file mode 100644 index 0000000000..b480e68d8d --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java @@ -0,0 +1,41 @@ +package com.baeldung.atomikos.spring; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.springframework.transaction.annotation.Transactional; + +public class Application { + + private DataSource inventoryDataSource; + private DataSource orderDataSource; + + public Application(DataSource inventoryDataSource, DataSource orderDataSource) { + this.inventoryDataSource = inventoryDataSource; + this.orderDataSource = orderDataSource; + } + + @Transactional(rollbackFor = Exception.class) + public void placeOrder(String productId, int amount) throws Exception { + + String orderId = UUID.randomUUID() + .toString(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "update Inventory set balance = balance - " + amount + " where productId ='" + productId + "'"; + s1.executeUpdate(q1); + s1.close(); + Statement s2 = orderConnection.createStatement(); + String q2 = "insert into Orders values ( '" + orderId + "', '" + productId + "', " + amount + " )"; + s2.executeUpdate(q2); + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java new file mode 100644 index 0000000000..c6ef83c4ca --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java @@ -0,0 +1,68 @@ +package com.baeldung.atomikos.spring.config; + +import java.util.Properties; + +import javax.transaction.SystemException; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.jta.JtaTransactionManager; + +import com.atomikos.icatch.jta.UserTransactionManager; +import com.atomikos.jdbc.AtomikosDataSourceBean; +import com.baeldung.atomikos.spring.Application; + +@Configuration +@EnableTransactionManagement +public class Config { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean inventoryDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db1"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db1"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean orderDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db2"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db2"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean(initMethod = "init", destroyMethod = "close") + public UserTransactionManager userTransactionManager() throws SystemException { + UserTransactionManager userTransactionManager = new UserTransactionManager(); + userTransactionManager.setTransactionTimeout(300); + userTransactionManager.setForceShutdown(true); + return userTransactionManager; + } + + @Bean + public JtaTransactionManager jtaTransactionManager() throws SystemException { + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(); + jtaTransactionManager.setTransactionManager(userTransactionManager()); + jtaTransactionManager.setUserTransaction(userTransactionManager()); + return jtaTransactionManager; + } + + @Bean + public Application application() { + return new Application(inventoryDataSource(), orderDataSource()); + } +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java new file mode 100644 index 0000000000..cf1fef2cd8 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java @@ -0,0 +1,48 @@ +package com.baeldung.atomikos.spring.jpa; + +import java.util.Set; +import java.util.UUID; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.atomikos.spring.jpa.inventory.Inventory; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryRepository; +import com.baeldung.atomikos.spring.jpa.order.Order; +import com.baeldung.atomikos.spring.jpa.order.OrderRepository; + +public class Application { + + @Autowired + private InventoryRepository inventoryRepository; + + @Autowired + private OrderRepository orderRepository; + + @Transactional(rollbackFor = Exception.class) + public void placeOrder(String productId, int amount) throws Exception { + + String orderId = UUID.randomUUID() + .toString(); + Inventory inventory = inventoryRepository.findOne(productId); + inventory.setBalance(inventory.getBalance() - amount); + inventoryRepository.save(inventory); + Order order = new Order(); + order.setOrderId(orderId); + order.setProductId(productId); + order.setAmount(new Long(amount)); + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> violations = validator.validate(order); + if (violations.size() > 0) + throw new Exception("Invalid instance of an order."); + orderRepository.save(order); + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java new file mode 100644 index 0000000000..6716f19576 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java @@ -0,0 +1,38 @@ +package com.baeldung.atomikos.spring.jpa.config; + +import javax.transaction.SystemException; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.jta.JtaTransactionManager; + +import com.atomikos.icatch.jta.UserTransactionManager; +import com.baeldung.atomikos.spring.jpa.Application; + +@Configuration +@EnableTransactionManagement +public class Config { + + @Bean(initMethod = "init", destroyMethod = "close") + public UserTransactionManager userTransactionManager() throws SystemException { + UserTransactionManager userTransactionManager = new UserTransactionManager(); + userTransactionManager.setTransactionTimeout(300); + userTransactionManager.setForceShutdown(true); + return userTransactionManager; + } + + @Bean + public JtaTransactionManager transactionManager() throws SystemException { + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(); + jtaTransactionManager.setTransactionManager(userTransactionManager()); + jtaTransactionManager.setUserTransaction(userTransactionManager()); + return jtaTransactionManager; + } + + @Bean + public Application application() { + return new Application(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java new file mode 100644 index 0000000000..999879218c --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java @@ -0,0 +1,31 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "INVENTORY") +public class Inventory { + + @Id + private String productId; + private Long balance; + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public Long getBalance() { + return balance; + } + + public void setBalance(Long balance) { + this.balance = balance; + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java new file mode 100644 index 0000000000..5301ad6ff2 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +import com.atomikos.jdbc.AtomikosDataSourceBean; + +@Configuration +@EnableJpaRepositories(basePackages = "com.baeldung.atomikos.spring.jpa.inventory", entityManagerFactoryRef = "inventoryEntityManager", transactionManagerRef = "transactionManager") +public class InventoryConfig { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean inventoryDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db1"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db1"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean + public EntityManagerFactory inventoryEntityManager() { + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setJpaVendorAdapter(vendorAdapter); + factory.setPackagesToScan("com.baeldung.atomikos.spring.jpa.inventory"); + factory.setDataSource(inventoryDataSource()); + Properties jpaProperties = new Properties(); + //jpaProperties.put("hibernate.show_sql", "true"); + //jpaProperties.put("hibernate.format_sql", "true"); + jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect"); + jpaProperties.put("hibernate.current_session_context_class", "jta"); + jpaProperties.put("javax.persistence.transactionType", "jta"); + jpaProperties.put("hibernate.transaction.manager_lookup_class", "com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"); + jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop"); + factory.setJpaProperties(jpaProperties); + factory.afterPropertiesSet(); + return factory.getObject(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java new file mode 100644 index 0000000000..c3868e51bf --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface InventoryRepository extends JpaRepository { + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java new file mode 100644 index 0000000000..4b9ae2dd1d --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java @@ -0,0 +1,42 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.Max; + +@Entity +@Table(name = "ORDERS") +public class Order { + + @Id + private String orderId; + private String productId; + @Max(5) + private Long amount; + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public Long getAmount() { + return amount; + } + + public void setAmount(Long amount) { + this.amount = amount; + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java new file mode 100644 index 0000000000..b4274bb64c --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +import com.atomikos.jdbc.AtomikosDataSourceBean; + +@Configuration +@EnableJpaRepositories(basePackages = "com.baeldung.atomikos.spring.jpa.order", entityManagerFactoryRef = "orderEntityManager", transactionManagerRef = "transactionManager") +public class OrderConfig { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean orderDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db2"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db2"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean + public EntityManagerFactory orderEntityManager() { + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setJpaVendorAdapter(vendorAdapter); + factory.setPackagesToScan("com.baeldung.atomikos.spring.jpa.order"); + factory.setDataSource(orderDataSource()); + Properties jpaProperties = new Properties(); + //jpaProperties.put("hibernate.show_sql", "true"); + //jpaProperties.put("hibernate.format_sql", "true"); + jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect"); + jpaProperties.put("hibernate.current_session_context_class", "jta"); + jpaProperties.put("javax.persistence.transactionType", "jta"); + jpaProperties.put("hibernate.transaction.manager_lookup_class", "com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"); + jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop"); + factory.setJpaProperties(jpaProperties); + factory.afterPropertiesSet(); + return factory.getObject(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java new file mode 100644 index 0000000000..2d5610ebca --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface OrderRepository extends JpaRepository { + +} diff --git a/core-java-modules/core-java-text/src/main/resources/logback.xml b/atomikos/src/main/resources/logback.xml similarity index 100% rename from core-java-modules/core-java-text/src/main/resources/logback.xml rename to atomikos/src/main/resources/logback.xml diff --git a/atomikos/src/main/resources/schema.sql b/atomikos/src/main/resources/schema.sql new file mode 100644 index 0000000000..5136ad1284 --- /dev/null +++ b/atomikos/src/main/resources/schema.sql @@ -0,0 +1,10 @@ +CREATE TABLE INVENTORY ( + productId VARCHAR PRIMARY KEY, + balance INT +); + +CREATE TABLE ORDERS ( + orderId VARCHAR PRIMARY KEY, + productId VARCHAR, + amount INT NOT NULL CHECK (amount <= 5) +); \ No newline at end of file diff --git a/atomikos/src/main/resources/transactions.properties b/atomikos/src/main/resources/transactions.properties new file mode 100644 index 0000000000..8e027032fa --- /dev/null +++ b/atomikos/src/main/resources/transactions.properties @@ -0,0 +1 @@ +com.atomikos.icatch.file=logs \ No newline at end of file diff --git a/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java new file mode 100644 index 0000000000..1a467807ba --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java @@ -0,0 +1,118 @@ +package com.baeldung.atomikos.direct; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import com.atomikos.icatch.jta.UserTransactionImp; +import com.atomikos.jdbc.AtomikosDataSourceBean; + +public class ApplicationUnitTest { + + private static DataSource inventoryDataSource; + private static DataSource orderDataSource; + + private static String productId = UUID.randomUUID() + .toString(); + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryDataSource, productId); + Application application = new Application(inventoryDataSource, orderDataSource); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryDataSource, productId); + Application application = new Application(inventoryDataSource, orderDataSource); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance, finalBalance); + } + + @BeforeClass + public static void setUp() throws SQLException { + + inventoryDataSource = getDataSource("db1"); + orderDataSource = getDataSource("db2"); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + String createInventoryTable = "create table Inventory ( " + " productId VARCHAR ( 100 ) PRIMARY KEY, balance INT )"; + String createInventoryRow = "insert into Inventory values ( '" + productId + "', 10000 )"; + Statement s1 = inventoryConnection.createStatement(); + try { + s1.executeUpdate(createInventoryTable); + } catch (Exception e) { + System.out.println("Inventory table exists"); + } + try { + s1.executeUpdate(createInventoryRow); + } catch (Exception e) { + System.out.println("Product row exists"); + } + s1.close(); + String createOrderTable = "create table Orders ( orderId VARCHAR ( 100 ) PRIMARY KEY, productId VARCHAR ( 100 ), amount INT NOT NULL CHECK (amount <= 5) )"; + Statement s2 = orderConnection.createStatement(); + try { + s2.executeUpdate(createOrderTable); + } catch (Exception e) { + System.out.println("Orders table exists"); + } + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } + + private static DataSource getDataSource(String db) { + + DataSource ds; + AtomikosDataSourceBean ads = new AtomikosDataSourceBean(); + ads.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties properties = new Properties(); + properties.put("databaseName", db); + properties.put("createDatabase", "create"); + ads.setXaProperties(properties); + ads.setUniqueResourceName(db); + ads.setPoolSize(10); // optional + ads.setBorrowConnectionTimeout(10); // optional + ds = ads; + return ds; + + } + + private static long getBalance(DataSource inventoryDataSource, String productId) throws Exception { + + UserTransactionImp utx = new UserTransactionImp(); + utx.begin(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "select balance from Inventory where productId='" + productId + "'"; + ResultSet rs1 = s1.executeQuery(q1); + if (rs1 == null || !rs1.next()) + throw new Exception("Product not found: " + productId); + long balance = rs1.getLong(1); + inventoryConnection.close(); + utx.commit(); + return balance; + + } + +} diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java new file mode 100644 index 0000000000..0c9392eac4 --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java @@ -0,0 +1,108 @@ +package com.baeldung.atomikos.spring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.junit.Before; +import org.junit.Ignore; +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.baeldung.atomikos.spring.config.Config; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Config.class }) +public class ApplicationUnitTest { + + private static String productId = UUID.randomUUID() + .toString(); + + @Autowired + Application application; + + @Autowired + DataSource inventoryDataSource; + + @Autowired + DataSource orderDataSource; + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryDataSource, productId); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryDataSource, productId); + try { + application.placeOrder(productId, amount); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance, finalBalance); + } + + @Before + public void setUp() throws SQLException { + + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + String createInventoryTable = "create table Inventory ( " + " productId VARCHAR ( 100 ) PRIMARY KEY, balance INT )"; + String createInventoryRow = "insert into Inventory values ( '" + productId + "', 10000 )"; + Statement s1 = inventoryConnection.createStatement(); + try { + s1.executeUpdate(createInventoryTable); + } catch (Exception e) { + System.out.println("Inventory table exists"); + } + try { + s1.executeUpdate(createInventoryRow); + } catch (Exception e) { + System.out.println("Product row exists"); + } + s1.close(); + String createOrderTable = "create table Orders ( orderId VARCHAR ( 100 ) PRIMARY KEY, productId VARCHAR ( 100 ), amount INT NOT NULL CHECK (amount <= 5) )"; + Statement s2 = orderConnection.createStatement(); + try { + s2.executeUpdate(createOrderTable); + } catch (Exception e) { + System.out.println("Orders table exists"); + } + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } + + private static long getBalance(DataSource inventoryDataSource, String productId) throws Exception { + + Connection inventoryConnection = inventoryDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "select balance from Inventory where productId='" + productId + "'"; + ResultSet rs1 = s1.executeQuery(q1); + if (rs1 == null || !rs1.next()) + throw new Exception("Product not found: " + productId); + long balance = rs1.getLong(1); + inventoryConnection.close(); + return balance; + + } + +} diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java new file mode 100644 index 0000000000..e6a3c1982c --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.atomikos.spring.jpa; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.SQLException; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Ignore; +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.baeldung.atomikos.spring.jpa.config.Config; +import com.baeldung.atomikos.spring.jpa.inventory.Inventory; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryConfig; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryRepository; +import com.baeldung.atomikos.spring.jpa.order.OrderConfig; +import com.baeldung.atomikos.spring.jpa.order.OrderRepository; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Config.class, InventoryConfig.class, OrderConfig.class }) +public class ApplicationUnitTest { + + private static String productId = UUID.randomUUID() + .toString(); + + @Autowired + Application application; + + @Autowired + InventoryRepository inventoryRepository; + + @Autowired + OrderRepository orderRepository; + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryRepository, productId); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryRepository, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryRepository, productId); + try { + application.placeOrder(productId, amount); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + long finalBalance = getBalance(inventoryRepository, productId); + assertEquals(initialBalance, finalBalance); + } + + @Before + public void setUp() throws SQLException { + + Inventory inventory = new Inventory(); + inventory.setProductId(productId); + inventory.setBalance(new Long(10000)); + inventoryRepository.save(inventory); + + } + + private static long getBalance(InventoryRepository inventoryRepository, String productId) throws Exception { + + return inventoryRepository.findOne(productId) + .getBalance(); + + } + +} diff --git a/core-kotlin-2/src/main/resources/logback.xml b/atomikos/src/test/resources/logback.xml similarity index 100% rename from core-kotlin-2/src/main/resources/logback.xml rename to atomikos/src/test/resources/logback.xml diff --git a/atomikos/src/test/resources/transactions.properties b/atomikos/src/test/resources/transactions.properties new file mode 100644 index 0000000000..8e027032fa --- /dev/null +++ b/atomikos/src/test/resources/transactions.properties @@ -0,0 +1 @@ +com.atomikos.icatch.file=logs \ No newline at end of file diff --git a/atomix/pom.xml b/atomix/pom.xml index 7821ef26d7..53c7a6c0ba 100644 --- a/atomix/pom.xml +++ b/atomix/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.atomix.io atomix diff --git a/aws-lambda/pom.xml b/aws-lambda/pom.xml index 12be77baef..e1d2c7df27 100644 --- a/aws-lambda/pom.xml +++ b/aws-lambda/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 aws-lambda 0.1.0-SNAPSHOT diff --git a/aws-reactive/README.md b/aws-reactive/README.md new file mode 100644 index 0000000000..1abf987b52 --- /dev/null +++ b/aws-reactive/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [AWS S3 with Java – Reactive Support](https://www.baeldung.com/java-aws-s3-reactive) diff --git a/aws-reactive/pom.xml b/aws-reactive/pom.xml index b3fcb24902..d4f0e5e231 100644 --- a/aws-reactive/pom.xml +++ b/aws-reactive/pom.xml @@ -1,105 +1,107 @@ - - 4.0.0 - + + 4.0.0 + com.baeldung parent-modules 1.0.0-SNAPSHOT - - aws-reactive - 0.0.1-SNAPSHOT - aws-reactive - AWS Reactive Sample - - 1.8 - + aws-reactive + 0.0.1-SNAPSHOT + aws-reactive + AWS Reactive Sample - - + + - - - org.springframework.boot - spring-boot-dependencies - 2.2.1.RELEASE - pom - import - + + + org.springframework.boot + spring-boot-dependencies + ${spring.version} + pom + import + - - software.amazon.awssdk - bom - 2.10.27 - pom - import - - - + + software.amazon.awssdk + bom + ${awssdk.version} + pom + import + + + - - - org.springframework.boot - spring-boot-starter-webflux - + + + org.springframework.boot + spring-boot-starter-webflux + - - software.amazon.awssdk - s3 - compile - + + software.amazon.awssdk + s3 + compile + - - netty-nio-client - software.amazon.awssdk - compile - + + netty-nio-client + software.amazon.awssdk + compile + - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + - - io.projectreactor - reactor-test - test - - - org.springframework.boot - spring-boot-devtools - runtime - - - org.springframework.boot - spring-boot-configuration-processor - - - org.projectlombok - lombok - - + + io.projectreactor + reactor-test + test + + + org.springframework.boot + spring-boot-devtools + runtime + + + org.springframework.boot + spring-boot-configuration-processor + + + org.projectlombok + lombok + + - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + 1.8 + 2.2.1.RELEASE + 2.10.27 + diff --git a/aws/pom.xml b/aws/pom.xml index 19057d48e9..be0cdfdd43 100644 --- a/aws/pom.xml +++ b/aws/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 aws 0.1.0-SNAPSHOT diff --git a/axon/pom.xml b/axon/pom.xml index be74b38fa6..f6c43c7cbd 100644 --- a/axon/pom.xml +++ b/axon/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 axon axon diff --git a/azure/pom.xml b/azure/pom.xml index 7134a47cd7..dc58ffa595 100644 --- a/azure/pom.xml +++ b/azure/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 azure 0.1 diff --git a/azure/src/main/resources/application.properties b/azure/src/main/resources/application.properties index 32ee873194..1c92245a6f 100644 --- a/azure/src/main/resources/application.properties +++ b/azure/src/main/resources/application.properties @@ -5,7 +5,7 @@ spring.jpa.hibernate.ddl-auto=create logging.file=azure.log logging.level.root=info -spring.datasource.url=jdbc:h2:file:~/test +spring.datasource.url=jdbc:h2:mem:azure-test-db spring.datasource.username=sa spring.datasource.password= diff --git a/bazel/bazelapp/README.md b/bazel/bazelapp/README.md deleted file mode 100644 index 528f797c21..0000000000 --- a/bazel/bazelapp/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Building Java Applications with Bazel](https://www.baeldung.com/bazel-build-tool) diff --git a/bazel/bazelapp/pom.xml b/bazel/bazelapp/pom.xml index 6440c26cd6..54519afff8 100644 --- a/bazel/bazelapp/pom.xml +++ b/bazel/bazelapp/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 bazelapp bazelapp diff --git a/bazel/bazelgreeting/README.md b/bazel/bazelgreeting/README.md deleted file mode 100644 index 528f797c21..0000000000 --- a/bazel/bazelgreeting/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Building Java Applications with Bazel](https://www.baeldung.com/bazel-build-tool) diff --git a/bazel/bazelgreeting/pom.xml b/bazel/bazelgreeting/pom.xml index ae8a6e4080..7742f92206 100644 --- a/bazel/bazelgreeting/pom.xml +++ b/bazel/bazelgreeting/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 bazelgreeting bazelgreeting diff --git a/bazel/pom.xml b/bazel/pom.xml index b1585cc73b..6673e09dbc 100644 --- a/bazel/pom.xml +++ b/bazel/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 bazel bazel diff --git a/blade/pom.xml b/blade/pom.xml index e302f33c51..178d1afb52 100644 --- a/blade/pom.xml +++ b/blade/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 blade blade @@ -106,7 +107,7 @@ java -jar - sample-blade-app.jar + blade.jar @@ -124,7 +125,7 @@ maven-assembly-plugin - 3.1.0 + ${assembly.plugin.version} ${project.build.finalName} false @@ -161,6 +162,7 @@ 3.11.1 3.0.0-M3 0.7 + 3.1.0 diff --git a/bootique/pom.xml b/bootique/pom.xml index 8e40b3ec8d..2cbcd671bb 100644 --- a/bootique/pom.xml +++ b/bootique/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.bootique bootique diff --git a/cas/README.md b/cas/README.md index 16775a8a02..6ceeaea0c4 100644 --- a/cas/README.md +++ b/cas/README.md @@ -1,7 +1,18 @@ ## CAS -This module contains articles about the Central Authentication Service (CAS) +This module contains articles about the Central Authentication Service (CAS). + +The module consists of 2 submodules: +1. `cas-server` - it requires JDK11 and uses the Gradle War Overlay style to ease setup and deployment. To start the server, simply run: + +`./gradlew run + -Dorg.gradle.java.home=$JAVA11_HOME + -Pargs="-Dcas.standalone.configurationDirectory=/cas-server/src/main/resources/etc/cas/config"` + +The server starts at https://localhost:8443. `casuser`/`Mellon` are the username and password for logging in. + +2. `cas-secured-app` - A Maven based Springboot Application ### Relevant Articles: -- [CAS SSO With Spring Security](baeldung.com/spring-security-cas-sso) \ No newline at end of file +- [CAS SSO With Spring Security](https://www.baeldung.com/spring-security-cas-sso) \ No newline at end of file diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 63d5d43417..426d65c32b 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 cas-secured-app cas-secured-app @@ -9,11 +11,15 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 + + 2.2.6.RELEASE + + org.springframework.boot diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java deleted file mode 100644 index 25cbb9bc9b..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.cassecuredapp; - -import org.jasig.cas.client.session.SingleSignOutFilter; -import org.jasig.cas.client.session.SingleSignOutHttpSessionListener; -import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; -import org.jasig.cas.client.validation.TicketValidator; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Primary; -import org.springframework.context.event.EventListener; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.authentication.CasAuthenticationProvider; -import org.springframework.security.cas.web.CasAuthenticationEntryPoint; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.logout.LogoutFilter; -import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; - -import javax.servlet.http.HttpSessionEvent; - -@SpringBootApplication -public class CasSecuredAppApplication { - - public static void main(String[] args) { - SpringApplication.run(CasSecuredAppApplication.class, args); - } - - @Bean - public ServiceProperties serviceProperties() { - ServiceProperties serviceProperties = new ServiceProperties(); - serviceProperties.setService("http://localhost:9000/login/cas"); - serviceProperties.setSendRenew(false); - return serviceProperties; - } - - @Bean - @Primary - public AuthenticationEntryPoint authenticationEntryPoint(ServiceProperties sP) { - CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); - entryPoint.setLoginUrl("https://localhost:6443/cas/login"); - entryPoint.setServiceProperties(sP); - return entryPoint; - } - - @Bean - public TicketValidator ticketValidator() { - return new Cas30ServiceTicketValidator("https://localhost:6443/cas"); - } - - @Bean - public CasAuthenticationProvider casAuthenticationProvider() { - CasAuthenticationProvider provider = new CasAuthenticationProvider(); - provider.setServiceProperties(serviceProperties()); - provider.setTicketValidator(ticketValidator()); - provider.setUserDetailsService((s) -> new User("test@test.com", "smatt", - true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); - provider.setKey("CAS_PROVIDER_LOCALHOST_9000"); - return provider; - } - - - @Bean - public SecurityContextLogoutHandler securityContextLogoutHandler() { - return new SecurityContextLogoutHandler(); - } - - @Bean - public LogoutFilter logoutFilter() { - LogoutFilter logoutFilter = new LogoutFilter( - "https://localhost:6443/cas/logout", securityContextLogoutHandler()); - logoutFilter.setFilterProcessesUrl("/logout/cas"); - return logoutFilter; - } - - @Bean - public SingleSignOutFilter singleSignOutFilter() { - SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); - singleSignOutFilter.setCasServerUrlPrefix("https://localhost:6443/cas"); - singleSignOutFilter.setIgnoreInitConfiguration(true); - return singleSignOutFilter; - } - - @EventListener - public SingleSignOutHttpSessionListener singleSignOutHttpSessionListener(HttpSessionEvent event) { - return new SingleSignOutHttpSessionListener(); - } -} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java new file mode 100644 index 0000000000..4a2c609758 --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java @@ -0,0 +1,97 @@ +package com.baeldung.cassecuredapp; + +import org.jasig.cas.client.session.SingleSignOutFilter; +import org.jasig.cas.client.session.SingleSignOutHttpSessionListener; +import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; +import org.jasig.cas.client.validation.TicketValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.context.event.EventListener; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.cas.ServiceProperties; +import org.springframework.security.cas.authentication.CasAuthenticationProvider; +import org.springframework.security.cas.web.CasAuthenticationEntryPoint; +import org.springframework.security.cas.web.CasAuthenticationFilter; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; +import org.springframework.security.web.authentication.logout.LogoutFilter; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; + +import javax.servlet.http.HttpSessionEvent; + +@SpringBootApplication +public class CasSecuredApplication { + + private static final Logger logger = LoggerFactory.getLogger(CasSecuredApplication.class); + + public static void main(String... args) { + SpringApplication.run(CasSecuredApplication.class, args); + } + + @Bean + public CasAuthenticationFilter casAuthenticationFilter( + AuthenticationManager authenticationManager, + ServiceProperties serviceProperties) throws Exception { + CasAuthenticationFilter filter = new CasAuthenticationFilter(); + filter.setAuthenticationManager(authenticationManager); + filter.setServiceProperties(serviceProperties); + return filter; + } + + @Bean + public ServiceProperties serviceProperties() { + logger.info("service properties"); + ServiceProperties serviceProperties = new ServiceProperties(); + serviceProperties.setService("http://cas-client:8900/login/cas"); + serviceProperties.setSendRenew(false); + return serviceProperties; + } + + @Bean + public TicketValidator ticketValidator() { + return new Cas30ServiceTicketValidator("https://localhost:8443"); + } + + @Bean + public CasAuthenticationProvider casAuthenticationProvider( + TicketValidator ticketValidator, + ServiceProperties serviceProperties) { + CasAuthenticationProvider provider = new CasAuthenticationProvider(); + provider.setServiceProperties(serviceProperties); + provider.setTicketValidator(ticketValidator); + provider.setUserDetailsService( + s -> new User("test@test.com", "Mellon", true, true, true, true, + AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); + provider.setKey("CAS_PROVIDER_LOCALHOST_8900"); + return provider; + } + + + @Bean + public SecurityContextLogoutHandler securityContextLogoutHandler() { + return new SecurityContextLogoutHandler(); + } + + @Bean + public LogoutFilter logoutFilter() { + LogoutFilter logoutFilter = new LogoutFilter("https://localhost:8443/logout", securityContextLogoutHandler()); + logoutFilter.setFilterProcessesUrl("/logout/cas"); + return logoutFilter; + } + + @Bean + public SingleSignOutFilter singleSignOutFilter() { + SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); + singleSignOutFilter.setCasServerUrlPrefix("https://localhost:8443"); + singleSignOutFilter.setLogoutCallbackPath("/exit/cas"); + singleSignOutFilter.setIgnoreInitConfiguration(true); + return singleSignOutFilter; + } + +} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java deleted file mode 100644 index 2eabed49e1..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.cassecuredapp.config; - -import org.jasig.cas.client.session.SingleSignOutFilter; -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.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.ProviderManager; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.authentication.CasAuthenticationProvider; -import org.springframework.security.cas.web.CasAuthenticationFilter; -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.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.logout.LogoutFilter; - -import java.util.Arrays; - -@EnableWebSecurity -@Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - private AuthenticationProvider authenticationProvider; - private AuthenticationEntryPoint authenticationEntryPoint; - private SingleSignOutFilter singleSignOutFilter; - private LogoutFilter logoutFilter; - - @Autowired - public SecurityConfig(CasAuthenticationProvider casAuthenticationProvider, AuthenticationEntryPoint eP, - LogoutFilter lF - , SingleSignOutFilter ssF - ) { - this.authenticationProvider = casAuthenticationProvider; - this.authenticationEntryPoint = eP; - - this.logoutFilter = lF; - this.singleSignOutFilter = ssF; - - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .regexMatchers("/secured.*", "/login") - .authenticated() - .and() - .authorizeRequests() - .regexMatchers("/") - .permitAll() - .and() - .httpBasic() - .authenticationEntryPoint(authenticationEntryPoint) - .and() - .logout().logoutSuccessUrl("/logout") - .and() - .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) - .addFilterBefore(logoutFilter, LogoutFilter.class); - - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(authenticationProvider); - } - - @Override - protected AuthenticationManager authenticationManager() throws Exception { - return new ProviderManager(Arrays.asList(authenticationProvider)); - } - - @Bean - public CasAuthenticationFilter casAuthenticationFilter(ServiceProperties sP) throws Exception { - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setServiceProperties(sP); - filter.setAuthenticationManager(authenticationManager()); - return filter; - } - -} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java new file mode 100644 index 0000000000..b0c3c68387 --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java @@ -0,0 +1,79 @@ +package com.baeldung.cassecuredapp.config; + +import org.jasig.cas.client.session.SingleSignOutFilter; +import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; +import org.jasig.cas.client.validation.TicketValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.cas.ServiceProperties; +import org.springframework.security.cas.authentication.CasAuthenticationProvider; +import org.springframework.security.cas.web.CasAuthenticationEntryPoint; +import org.springframework.security.cas.web.CasAuthenticationFilter; +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.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.authentication.logout.LogoutFilter; + +import java.util.Collections; + +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class); + private SingleSignOutFilter singleSignOutFilter; + private LogoutFilter logoutFilter; + private CasAuthenticationProvider casAuthenticationProvider; + private ServiceProperties serviceProperties; + + @Autowired + public WebSecurityConfig(SingleSignOutFilter singleSignOutFilter, LogoutFilter logoutFilter, + CasAuthenticationProvider casAuthenticationProvider, + ServiceProperties serviceProperties) { + this.logoutFilter = logoutFilter; + this.singleSignOutFilter = singleSignOutFilter; + this.serviceProperties = serviceProperties; + this.casAuthenticationProvider = casAuthenticationProvider; + } + + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().antMatchers( "/secured", "/login").authenticated() + .and() + .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()) + .and() + .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) + .addFilterBefore(logoutFilter, LogoutFilter.class) + .csrf().ignoringAntMatchers("/exit/cas"); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(casAuthenticationProvider); + } + + @Bean + @Override + protected AuthenticationManager authenticationManager() throws Exception { + return new ProviderManager(Collections.singletonList(casAuthenticationProvider)); + } + + public AuthenticationEntryPoint authenticationEntryPoint() { + CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); + entryPoint.setLoginUrl("https://localhost:8443/login"); + entryPoint.setServiceProperties(serviceProperties); + return entryPoint; + } + + + +} 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 2c88b74a83..16254c8cbd 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.log4j.LogManager; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler; @@ -13,24 +13,27 @@ import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY; + @Controller public class AuthController { - private Logger logger = LogManager.getLogger(AuthController.class); - - @GetMapping("/logout") - public String logout( - HttpServletRequest request, HttpServletResponse response, SecurityContextLogoutHandler logoutHandler) { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - logoutHandler.logout(request, response, auth ); - new CookieClearingLogoutHandler(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY).logout(request, response, auth); - return "auth/logout"; - } - + private Logger logger = LoggerFactory.getLogger(AuthController.class); @GetMapping("/login") public String login() { + logger.info("/login called"); return "redirect:/secured"; } + + @GetMapping("/logout") + public String logout(HttpServletRequest request, HttpServletResponse response, SecurityContextLogoutHandler logoutHandler) { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + CookieClearingLogoutHandler cookieClearingLogoutHandler = new CookieClearingLogoutHandler(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + cookieClearingLogoutHandler.logout(request, response, auth); + logoutHandler.logout(request, response, auth); + return "auth/logout"; + } + } diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java index 75956cf493..d4800206d4 100644 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java @@ -1,15 +1,19 @@ package com.baeldung.cassecuredapp.controllers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - @Controller public class IndexController { + private Logger logger = LoggerFactory.getLogger(IndexController.class); + @GetMapping("/") public String index() { + logger.info("Index controller called"); return "index"; } + } diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java new file mode 100644 index 0000000000..0b3ab6199f --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java @@ -0,0 +1,30 @@ +package com.baeldung.cassecuredapp.controllers; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class SecuredController { + + private Logger logger = LoggerFactory.getLogger(SecuredController.class); + + @GetMapping("/secured") + public String securedIndex(ModelMap modelMap) { + + logger.info("/secured called"); + + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); + + if(auth.getPrincipal() instanceof UserDetails) + modelMap.put("username", ((UserDetails) auth.getPrincipal()).getUsername()); + + return "secure/index"; + } +} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java deleted file mode 100644 index 9a872d1f40..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.cassecuredapp.controllers; - -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping(value = "/secured") -public class SecuredPageController { - - @GetMapping - public String index(ModelMap modelMap) { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - if( auth != null && auth.getPrincipal() != null - && auth.getPrincipal() instanceof UserDetails) { - modelMap.put("username", ((UserDetails) auth.getPrincipal()).getUsername()); - } - return "secure/index"; - } -} diff --git a/cas/cas-secured-app/src/main/resources/application.properties b/cas/cas-secured-app/src/main/resources/application.properties index 99802c632f..f8789997d5 100644 --- a/cas/cas-secured-app/src/main/resources/application.properties +++ b/cas/cas-secured-app/src/main/resources/application.properties @@ -1 +1,2 @@ -server.port=9000 \ No newline at end of file +server.port=8900 +spring.freemarker.suffix=.ftl \ No newline at end of file diff --git a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java deleted file mode 100644 index 2f2644e2ea..0000000000 --- a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.cassecuredapp; - -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 CasSecuredAppApplicationIntegrationTest { - - @Test - public void contextLoads() { - } - -} diff --git a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java new file mode 100644 index 0000000000..de13f6665d --- /dev/null +++ b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.cassecuredapp; + +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 CasSecuredApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/cas/cas-server/.factorypath b/cas/cas-server/.factorypath deleted file mode 100644 index 006c761796..0000000000 --- a/cas/cas-server/.factorypath +++ /dev/null @@ -1,228 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/.gitignore b/cas/cas-server/.gitignore old mode 100644 new mode 100755 index 5304519922..6121b5ea9d --- a/cas/cas-server/.gitignore +++ b/cas/cas-server/.gitignore @@ -2,6 +2,8 @@ !/.project .project .settings +.history +.vscode target/ .idea/ .DS_Store @@ -9,6 +11,11 @@ target/ overlays/ .gradle/ build/ +log/ bin/ +*.war *.iml *.log +tmp/ +./apache-tomcat +apache-tomcat.zip \ No newline at end of file diff --git a/cas/cas-server/.mergify.yml b/cas/cas-server/.mergify.yml new file mode 100644 index 0000000000..4fcbdbe4ac --- /dev/null +++ b/cas/cas-server/.mergify.yml @@ -0,0 +1,32 @@ +# +# Licensed to Apereo under one or more contributor license +# agreements. See the NOTICE file distributed with this work +# for additional information regarding copyright ownership. +# Apereo 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 the following location: +# +# 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. +# + +pull_request_rules: +- name: automatic merge by dependabot + conditions: + - status-success=continuous-integration/travis-ci/pr + - status-success=WIP + - "#changes-requested-reviews-by=0" + - base=master + - label=dependencies + actions: + merge: + method: merge + strict: true + delete_head_branch: \ No newline at end of file diff --git a/cas/cas-server/.travis.yml b/cas/cas-server/.travis.yml new file mode 100644 index 0000000000..8347dd1719 --- /dev/null +++ b/cas/cas-server/.travis.yml @@ -0,0 +1,62 @@ +language: java +sudo: required +dist: trusty +services: + - docker +branches: + only: + - master +before_cache: + - rm -rf $HOME/.gradle/caches/5.*/ + - rm -rf $HOME/.gradle/caches/4.*/ + - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ + - find ~/.gradle/caches/ -name "*.lock" -type f -delete +cache: + bundler: false + cargo: false + directories: + - $HOME/.m2 + - $HOME/.npm/ + - $HOME/.gradle/caches/ + - $HOME/.gradle/wrapper/ +env: + global: + - JAVA_OPTS="-Xms512m -Xmx4048m -Xss128m -XX:ReservedCodeCacheSize=512m -XX:+UseG1GC -Xverify:none -server" + - GRADLE_OPTS="-Xms512m -Xmx1024m -Xss128m -XX:ReservedCodeCacheSize=512m -XX:+UseG1GC -Xverify:none -server" +jdk: +- openjdk11 +before_install: +- echo -e "Configuring Gradle wrapper...\n" +- mkdir -p ~/.gradle && echo "org.gradle.daemon=false" >> ~/.gradle/gradle.properties +- chmod -R 777 ./gradlew +- chmod -R 777 *.sh +install: true +stages: + - build + - validate + - docker +jobs: + include: + - stage: build + script: ./gradlew clean build --stacktrace --no-daemon --refresh-dependencies -Dorg.gradle.internal.http.socketTimeout=600000 -Dorg.gradle.internal.http.connectionTimeout=600000 + name: "Build CAS" + ############################################ + - stage: validate + script: ./gradlew downloadShell + name: "Download CAS Shell" + - stage: validate + script: ./gradlew listTemplateViews + name: "List CAS Template Views" + - stage: validate + script: ./gradlew explodeWar + name: "Unzip CAS Web Application" + ############################################ + - stage: docker + script: ./gradlew build jibDockerBuild --stacktrace --no-daemon --refresh-dependencies + name: "Build Docker Image via Jib" + - stage: docker + script: docker-compose build + name: "Build Docker Image via Docker Compose" + - stage: docker + script: ./docker-build.sh + name: "Build Docker Image" \ No newline at end of file diff --git a/cas/cas-server/Dockerfile b/cas/cas-server/Dockerfile new file mode 100644 index 0000000000..b2f15ef4c3 --- /dev/null +++ b/cas/cas-server/Dockerfile @@ -0,0 +1,40 @@ +FROM adoptopenjdk/openjdk11:alpine-slim AS overlay + +RUN mkdir -p cas-overlay +COPY ./src cas-overlay/src/ +COPY ./gradle/ cas-overlay/gradle/ +COPY ./gradlew ./settings.gradle ./build.gradle ./gradle.properties /cas-overlay/ + +RUN mkdir -p ~/.gradle \ + && echo "org.gradle.daemon=false" >> ~/.gradle/gradle.properties \ + && echo "org.gradle.configureondemand=true" >> ~/.gradle/gradle.properties \ + && cd cas-overlay \ + && chmod 750 ./gradlew \ + && ./gradlew --version; + +RUN cd cas-overlay \ + && ./gradlew clean build --parallel; + +FROM adoptopenjdk/openjdk11:alpine-jre AS cas + +LABEL "Organization"="Apereo" +LABEL "Description"="Apereo CAS" + +RUN cd / \ + && mkdir -p /etc/cas/config \ + && mkdir -p /etc/cas/services \ + && mkdir -p /etc/cas/saml \ + && mkdir -p cas-overlay; + +COPY etc/cas/ /etc/cas/ +COPY etc/cas/config/ /etc/cas/config/ +COPY etc/cas/services/ /etc/cas/services/ +COPY etc/cas/saml/ /etc/cas/saml/ +COPY --from=overlay cas-overlay/build/libs/cas.war cas-overlay/ + +EXPOSE 8080 8443 + +ENV PATH $PATH:$JAVA_HOME/bin:. + +WORKDIR cas-overlay +ENTRYPOINT ["java", "-server", "-noverify", "-Xmx2048M", "-jar", "cas.war"] diff --git a/cas/cas-server/README.md b/cas/cas-server/README.md deleted file mode 100644 index 44cfa2246c..0000000000 --- a/cas/cas-server/README.md +++ /dev/null @@ -1,105 +0,0 @@ -CAS Overlay Template -============================ - -Generic CAS WAR overlay to exercise the latest versions of CAS. This overlay could be freely used as a starting template for local CAS war overlays. The CAS services management overlay is available [here](https://github.com/apereo/cas-services-management-overlay). - -# Versions - -```xml -5.3.x -``` - -# Requirements - -* JDK 1.8+ - -# Configuration - -The `etc` directory contains the configuration files and directories that need to be copied to `/etc/cas/config`. - -# Build - -To see what commands are available to the build script, run: - -```bash -./build.sh help -``` - -To package the final web application, run: - -```bash -./build.sh package -``` - -To update `SNAPSHOT` versions run: - -```bash -./build.sh package -U -``` - -# Deployment - -- Create a keystore file `thekeystore` under `/etc/cas`. Use the password `changeit` for both the keystore and the key/certificate entries. -- Ensure the keystore is loaded up with keys and certificates of the server. - -On a successful deployment via the following methods, CAS will be available at: - -* `http://cas.server.name:8080/cas` -* `https://cas.server.name:8443/cas` - -## Executable WAR - -Run the CAS web application as an executable WAR. - -```bash -./build.sh run -``` - -## Spring Boot - -Run the CAS web application as an executable WAR via Spring Boot. This is most useful during development and testing. - -```bash -./build.sh bootrun -``` - -### 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/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. - -```xml --tomcat -``` - -## Windows Build - -If you are building on windows, try `build.cmd` instead of `build.sh`. Arguments are similar but for usage, run: - -``` -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 -``` - -### Relevant Articles: - -- [CAS SSO With Spring Security](https://www.baeldung.com/spring-security-cas-sso) diff --git a/cas/cas-server/build.cmd b/cas/cas-server/build.cmd deleted file mode 100644 index 2cf9262afe..0000000000 --- a/cas/cas-server/build.cmd +++ /dev/null @@ -1,102 +0,0 @@ -@echo off - -@set JAVA_ARGS=-Xms500m -Xmx1g -@set CAS_DIR=\etc\cas -@set CONFIG_DIR=\etc\cas\config - -@rem Call this script with DNAME and CERT_SUBJ_ALT_NAMES already set to override -@if "%DNAME%" == "" set DNAME=CN=cas.example.org,OU=Example,OU=Org,C=US -@rem List other host names or ip addresses you want in your certificate, may help with host name verification, -@rem if client apps make https connection for ticket validation and compare name in cert (include sub. alt. names) -@rem to name used to access CAS -@if "%CERT_SUBJ_ALT_NAMES%" == "" set CERT_SUBJ_ALT_NAMES=dns:example.org,dns:localhost,dns:%COMPUTERNAME%,ip:127.0.0.1 - -@rem Check for mvn in path, use it if found, otherwise use maven wrapper -@set MAVEN_CMD=mvn -@where /q mvn -@if %ERRORLEVEL% neq 0 set MAVEN_CMD=.\mvnw.bat - -@if "%1" == "" call:help -@if "%1" == "copy" call:copy -@if "%1" == "clean" call:clean %2 %3 %4 -@if "%1" == "package" call:package %2 %3 %4 -@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 - -:copy - @echo "Creating configuration directory under %CONFIG_DIR%" - if not exist %CONFIG_DIR% mkdir %CONFIG_DIR% - - @echo "Copying configuration files from etc/cas to /etc/cas" - xcopy /S /Y etc\cas\* \etc\cas -@goto:eof - -:help - @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 - -:clean - call %MAVEN_CMD% clean %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:package - call %MAVEN_CMD% clean package -T 5 %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:bootrun - call %MAVEN_CMD% clean package spring-boot:run -T 5 %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:debug - call:package %1 %2 %3 & java %JAVA_ARGS% -Xdebug -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=n -jar target/cas.war -@goto:eof - -:run - 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 ( - @echo Java keytool.exe not found in path. - exit /b 1 - ) else ( - if not exist %CAS_DIR% mkdir %CAS_DIR% - @echo on - @echo Generating self-signed SSL cert for %DNAME% in %CAS_DIR%\thekeystore - keytool -genkeypair -alias cas -keyalg RSA -keypass changeit -storepass changeit -keystore %CAS_DIR%\thekeystore -dname %DNAME% -ext SAN=%CERT_SUBJ_ALT_NAMES% - @echo Exporting cert for use in trust store (used by cas clients) - 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.gradle b/cas/cas-server/build.gradle new file mode 100644 index 0000000000..41381e2d8f --- /dev/null +++ b/cas/cas-server/build.gradle @@ -0,0 +1,106 @@ +buildscript { + repositories { + mavenLocal() + mavenCentral() + jcenter() + maven { url "https://repo.spring.io/libs-milestone" } + maven { url "https://repo.spring.io/libs-snapshot" } + maven { url "https://plugins.gradle.org/m2/" } + } + dependencies { + classpath "de.undercouch:gradle-download-task:${project.gradleDownloadTaskVersion}" + classpath "org.springframework.boot:spring-boot-gradle-plugin:${project.springBootVersion}" + classpath "gradle.plugin.com.google.cloud.tools:jib-gradle-plugin:${project.jibVersion}" + classpath "io.freefair.gradle:maven-plugin:${project.gradleMavenPluginVersion}" + } +} + +repositories { + mavenLocal() + mavenCentral() + jcenter() + maven { url "https://oss.sonatype.org/content/repositories/snapshots" } + maven { url "https://build.shibboleth.net/nexus/content/repositories/releases/" } + maven { url "https://repo.spring.io/milestone/" } + maven { url "https://repo.spring.io/snapshot/" } + maven { url "https://oss.jfrog.org/artifactory/oss-snapshot-local" } +} + +def casServerVersion = project.'cas.version' +def casWebApplicationBinaryName = "cas.war" + +project.ext."casServerVersion" = casServerVersion +project.ext."casWebApplicationBinaryName" = casWebApplicationBinaryName + +apply plugin: "io.freefair.war-overlay" +apply from: rootProject.file("gradle/tasks.gradle") + +apply plugin: "war" +apply plugin: "eclipse" +apply plugin: "idea" + +apply from: rootProject.file("gradle/springboot.gradle") +apply from: rootProject.file("gradle/dockerjib.gradle") + +dependencies { + // Other CAS dependencies/modules may be listed here... + compile "org.apereo.cas:cas-server-support-json-service-registry:${casServerVersion}" + compile "org.apereo.cas:cas-server-support-jdbc:${casServerVersion}" +} + +tasks.findByName("jibDockerBuild") + .dependsOn(copyWebAppIntoJib, copyConfigIntoJib) + .finalizedBy(deleteWebAppFromJib) + +tasks.findByName("jib") + .dependsOn(copyWebAppIntoJib, copyConfigIntoJib) + .finalizedBy(deleteWebAppFromJib) + +configurations.all { + resolutionStrategy { + cacheChangingModulesFor 0, "seconds" + cacheDynamicVersionsFor 0, "seconds" + + preferProjectModules() + + def failIfConflict = project.hasProperty("failOnVersionConflict") && Boolean.valueOf(project.getProperty("failOnVersionConflict")) + if (failIfConflict) { + failOnVersionConflict() + } + } +} + +eclipse { + classpath { + downloadSources = true + downloadJavadoc = true + } +} + +idea { + module { + downloadJavadoc = true + downloadSources = true + } +} + +bootWar { + entryCompression = ZipEntryCompression.STORED + overlays { + // https://docs.freefair.io/gradle-plugins/current/reference/#_io_freefair_war_overlay + // Note: The "excludes" property is only for files in the war dependency. + // If a jar is excluded from the war, it could be brought back into the final war as a dependency + // of non-war dependencies. Those should be excluded via normal gradle dependency exclusions. + cas { + from "org.apereo.cas:cas-server-webapp${project.appServer}:${casServerVersion}@war" + provided = false + //excludes = ["WEB-INF/lib/somejar-1.0*"] + } + } +} + + +wrapper { + distributionType = Wrapper.DistributionType.BIN + gradleVersion = "${project.gradleVersion}" +} diff --git a/cas/cas-server/build.sh b/cas/cas-server/build.sh deleted file mode 100644 index 4d80aa2593..0000000000 --- a/cas/cas-server/build.sh +++ /dev/null @@ -1,189 +0,0 @@ -#!/bin/bash - - -function copy() { - echo -e "Creating configuration directory under /etc/cas" - mkdir -p /etc/cas/config - - echo -e "Copying configuration files from etc/cas to /etc/cas" - cp -rfv etc/cas/* /etc/cas -} - -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" - 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" - 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 -} - -function bootrun() { - shift - ./mvnw clean package spring-boot:run -P bootiful -T 5 "$@" -} - -function debug() { - package && java -Xdebug -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=n -jar target/cas.war -} - -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 - copy - fi - which keytool - if [[ $? -ne 0 ]] ; then - 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}" - CERT_SUBJ_ALT_NAMES="${CERT_SUBJ_ALT_NAMES:-dns:example.org,dns:localhost,ip:127.0.0.1}" - echo "Generating keystore for CAS with DN ${DNAME}" - keytool -genkeypair -alias cas -keyalg RSA -keypass changeit -storepass changeit -keystore /etc/cas/thekeystore -dname ${DNAME} -ext SAN=${CERT_SUBJ_ALT_NAMES} - 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 - ;; -"clean") - shift - clean "$@" - ;; -"package") - shift - package "$@" - ;; -"bootrun") - shift - bootrun "$@" - ;; -"debug") - debug "$@" - ;; -"run") - run "$@" - ;; -"runalone") - runalone "$@" - ;; -"listviews") - listviews "$@" - ;; -"gencert") - gencert "$@" - ;; -"getview") - getview "$@" - ;; -"cli") - shift - cli "$@" - ;; -*) - help - ;; -esac diff --git a/cas/cas-server/docker-build.sh b/cas/cas-server/docker-build.sh new file mode 100755 index 0000000000..8f2c2776bf --- /dev/null +++ b/cas/cas-server/docker-build.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) + +echo "Building CAS docker image tagged as [$image_tag]" +# read -p "Press [Enter] to continue..." any_key; + +docker build --tag="org.apereo.cas/cas:$image_tag" . \ + && echo "Built CAS image successfully tagged as org.apereo.cas/cas:$image_tag" \ + && docker images "org.apereo.cas/cas:$image_tag" \ No newline at end of file diff --git a/cas/cas-server/docker-compose.yml b/cas/cas-server/docker-compose.yml new file mode 100644 index 0000000000..8f2e6ca7c9 --- /dev/null +++ b/cas/cas-server/docker-compose.yml @@ -0,0 +1,7 @@ +version: '3' +services: + cas: + build: . + ports: + - "8443:8443" + - "8080:8080" \ No newline at end of file diff --git a/cas/cas-server/docker-push.sh b/cas/cas-server/docker-push.sh new file mode 100755 index 0000000000..e04b107212 --- /dev/null +++ b/cas/cas-server/docker-push.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +read -p "Docker username: " docker_user +read -s -p "Docker password: " docker_psw + +echo "$docker_psw" | docker login --username "$docker_user" --password-stdin + +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) + +echo "Pushing CAS docker image tagged as $image_tag to org.apereo.cas/cas..." +docker push org.apereo.cas/cas:"$image_tag" \ + && echo "Pushed org.apereo.cas/cas:$image_tag successfully."; \ No newline at end of file diff --git a/cas/cas-server/docker-run.sh b/cas/cas-server/docker-run.sh new file mode 100755 index 0000000000..f8627859f2 --- /dev/null +++ b/cas/cas-server/docker-run.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +docker stop cas > /dev/null 2>&1 +docker rm cas > /dev/null 2>&1 +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) +docker run -d -p 8080:8080 -p 8443:8443 --name="cas" org.apereo.cas/cas:"${image_tag}" +docker logs -f cas \ No newline at end of file diff --git a/cas/cas-server/etc/cas/config/application.yml b/cas/cas-server/etc/cas/config/application.yml deleted file mode 100644 index be1f7c3edd..0000000000 --- a/cas/cas-server/etc/cas/config/application.yml +++ /dev/null @@ -1,2 +0,0 @@ -info: - description: CAS Configuration \ No newline at end of file diff --git a/cas/cas-server/etc/cas/config/cas.properties b/cas/cas-server/etc/cas/config/cas.properties index 47a1477308..a3be0e1388 100644 --- a/cas/cas-server/etc/cas/config/cas.properties +++ b/cas/cas-server/etc/cas/config/cas.properties @@ -1,7 +1,6 @@ -cas.server.name: https://cas.example.org:8443 -cas.server.prefix: https://cas.example.org:8443/cas - -cas.adminPagesSecurity.ip=127\.0\.0\.1 +cas.server.name=https://cas.example.org:8443 +cas.server.prefix=${cas.server.name}/cas logging.config: file:/etc/cas/config/log4j2.xml -# cas.serviceRegistry.config.location: classpath:/services + +# cas.authn.accept.users= diff --git a/cas/cas-server/etc/cas/config/log4j2.xml b/cas/cas-server/etc/cas/config/log4j2.xml index e688cc0350..685dfab245 100644 --- a/cas/cas-server/etc/cas/config/log4j2.xml +++ b/cas/cas-server/etc/cas/config/log4j2.xml @@ -2,20 +2,26 @@ - - . - - warn + /var/log + + info + warn + info + warn + debug + warn + warn + warn + warn + warn + warn - + - + @@ -23,8 +29,8 @@ - + @@ -33,16 +39,6 @@ - - - - - - - - - @@ -52,52 +48,58 @@ - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/etc/cas/saml/.gitkeep b/cas/cas-server/etc/cas/saml/.gitkeep new file mode 100644 index 0000000000..882c99944d --- /dev/null +++ b/cas/cas-server/etc/cas/saml/.gitkeep @@ -0,0 +1 @@ +This directory is references in the Dockerfile so it needs to be here. \ No newline at end of file diff --git a/libraries/src/test/resources/ftp/baz.txt b/cas/cas-server/etc/cas/services/.donotdel similarity index 100% rename from libraries/src/test/resources/ftp/baz.txt rename to cas/cas-server/etc/cas/services/.donotdel diff --git a/cas/cas-server/etc/cas/thekeystore b/cas/cas-server/etc/cas/thekeystore new file mode 100644 index 0000000000..78f49baf74 Binary files /dev/null and b/cas/cas-server/etc/cas/thekeystore differ diff --git a/cas/cas-server/gradle.properties b/cas/cas-server/gradle.properties new file mode 100644 index 0000000000..28daacc245 --- /dev/null +++ b/cas/cas-server/gradle.properties @@ -0,0 +1,28 @@ +# Versions +cas.version=6.1.5 +springBootVersion=2.2.0.RELEASE + +# Use -jetty, -undertow to other containers +# Or blank if you want to deploy to an external container +appServer=-tomcat +executable=false + +gradleVersion=5.6.3 +tomcatVersion=9.0.30 + +group=org.apereo.cas +sourceCompatibility=11 +targetCompatibility=11 + +jibVersion=1.7.0 + +# Location of the downloaded CAS shell JAR +shellDir=build/libs +ivyVersion=2.4.0 +gradleDownloadTaskVersion=3.4.3 +gradleMavenPluginVersion=3.8.4 + +# use without "-slim" in tag name if you want tools like jstack, adds about 100MB to image size +# (https://hub.docker.com/r/adoptopenjdk/openjdk11/tags/) +baseDockerImage=adoptopenjdk/openjdk11:alpine-jre +allowInsecureRegistries=false diff --git a/cas/cas-server/gradle/dockerjib.gradle b/cas/cas-server/gradle/dockerjib.gradle new file mode 100644 index 0000000000..dcd70e3875 --- /dev/null +++ b/cas/cas-server/gradle/dockerjib.gradle @@ -0,0 +1,52 @@ +apply plugin: "com.google.cloud.tools.jib" + +jib { + from { + image = project.baseDockerImage + } + to { + image = "${project.group}/${project.name}" + /** + ecr-login: Amazon Elastic Container Registry (ECR) + gcr: Google Container Registry (GCR) + osxkeychain: Docker Hub + */ + credHelper = "osxkeychain" + /** + auth { + username = "*******" + password = "*******" + } + tags = [casServerVersion] + */ + } + container { + useCurrentTimestamp = true + entrypoint = ['docker/entrypoint.sh'] + ports = ['80', '443', '8080', '8443'] + labels = [version:casServerVersion, name:project.name, group:project.group] + } + extraDirectories { + paths = 'src/main/jib' + permissions = [ + '/docker/entrypoint.sh': '755' + ] + } + allowInsecureRegistries = project.allowInsecureRegistries +} + +task copyWebAppIntoJib(type: Copy, group: "Docker", description: "Copy the web application into Docker image") { + dependsOn build + from "build/libs/${casWebApplicationBinaryName}" + into "src/main/jib/docker/cas/war" +} + +task copyConfigIntoJib(type: Copy, group: "Docker", description: "Copy the CAS configuration into Docker image") { + dependsOn build + from "etc/cas" + into "src/main/jib/docker/cas" +} + +task deleteWebAppFromJib(type: Delete, group: "Docker", description: "Explodes the CAS web application archive") { + delete "src/main/jib/docker/cas" +} \ No newline at end of file diff --git a/cas/cas-server/gradle/springboot.gradle b/cas/cas-server/gradle/springboot.gradle new file mode 100644 index 0000000000..b6a46b8940 --- /dev/null +++ b/cas/cas-server/gradle/springboot.gradle @@ -0,0 +1,24 @@ +apply plugin: "org.springframework.boot" + +bootRun.enabled = false +bootRun.onlyIf { return false } +tasks.remove(tasks['bootRun']) + +springBoot { + mainClassName = "org.apereo.cas.web.CasWebApplication" +} + +bootWar { + doFirst { + def executable = project.hasProperty("executable") && Boolean.valueOf(project.getProperty("executable")) + if (executable) { + logger.info "Including launch script for executable WAR artifact" + launchScript() + } else { + logger.info "WAR artifact is not marked as an executable" + } + archiveName "${casWebApplicationBinaryName}" + baseName "cas" + excludeDevtools = true + } +} \ No newline at end of file diff --git a/cas/cas-server/gradle/tasks.gradle b/cas/cas-server/gradle/tasks.gradle new file mode 100644 index 0000000000..2babeb2d1f --- /dev/null +++ b/cas/cas-server/gradle/tasks.gradle @@ -0,0 +1,258 @@ +import org.apache.ivy.util.url.* +import org.apache.tools.ant.taskdefs.condition.Os +import org.gradle.api.tasks.Copy + +import java.nio.file.* +import org.gradle.internal.logging.text.StyledTextOutputFactory; +import static org.gradle.internal.logging.text.StyledTextOutput.Style; + +buildscript { + repositories { + mavenLocal() + mavenCentral() + jcenter() + } + dependencies { + classpath "org.apache.ivy:ivy:${project.ivyVersion}" + } +} + +apply plugin: "de.undercouch.download" + +def tomcatDirectory = "${buildDir}/apache-tomcat-${tomcatVersion}" +project.ext."tomcatDirectory" = tomcatDirectory + +def explodedDir="${buildDir}/cas" +def explodedResourcesDir="${buildDir}/cas-resources" +def resourceJarName = "cas-server-webapp-resources" + +task copyCasConfiguration(type: Copy, group: "build", description: "Copy the CAS configuration from this project to /etc/cas/config") { + from "etc/cas/config" + into new File('/etc/cas/config').absolutePath + doFirst { + new File('/etc/cas/config').mkdirs() + } +} + +task explodeWarOnly(type: Copy, group: "build", description: "Explodes the CAS web application archive") { + dependsOn 'build' + from zipTree("build/libs/${casWebApplicationBinaryName}") + into explodedDir +} + +task explodeWar(type: Copy, group: "build", description: "Explodes the CAS archive and resources jar from the CAS web application archive") { + dependsOn explodeWarOnly + from zipTree("${explodedDir}/WEB-INF/lib/${resourceJarName}-${casServerVersion}.jar") + into explodedResourcesDir +} + +task run(group: "build", description: "Run the CAS web application in embedded container mode") { + dependsOn 'build' + doLast { + def casRunArgs = new ArrayList<>(Arrays.asList("-server -noverify -Xmx2048M -XX:+TieredCompilation -XX:TieredStopAtLevel=1".split(" "))) + if (project.hasProperty('args')) { + casRunArgs.addAll(project.args.split('\\s+')) + } + javaexec { + main = "-jar" + jvmArgs = casRunArgs + args = ["build/libs/${casWebApplicationBinaryName}"] + logger.info "Started ${commandLine}" + } + } +} + +task setExecutable(group: "build", description: "Configure the project to run in executable mode") { + doFirst { + project.setProperty("executable", "true") + logger.info "Configuring the project as executable" + } +} + +task executable(type:Exec, group: "build", description: "Run the CAS web application in standalone executable mode") { + dependsOn setExecutable, 'build' + doFirst { + workingDir "." + if (!Os.isFamily(Os.FAMILY_WINDOWS)) { + commandLine "chmod", "+x", bootWar.archivePath + } + logger.info "Running ${bootWar.archivePath}" + commandLine bootWar.archivePath + } +} + +task debug(group: "build", description: "Debug the CAS web application in embedded mode on port 5005") { + dependsOn 'build' + doLast { + logger.info "Debugging process is started in a suspended state, listening on port 5005." + def casArgs = Arrays.asList("-Xmx2048M".split(" ")) + javaexec { + main = "-jar" + jvmArgs = casArgs + debug = true + args = ["build/libs/${casWebApplicationBinaryName}"] + logger.info "Started ${commandLine}" + } + } +} + +task downloadShell(group: "shell", description: "Download CAS shell jar from snapshot or release maven repo") { + doFirst { + mkdir "${project.shellDir}" + } + doLast { + def downloadFile + if (isRunningCasServerSnapshot(casServerVersion)) { + def snapshotDir = "https://oss.sonatype.org/content/repositories/snapshots/org/apereo/cas/cas-server-support-shell/${casServerVersion}/" + def files = new ApacheURLLister().listFiles(new URL(snapshotDir)) + files = files.sort{it.path} + files.each { + if (it.path.endsWith(".jar")) { + downloadFile = it + } + } + } else { + downloadFile = "https://repo1.maven.org/maven2/org/apereo/cas/cas-server-support-shell/${casServerVersion}/cas-server-support-shell-${casServerVersion}.jar" + } + logger.info "Downloading file: ${downloadFile}" + download { + src downloadFile + dest new File("${project.shellDir}", "cas-server-support-shell-${casServerVersion}.jar") + overwrite false + } + } +} + +task runShell(group: "shell", description: "Run the CAS shell") { + dependsOn downloadShell + doLast { + println "Run the following command to launch the shell:\n\tjava -jar ${project.shellDir}/cas-server-support-shell-${casServerVersion}.jar" + } +} + +task debugShell(group: "shell", description: "Run the CAS shell with debug options, wait for debugger on port 5005") { + dependsOn downloadShell + doLast { + println """ + Run the following command to launch the shell:\n\t + java -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=y -jar ${project.shellDir}/cas-server-support-shell-${casServerVersion}.jar + """ + } +} + +task showConfiguration(group: "build", description: "Show configurations for each dependency, etc") { + doLast() { + def cfg = project.hasProperty("configuration") ? project.property("configuration") : "compile" + configurations.getByName(cfg).each { println it } + } +} + +task allDependenciesInsight(group: "build", type: DependencyInsightReportTask, description: "Produce insight information for all dependencies") {} + +task allDependencies(group: "build", type: DependencyReportTask, description: "Display a graph of all project dependencies") {} + +task casVersion (group: "build", description: "Display the current CAS version") { + doFirst { + def verbose = project.hasProperty("verbose") && Boolean.valueOf(project.getProperty("verbose")) + if (verbose) { + def out = services.get(StyledTextOutputFactory).create("CAS") + println "******************************************************************" + out.withStyle(Style.Info).println "Apereo CAS $casServerVersion" + out.withStyle(Style.Description).println "Enterprise Single SignOn for all earthlings and beyond" + out.withStyle(Style.SuccessHeader).println "- GitHub: " + out.withStyle(Style.Success).println "https://github.com/apereo/cas" + out.withStyle(Style.SuccessHeader).println "- Docs: " + out.withStyle(Style.Success).println "https://apereo.github.io/cas" + out.withStyle(Style.SuccessHeader).println "- Blog: " + out.withStyle(Style.Success).println "https://apereo.github.io" + println "******************************************************************" + } else { + println casServerVersion + } + } +} + +task createKeystore(group: "build", description: "Create CAS keystore") { + doFirst { + mkdir "/etc/cas" + + def keystorePath = "/etc/cas/thekeystore" + + def dn = "CN=cas.example.org,OU=Example,OU=Org,C=US" + if (project.hasProperty("certificateDn")) { + dn = project.getProperty("certificateDn") + } + def subjectAltName = "dns:example.org,dns:localhost,ip:127.0.0.1" + if (project.hasProperty("certificateSubAltName")) { + subjectAltName = project.getProperty("certificateSubAltName") + } + // this will fail if thekeystore exists and has cert with cas alias already (so delete if you want to recreate) + logger.info "Generating keystore for CAS with DN ${dn}" + exec { + workingDir "." + commandLine "keytool", "-genkeypair", "-alias", "cas", + "-keyalg", "RSA", + "-keypass", "changeit", "-storepass", "changeit", + "-keystore", keystorePath, + "-dname", dn, "-ext", "SAN=${subjectAltName}" + } + logger.info "Exporting cert from keystore..." + exec { + workingDir "." + commandLine "keytool", "-exportcert", "-alias", "cas", + "-storepass", "changeit", "-keystore", keystorePath, + "-file", "/etc/cas/cas.cer" + } + logger.info "Import /etc/cas/cas.cer into your Java truststore (JAVA_HOME/lib/security/cacerts)" + } +} + +task listTemplateViews (group: "build", description: "List all CAS views") { + dependsOn explodeWar + + doFirst { + fileTree(explodedResourcesDir).matching { + include "**/*.html" + } + .collect { it.name } + .toSorted() + .each { println it } + } +} + +task getResource(group: "build", description: "Fetch a CAS resource and move it into the overlay") { + dependsOn explodeWar + + doFirst { + def resourceName = project.getProperty("resourceName") + + def results = fileTree(explodedResourcesDir).matching { + include "**/${resourceName}.*" + } + if (results.isEmpty()) { + println "No resources could be found matching ${resourceName}" + return + } + if (results.size() > 1) { + println "Multiple resources found matching ${resourceName}: ${results}" + return + } + + def fromFile = explodedResourcesDir + def resourcesDir = "src/main/resources" + mkdir resourcesDir + + def resourceFile = results[0].canonicalPath + def toResourceFile = resourceFile.replace(fromFile, resourcesDir) + + def parent = file(toResourceFile).getParent() + mkdir parent + + Files.copy(Paths.get(resourceFile), Paths.get(toResourceFile), StandardCopyOption.REPLACE_EXISTING) + println "Copied file ${resourceFile} to ${toResourceFile}" + } +} + +def isRunningCasServerSnapshot(casServerVersion) { + return "${casServerVersion}".contains("-SNAPSHOT") +} \ No newline at end of file diff --git a/cas/cas-server/gradle/wrapper/gradle-wrapper.properties b/cas/cas-server/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..f04d6a20ae --- /dev/null +++ b/cas/cas-server/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.3-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/cas/cas-server/gradlew b/cas/cas-server/gradlew new file mode 100755 index 0000000000..83f2acfdc3 --- /dev/null +++ b/cas/cas-server/gradlew @@ -0,0 +1,188 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# 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 +# +# https://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. +# + +############################################################################## +## +## 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='"-Xmx64m" "-Xms64m"' + +# 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 or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; 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/cas/cas-server/gradlew.bat b/cas/cas-server/gradlew.bat new file mode 100644 index 0000000000..24467a141f --- /dev/null +++ b/cas/cas-server/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@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="-Xmx64m" "-Xms64m" + +@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/cas/cas-server/maven/maven-wrapper.jar b/cas/cas-server/maven/maven-wrapper.jar deleted file mode 100644 index 18ba302c65..0000000000 Binary files a/cas/cas-server/maven/maven-wrapper.jar and /dev/null differ diff --git a/cas/cas-server/maven/maven-wrapper.properties b/cas/cas-server/maven/maven-wrapper.properties deleted file mode 100644 index 97a946225a..0000000000 --- a/cas/cas-server/maven/maven-wrapper.properties +++ /dev/null @@ -1,3 +0,0 @@ -#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/mvnw b/cas/cas-server/mvnw deleted file mode 100644 index 2275ac7647..0000000000 --- a/cas/cas-server/mvnw +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - wdir=$(cd "$wdir/.."; pwd) - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER="org.apache.maven.wrapper.MavenWrapperMain" - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - -classpath \ -"$MAVEN_PROJECTBASEDIR/maven/maven-wrapper.jar" \ - ${WRAPPER_LAUNCHER} "$@" diff --git a/cas/cas-server/mvnw.bat b/cas/cas-server/mvnw.bat deleted file mode 100644 index d391151aa7..0000000000 --- a/cas/cas-server/mvnw.bat +++ /dev/null @@ -1,174 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto chkMHome - -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 - -:chkMHome -if not "%M2_HOME%"=="" goto valMHome - -SET "M2_HOME=%~dp0.." -if not "%M2_HOME%"=="" goto valMHome - -echo. -echo Error: M2_HOME not found in your environment. >&2 -echo Please set the M2_HOME variable in your environment to match the >&2 -echo location of the Maven installation. >&2 -echo. -goto error - -:valMHome - -:stripMHome -if not "_%M2_HOME:~-1%"=="_\" goto checkMCmd -set "M2_HOME=%M2_HOME:~0,-1%" -goto stripMHome - -:checkMCmd -if exist "%M2_HOME%\bin\mvn.cmd" goto init - -echo. -echo Error: M2_HOME is set to an invalid directory. >&2 -echo M2_HOME = "%M2_HOME%" >&2 -echo Please set the M2_HOME variable in your environment to match the >&2 -echo location of the Maven installation >&2 -echo. -goto error -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\maven\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% %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% - -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml deleted file mode 100644 index bfd8f685ac..0000000000 --- a/cas/cas-server/pom.xml +++ /dev/null @@ -1,206 +0,0 @@ - - - 4.0.0 - cas-server - 1.0 - cas-server - war - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.apereo.cas - cas-server-support-json-service-registry - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc-drivers - ${cas.version} - - - - - - - com.rimerosolutions.maven.plugins - wrapper-maven-plugin - ${wrapper-maven-plugin.version} - - true - MD5 - - - - org.springframework.boot - spring-boot-maven-plugin - - ${mainClassName} - true - ${isExecutable} - WAR - - - - - repackage - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - cas - false - false - - false - ${manifestFileToUse} - - - - org.apereo.cas - cas-server-webapp${app.server} - - - - - - cas - - - - - - 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 - - pgp - - - - com.github.s4u.plugins - pgpverify-maven-plugin - ${pgpverify-maven-plugin.version} - - - - check - - - - - hkp://pool.sks-keyservers.net - ${settings.localRepository}/pgpkeys-cache - test - true - false - - - - - - - - - 5.3.3 - - -tomcat - - org.springframework.boot.loader.WarLauncher - false - ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF - - 0.0.4 - 2.6 - - 0.3.0 - 1.1.0 - - - diff --git a/cas/cas-server/settings.gradle b/cas/cas-server/settings.gradle new file mode 100644 index 0000000000..3ad50900ea --- /dev/null +++ b/cas/cas-server/settings.gradle @@ -0,0 +1 @@ +rootProject.name='cas' \ No newline at end of file diff --git a/cas/cas-server/src/main/jib/docker/entrypoint.sh b/cas/cas-server/src/main/jib/docker/entrypoint.sh new file mode 100755 index 0000000000..a3a0895b04 --- /dev/null +++ b/cas/cas-server/src/main/jib/docker/entrypoint.sh @@ -0,0 +1,22 @@ +#!/bin/sh + +#echo -e "\nChecking java..." +#java -version + +#echo -e "\nCreating CAS configuration directories..." +mkdir -p /etc/cas/config +mkdir -p /etc/cas/services + +#echo "Listing provided CAS docker artifacts..." +#ls -R docker/cas + +#echo -e "\nMoving CAS configuration artifacts..." +mv docker/cas/thekeystore /etc/cas 2>/dev/null +mv docker/cas/config/*.* /etc/cas/config 2>/dev/null +mv docker/cas/services/*.* /etc/cas/services 2>/dev/null + +#echo -e "\nListing CAS configuration under /etc/cas..." +#ls -R /etc/cas + +echo -e "\nRunning CAS..." +exec java -Xms512m -Xmx2048M -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -jar docker/cas/war/cas.war diff --git a/cas/cas-server/src/main/resources/application.properties b/cas/cas-server/src/main/resources/application.properties index 7735fcabdc..185532f943 100644 --- a/cas/cas-server/src/main/resources/application.properties +++ b/cas/cas-server/src/main/resources/application.properties @@ -1,134 +1,4 @@ -## -# CAS Server Context Configuration -# -server.context-path=/cas -server.port=6443 - +server.port=8443 +spring.main.allow-bean-definition-overriding=true server.ssl.key-store=classpath:/etc/cas/thekeystore -server.ssl.key-store-password=changeit -server.ssl.key-password=changeit -# server.ssl.ciphers= -# server.ssl.client-auth= -# server.ssl.enabled= -# server.ssl.key-alias= -# server.ssl.key-store-provider= -# server.ssl.key-store-type= -# server.ssl.protocol= -# server.ssl.trust-store= -# server.ssl.trust-store-password= -# server.ssl.trust-store-provider= -# server.ssl.trust-store-type= - -server.max-http-header-size=2097152 -server.use-forward-headers=true -server.connection-timeout=20000 -server.error.include-stacktrace=NEVER - -server.tomcat.max-http-post-size=2097152 -server.tomcat.basedir=build/tomcat -server.tomcat.accesslog.enabled=true -server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms) -server.tomcat.accesslog.suffix=.log -server.tomcat.max-threads=10 -server.tomcat.port-header=X-Forwarded-Port -server.tomcat.protocol-header=X-Forwarded-Proto -server.tomcat.protocol-header-https-value=https -server.tomcat.remote-ip-header=X-FORWARDED-FOR -server.tomcat.uri-encoding=UTF-8 - -spring.http.encoding.charset=UTF-8 -spring.http.encoding.enabled=true -spring.http.encoding.force=true - -## -#CAS CONFIG LOCATION -# -standalone.config=classpath:/etc/cas/config - - -## -# CAS Cloud Bus Configuration -# -spring.cloud.bus.enabled=false -# spring.cloud.bus.refresh.enabled=true -# spring.cloud.bus.env.enabled=true -# spring.cloud.bus.destination=CasCloudBus -# spring.cloud.bus.ack.enabled=true - -endpoints.enabled=false -endpoints.sensitive=true - -endpoints.restart.enabled=false -endpoints.shutdown.enabled=false - -management.security.enabled=true -management.security.roles=ACTUATOR,ADMIN -management.security.sessions=if_required -management.context-path=/status -management.add-application-context-header=false - -security.basic.authorize-mode=role -security.basic.enabled=false -security.basic.path=/cas/status/** - -## -# CAS Web Application Session Configuration -# -server.session.timeout=300 -server.session.cookie.http-only=true -server.session.tracking-modes=COOKIE - -## -# CAS Thymeleaf View Configuration -# -spring.thymeleaf.encoding=UTF-8 -spring.thymeleaf.cache=true -spring.thymeleaf.mode=HTML -## -# CAS Log4j Configuration -# -# logging.config=file:/etc/cas/log4j2.xml - -server.context-parameters.isLog4jAutoInitializationDisabled=true - -## -# CAS AspectJ Configuration -# -spring.aop.auto=true -spring.aop.proxy-target-class=true - -## -# CAS Authentication Credentials -# -#cas.authn.accept.users=casuser::Mellon -cas.authn.accept.users= -cas.authn.accept.name= - -#CAS Database Authentication Property -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=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 -cas.authn.jdbc.query[0].fieldPassword=password -cas.authn.jdbc.query[0].passwordEncoder.type=NONE - - -## -# CAS Delegated Authentication -# -cas.authn.pac4j.bitbucket.clientName=Bitbucket -cas.authn.pac4j.dropbox.clientName=Dropbox -cas.authn.pac4j.facebook.clientName=Facebook -cas.authn.pac4j.foursquare.clientName=Foursquare -cas.authn.pac4j.github.clientName=Github -cas.authn.pac4j.google.clientName=Google -cas.authn.pac4j.linkedIn.clientName=LinkedIn -cas.authn.pac4j.paypal.clientName=PayPal -cas.authn.pac4j.twitter.clientName=Twitter -cas.authn.pac4j.yahoo.clientName=Yahoo -cas.authn.pac4j.windowsLive.clientName=Windows Live -cas.authn.pac4j.wordpress.clientName=WordPress +server.ssl.key-store-password=changeit \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/cas.properties b/cas/cas-server/src/main/resources/cas.properties deleted file mode 100644 index e39d68f312..0000000000 --- a/cas/cas-server/src/main/resources/cas.properties +++ /dev/null @@ -1,9 +0,0 @@ -cas.server.name: https://localhost:6443 -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 \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql index 79a4a48a82..104b515813 100644 --- a/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql +++ b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql @@ -4,13 +4,13 @@ USE `test`; -- Dumping structure for table test.users CREATE TABLE IF NOT EXISTS `users` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `email` varchar(50) DEFAULT NULL, - `password` text DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; + `id` int(11) NOT NULL AUTO_INCREMENT, + `email` varchar(50) DEFAULT NULL, + `password` text DEFAULT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40000 ALTER TABLE `users` DISABLE KEYS */; INSERT INTO `users` (`id`, `email`, `password`) VALUES - (1, 'test@test.com', 'Mellon'); + (1, 'test@test.com', 'Mellon'); /*!40000 ALTER TABLE `users` ENABLE KEYS */; \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/application.yml b/cas/cas-server/src/main/resources/etc/cas/config/application.yml deleted file mode 100644 index be1f7c3edd..0000000000 --- a/cas/cas-server/src/main/resources/etc/cas/config/application.yml +++ /dev/null @@ -1,2 +0,0 @@ -info: - description: CAS Configuration \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/cas.properties b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties index 47a1477308..dda939bc1d 100644 --- a/cas/cas-server/src/main/resources/etc/cas/config/cas.properties +++ b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties @@ -1,7 +1,15 @@ -cas.server.name: https://cas.example.org:8443 -cas.server.prefix: https://cas.example.org:8443/cas +cas.serviceRegistry.initFromJson=true +cas.serviceRegistry.json.location=classpath:/etc/cas/services -cas.adminPagesSecurity.ip=127\.0\.0\.1 -logging.config: file:/etc/cas/config/log4j2.xml -# cas.serviceRegistry.config.location: classpath:/services +cas.authn.accept.users= + +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=smattroot +cas.authn.jdbc.query[0].ddlAuto=none +cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver +cas.authn.jdbc.query[0].fieldPassword=password +cas.authn.jdbc.query[0].passwordEncoder.type=NONE \ 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 deleted file mode 100644 index e688cc0350..0000000000 --- a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - . - - warn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json b/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json new file mode 100644 index 0000000000..5d468945ff --- /dev/null +++ b/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json @@ -0,0 +1,8 @@ +{ + "@class" : "org.apereo.cas.services.RegexRegisteredService", + "serviceId" : "http://cas-client:8900/login/cas", + "name" : "casSecuredApp", + "id" : 8900, + "logoutType" : "BACK_CHANNEL", + "logoutUrl" : "http://cas-client:8900/exit/cas" +} \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore b/cas/cas-server/src/main/resources/etc/cas/thekeystore index 77bf895249..a361bf03f9 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 deleted file mode 100644 index 12ef688a08..0000000000 Binary files a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt and /dev/null differ diff --git a/cas/cas-server/src/main/resources/log4j2.xml b/cas/cas-server/src/main/resources/log4j2.xml deleted file mode 100644 index e688cc0350..0000000000 --- a/cas/cas-server/src/main/resources/log4j2.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - . - - warn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json b/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json deleted file mode 100644 index 336007e484..0000000000 --- a/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "@class" : "org.apereo.cas.services.RegexRegisteredService", - "serviceId" : "^http://localhost:9000/login/cas", - "name" : "CAS Spring Secured App", - "description": "This is a Spring App that usses the CAS Server for it's authentication", - "id" : 19991, - "evaluationOrder" : 1 -} \ No newline at end of file diff --git a/cas/pom.xml b/cas/pom.xml deleted file mode 100644 index f458b23797..0000000000 --- a/cas/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - cas - cas - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. - - - - cas-secured-app - cas-server - - - diff --git a/cdi/pom.xml b/cdi/pom.xml index 87ad9c111a..fec12a9b16 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 cdi 1.0-SNAPSHOT @@ -26,8 +28,8 @@ org.hamcrest - hamcrest-core - ${org.hamcrest.version} + hamcrest + ${hamcrest.version} test diff --git a/checker-plugin/pom.xml b/checker-plugin/pom.xml index 0140d7951a..9820d8b602 100644 --- a/checker-plugin/pom.xml +++ b/checker-plugin/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 checker-plugin 1.0-SNAPSHOT @@ -66,13 +68,10 @@ -Xbootclasspath/p:${annotatedJdk} - + - + -Awarns @@ -85,9 +84,7 @@ ${org.checkerframework:jdk8:jar} - + 2.3.1 2.3.1 2.3.1 diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml index 1429ca8b24..8706bd3b53 100644 --- a/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.example cf-uaa-oauth2-client diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml index 6297c6f673..6bac4fe59a 100644 --- a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.cfuaa cf-uaa-oauth2-resource-server diff --git a/cloud-foundry-uaa/pom.xml b/cloud-foundry-uaa/pom.xml new file mode 100644 index 0000000000..a8a46b921d --- /dev/null +++ b/cloud-foundry-uaa/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + cloud-foundry-uaa + 0.0.1-SNAPSHOT + cloud-foundry-uaa + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + cf-uaa-oauth2-client + cf-uaa-oauth2-resource-server + + + diff --git a/code-generation/pom.xml b/code-generation/pom.xml index 7cc076c58f..c5feef2426 100644 --- a/code-generation/pom.xml +++ b/code-generation/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 code-generation 1.0 diff --git a/core-groovy-2/determine-datatype/pom.xml b/core-groovy-2/determine-datatype/pom.xml new file mode 100644 index 0000000000..0bcef4e5d8 --- /dev/null +++ b/core-groovy-2/determine-datatype/pom.xml @@ -0,0 +1,40 @@ + + 4.0.0 + com.baeldung.groovy + determine-datatype + 0.0.1-SNAPSHOT + + src + + + maven-compiler-plugin + 3.8.0 + + 1.8 + 1.8 + + + + org.codehaus.gmaven + groovy-maven-plugin + + + org.codehaus.groovy + groovy-all + 2.0.6 + + + + + + + + + org.junit + junit5-engine + 5.0.0-ALPHA + + + \ No newline at end of file diff --git a/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/Person.groovy b/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/Person.groovy new file mode 100644 index 0000000000..1a89dce435 --- /dev/null +++ b/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/Person.groovy @@ -0,0 +1,14 @@ +package com.baeldung.groovy.determine.datatype + +class Person { + + private int ageAsInt + private Double ageAsDouble + private String ageAsString + + Person() {} + Person(int ageAsInt) { this.ageAsInt = ageAsInt} + Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble} + Person(String ageAsString) { this.ageAsString = ageAsString} +} +class Student extends Person {} diff --git a/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/PersonTest.groovy b/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/PersonTest.groovy new file mode 100644 index 0000000000..56095a3f1b --- /dev/null +++ b/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/PersonTest.groovy @@ -0,0 +1,55 @@ +package com.baeldung.groovy.determine.datatype; + +import org.junit.Assert +import org.junit.Test; + +public class PersonTest { + + @Test + public void givenWhenParameterTypeIsInteger_thenReturnTrue() { + Person personObj = new Person(10) + Assert.assertTrue(personObj.ageAsInt instanceof Integer); + } + + @Test + public void givenWhenParameterTypeIsDouble_thenReturnTrue() { + Person personObj = new Person(10.0) + Assert.assertTrue((personObj.ageAsDouble).getClass() == Double) + } + + @Test + public void givenWhenParameterTypeIsString_thenReturnTrue() { + Person personObj = new Person("10 years") + Assert.assertTrue(personObj.ageAsString.class == String) + } + + @Test + public void givenClassName_WhenParameterIsInteger_thenReturnTrue() { + Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class) + } + + @Test + public void givenWhenObjectIsInstanceOfType_thenReturnTrue() { + Person personObj = new Person() + Assert.assertTrue(personObj instanceof Person) + } + + @Test + public void givenWhenInstanceIsOfSubtype_thenReturnTrue() { + Student studentObj = new Student() + Assert.assertTrue(studentObj in Person) + } + + @Test + public void givenGroovyList_WhenFindClassName_thenReturnTrue() { + def ageList = ['ageAsString','ageAsDouble', 10] + Assert.assertTrue(ageList.class == ArrayList) + Assert.assertTrue(ageList.getClass() == ArrayList) + } + + @Test + public void givenGrooyMap_WhenFindClassName_thenReturnTrue() { + def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0] + Assert.assertFalse(ageMap.class == LinkedHashMap) + } +} \ No newline at end of file diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index e0987de4b3..a01560781b 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-groovy-2 1.0-SNAPSHOT @@ -62,12 +64,12 @@ org.codehaus.groovy groovy-eclipse-compiler - 3.3.0-01 + ${groovy.compiler.version} true maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} groovy-eclipse-compiler ${java.version} @@ -77,7 +79,7 @@ org.codehaus.groovy groovy-eclipse-compiler - 3.3.0-01 + ${groovy.compiler.version} org.codehaus.groovy @@ -113,7 +115,7 @@ maven-surefire-plugin - 2.20.1 + ${surefire.plugin.version} false @@ -126,7 +128,7 @@ org.apache.maven.plugins maven-assembly-plugin - 3.1.0 + ${assembly.plugin.version} @@ -183,6 +185,10 @@ 1.1.3 1.2.3 2.5.7 + 3.1.0 + 2.20.1 + 3.8.0 + 3.3.0-01 diff --git a/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy b/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy index 65591cae8d..0612ecb955 100644 --- a/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy +++ b/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy @@ -2,10 +2,13 @@ package com.baeldung.metaprogramming.extension import com.baeldung.metaprogramming.Employee +import java.time.LocalDate +import java.time.Year + class BasicExtensions { static int getYearOfBirth(Employee self) { - return (new Date().getYear() + 1900) - self.age; + return Year.now().value - self.age } static String capitalize(String self) { diff --git a/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy index 8066b10f9b..4a8631eb95 100644 --- a/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy +++ b/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy @@ -1,6 +1,9 @@ package com.baeldung.metaprogramming -import groovy.time.TimeCategory + +import java.time.LocalDate +import java.time.Period +import java.time.Year class MetaprogrammingUnitTest extends GroovyTestCase { @@ -51,14 +54,16 @@ class MetaprogrammingUnitTest extends GroovyTestCase { void testJavaMetaClass() { String.metaClass.capitalize = { String str -> - str.substring(0, 1).toUpperCase() + str.substring(1); + str.substring(0, 1).toUpperCase() + str.substring(1) } assert "norman".capitalize() == "Norman" } void testEmployeeExtension() { - Employee emp = new Employee(age: 28) - assert emp.getYearOfBirth() == 1991 + def age = 28 + def expectedYearOfBirth = Year.now() - age + Employee emp = new Employee(age: age) + assert emp.getYearOfBirth() == expectedYearOfBirth.value } void testJavaClassesExtensions() { @@ -115,4 +120,4 @@ class MetaprogrammingUnitTest extends GroovyTestCase { Employee employee = new Employee(1, "Norman", "Lewis", 28) employee.logEmp() } -} \ No newline at end of file +} diff --git a/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy index 302959d0d9..b8417b8ac1 100644 --- a/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy +++ b/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy @@ -9,7 +9,7 @@ import wslite.soap.SOAPMessageBuilder import wslite.http.auth.HTTPBasicAuthorization import org.junit.Test -class WebserviceUnitTest extends GroovyTestCase { +class WebserviceManualTest extends GroovyTestCase { JsonSlurper jsonSlurper = new JsonSlurper() @@ -149,4 +149,4 @@ class WebserviceUnitTest extends GroovyTestCase { assert e?.response?.statusCode != 200 } } -} \ No newline at end of file +} diff --git a/core-groovy-collections/pom.xml b/core-groovy-collections/pom.xml index 423be5e977..125dfca4c1 100644 --- a/core-groovy-collections/pom.xml +++ b/core-groovy-collections/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-groovy-collections 1.0-SNAPSHOT @@ -99,7 +101,7 @@ maven-surefire-plugin - 2.20.1 + ${surefire.plugin.version} false @@ -126,6 +128,7 @@ 2.4.0 1.1-groovy-2.4 1.6 + 2.20.1 diff --git a/core-groovy/README.md b/core-groovy/README.md index 25a0aece3a..f852b3ccf2 100644 --- a/core-groovy/README.md +++ b/core-groovy/README.md @@ -12,4 +12,5 @@ This module contains articles about core Groovy concepts - [Closures in Groovy](https://www.baeldung.com/groovy-closures) - [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date) - [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io) -- [[More -->]](/core-groovy-2) \ No newline at end of file +- [Convert String to Integer in Groovy](https://www.baeldung.com/groovy-convert-string-to-integer) +- [[More -->]](/core-groovy-2) diff --git a/core-groovy/pom.xml b/core-groovy/pom.xml index 6407f7c0c6..69833ff74d 100644 --- a/core-groovy/pom.xml +++ b/core-groovy/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-groovy 1.0-SNAPSHOT diff --git a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy index a479c265c4..da1dfc10ba 100644 --- a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy @@ -1,6 +1,7 @@ package com.baeldung.file import spock.lang.Specification +import spock.lang.Ignore class ReadFileUnitTest extends Specification { diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy new file mode 100644 index 0000000000..48cf48fa8a --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy @@ -0,0 +1,110 @@ +package com.baeldung.stringtoint + +import org.junit.Test + +import java.text.DecimalFormat + +import static org.junit.Assert.assertEquals +import static org.junit.Assert.assertNull + +class ConvertStringToInt { + + @Test + void givenString_whenUsingAsInteger_thenConvertToInteger() { + def stringNum = "123" + def invalidString = "123a" + Integer expectedInteger = 123 + Integer integerNum = stringNum as Integer + def intNum = invalidString?.isInteger() ? invalidString as Integer : null + + assertNull(null, intNum) + assertEquals(integerNum, expectedInteger) + } + + @Test + void givenString_whenUsingAsInt_thenConvertToInt() { + def stringNum = "123" + int expectedInt = 123 + int intNum = stringNum as int + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingToInteger_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = stringNum.toInteger() + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingParseInt_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = Integer.parseInt(stringNum) + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingValueOf_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = Integer.valueOf(stringNum) + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingIntValue_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = new Integer(stringNum).intValue() + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingNewInteger_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = new Integer(stringNum) + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingDecimalFormat_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + DecimalFormat decimalFormat = new DecimalFormat("#") + int intNum = decimalFormat.parse(stringNum).intValue() + + assertEquals(intNum, expectedInt) + } + + @Test(expected = NumberFormatException.class) + void givenInvalidString_whenUsingAs_thenThrowNumberFormatException() { + def invalidString = "123a" + invalidString as Integer + } + + @Test(expected = NullPointerException.class) + void givenNullString_whenUsingToInteger_thenThrowNullPointerException() { + def invalidString = null + invalidString.toInteger() + } + + @Test + void givenString_whenUsingIsInteger_thenCheckIfCorrectValue() { + def invalidString = "123a" + def validString = "123" + def invalidNum = invalidString?.isInteger() ? invalidString as Integer : false + def correctNum = validString?.isInteger() ? validString as Integer : false + + assertEquals(false, invalidNum) + assertEquals(123, correctNum) + } +} diff --git a/core-java-lambdas/README.md b/core-java-lambdas/README.md deleted file mode 100644 index 5b94953e68..0000000000 --- a/core-java-lambdas/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Java 9 java.lang.Module API](https://www.baeldung.com/java-lambda-effectively-final-local-variables) diff --git a/core-java-modules/core-java-10/pom.xml b/core-java-modules/core-java-10/pom.xml index 49ebbfb283..a9b991852f 100644 --- a/core-java-modules/core-java-10/pom.xml +++ b/core-java-modules/core-java-10/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-10 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-11/README.md b/core-java-modules/core-java-11/README.md index 93a2c6faf5..70e2e66737 100644 --- a/core-java-modules/core-java-11/README.md +++ b/core-java-modules/core-java-11/README.md @@ -12,3 +12,5 @@ This module contains articles about Java 11 core features - [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector) - [Guide to jlink](https://www.baeldung.com/jlink) - [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference) +- [Benchmark JDK Collections vs Eclipse Collections](https://www.baeldung.com/jdk-collections-vs-eclipse-collections) +- [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile) diff --git a/core-java-modules/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml index 5bebaae00d..bbc4219eaa 100644 --- a/core-java-modules/core-java-11/pom.xml +++ b/core-java-modules/core-java-11/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 core-java-11 0.1.0-SNAPSHOT @@ -42,12 +43,12 @@ org.eclipse.collections eclipse-collections - 10.0.0 + ${eclipse.collections.version} org.eclipse.collections eclipse-collections-api - 10.0.0 + ${eclipse.collections.version} @@ -65,7 +66,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.1 + ${shade.plugin.version} package @@ -78,14 +79,11 @@ org.openjdk.jmh.Main - + - + *:* META-INF/*.SF @@ -108,6 +106,8 @@ 3.11.1 benchmarks 1.22 + 10.0.0 + 10.0.0 diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/patternreuse/PatternJava11UnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/patternreuse/PatternJava11UnitTest.java new file mode 100644 index 0000000000..e334d2c843 --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/patternreuse/PatternJava11UnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.patternreuse; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PatternJava11UnitTest { + + @Test + public void givenPreCompiledPattern_whenCallAsMatchPredicate_thenReturnMatchPredicateToMatchesPattern() { + List namesToValidate = Arrays.asList("Fabio Silva", "Fabio Luis Silva"); + Pattern firstLastNamePreCompiledPattern = Pattern.compile("[a-zA-Z]{3,} [a-zA-Z]{3,}"); + + Predicate patternAsMatchPredicate = firstLastNamePreCompiledPattern.asMatchPredicate(); + List validatedNames = namesToValidate.stream() + .filter(patternAsMatchPredicate) + .collect(Collectors.toList()); + + assertTrue(validatedNames.contains("Fabio Silva")); + assertFalse(validatedNames.contains("Fabio Luis Silva")); + } +} diff --git a/core-java-modules/core-java-12/pom.xml b/core-java-modules/core-java-12/pom.xml index 171d3f6e73..373f23488e 100644 --- a/core-java-modules/core-java-12/pom.xml +++ b/core-java-modules/core-java-12/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 core-java-12 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-13/README.md b/core-java-modules/core-java-13/README.md new file mode 100644 index 0000000000..697f89c362 --- /dev/null +++ b/core-java-modules/core-java-13/README.md @@ -0,0 +1,4 @@ +### Relevant articles: + +- [Java Switch Statement](https://www.baeldung.com/java-switch) +- [New Java 13 Features](https://www.baeldung.com/java-13-new-features) diff --git a/core-java-modules/core-java-13/pom.xml b/core-java-modules/core-java-13/pom.xml index 1f215ae6b0..4537067567 100644 --- a/core-java-modules/core-java-13/pom.xml +++ b/core-java-modules/core-java-13/pom.xml @@ -1,5 +1,7 @@ - 4.0.0 com.baeldung @@ -41,7 +43,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M3 + ${surefire.plugin.version} --enable-preview @@ -53,6 +55,7 @@ 13 13 3.6.1 + 3.0.0-M3 \ No newline at end of file diff --git a/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java new file mode 100644 index 0000000000..be1fcfd167 --- /dev/null +++ b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.newfeatures; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class SwitchExpressionsWithYieldUnitTest { + + @Test + @SuppressWarnings("preview") + public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() { + var me = 4; + var operation = "squareMe"; + var result = switch (operation) { + case "doubleMe" -> { + yield me * 2; + } + case "squareMe" -> { + yield me * me; + } + default -> me; + }; + + assertEquals(16, result); + } + +} diff --git a/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java new file mode 100644 index 0000000000..1f8ddcbfb4 --- /dev/null +++ b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.newfeatures; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class TextBlocksUnitTest { + + private static final String JSON_STRING = "{\r\n" + "\"name\" : \"Baeldung\",\r\n" + "\"website\" : \"https://www.%s.com/\"\r\n" + "}"; + + @SuppressWarnings("preview") + private static final String TEXT_BLOCK_JSON = """ + { + "name" : "Baeldung", + "website" : "https://www.%s.com/" + } + """; + + @Test + public void whenTextBlocks_thenStringOperationsWork() { + + assertThat(TEXT_BLOCK_JSON.contains("Baeldung")).isTrue(); + assertThat(TEXT_BLOCK_JSON.indexOf("www")).isGreaterThan(0); + assertThat(TEXT_BLOCK_JSON.length()).isGreaterThan(0); + + } + + @SuppressWarnings("removal") + @Test + public void whenTextBlocks_thenFormattedWorksAsFormat() { + assertThat(TEXT_BLOCK_JSON.formatted("baeldung") + .contains("www.baeldung.com")).isTrue(); + + assertThat(String.format(JSON_STRING, "baeldung") + .contains("www.baeldung.com")).isTrue(); + + } + +} diff --git a/core-java-modules/core-java-14/.mvn/jvm.config b/core-java-modules/core-java-14/.mvn/jvm.config new file mode 100644 index 0000000000..50f549be0a --- /dev/null +++ b/core-java-modules/core-java-14/.mvn/jvm.config @@ -0,0 +1 @@ +--enable-preview \ No newline at end of file diff --git a/core-java-modules/core-java-14/README.md b/core-java-modules/core-java-14/README.md new file mode 100644 index 0000000000..13bb468b30 --- /dev/null +++ b/core-java-modules/core-java-14/README.md @@ -0,0 +1,10 @@ +## Core Java 14 + +This module contains articles about Java 14. + +### Relevant articles + +- [Guide to the @Serial Annotation in Java 14](https://www.baeldung.com/java-14-serial-annotation) +- [Java Text Blocks](https://www.baeldung.com/java-text-blocks) +- [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof) +- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception) diff --git a/core-java-modules/core-java-14/pom.xml b/core-java-modules/core-java-14/pom.xml new file mode 100644 index 0000000000..96cb6b37e7 --- /dev/null +++ b/core-java-modules/core-java-14/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + core-java-14 + core-java-14 + jar + http://maven.apache.org + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.release} + --enable-preview + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.plugin.version} + + --enable-preview + + + + + + + 14 + 3.6.1 + 3.8.1 + 3.0.0-M3 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/npe/HelpfulNullPointerException.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/npe/HelpfulNullPointerException.java new file mode 100644 index 0000000000..913f796cd4 --- /dev/null +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/npe/HelpfulNullPointerException.java @@ -0,0 +1,56 @@ +package com.baeldung.java14.npe; + +public class HelpfulNullPointerException { + + public static void main(String[] args) { + Employee employee = null; + employee.getName(); + } + + public String getEmployeeEmailAddress(Employee employee) { + String emailAddress = employee.getPersonalDetails().getEmailAddress().toLowerCase(); + return emailAddress; + } + + static class Employee { + String name; + PersonalDetails personalDetails; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public PersonalDetails getPersonalDetails() { + return personalDetails; + } + + public void setPersonalDetails(PersonalDetails personalDetails) { + this.personalDetails = personalDetails; + } + } + + static class PersonalDetails { + String emailAddress; + String phone; + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + } +} diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/patternmatchingforinstanceof/PatternMatchingForInstanceOf.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/patternmatchingforinstanceof/PatternMatchingForInstanceOf.java new file mode 100644 index 0000000000..11026f45f9 --- /dev/null +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/patternmatchingforinstanceof/PatternMatchingForInstanceOf.java @@ -0,0 +1,26 @@ +package com.baeldung.java14.patternmatchingforinstanceof; + +public class PatternMatchingForInstanceOf { + + public void performAnimalOperations(Animal animal) { + if (animal instanceof Cat cat) { + cat.meow(); + } else if(animal instanceof Dog dog) { + dog.woof(); + } + } + + abstract class Animal { + } + + final class Cat extends Animal { + void meow() { + } + } + + final class Dog extends Animal { + void woof() { + } + } + +} diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/textblocks/TextBlocks13.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/textblocks/TextBlocks13.java new file mode 100644 index 0000000000..58d4cf44f3 --- /dev/null +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/textblocks/TextBlocks13.java @@ -0,0 +1,46 @@ +package com.baeldung.java14.textblocks; + +public class TextBlocks13 { + public String getBlockOfHtml() { + return """ + + + + example text + + """; + } + + public String getNonStandardIndent() { + return """ + Indent + """; + } + + public String getQuery() { + return """ + select "id", "user" + from "table" + """; + } + + public String getTextWithCarriageReturns() { + return """ + separated with\r + carriage returns"""; + } + + public String getTextWithEscapes() { + return """ + fun with\n + whitespace\t\r + and other escapes \""" + """; + } + + public String getFormattedText(String parameter) { + return """ + Some parameter: %s + """.formatted(parameter); + } +} diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/textblocks/TextBlocks14.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/textblocks/TextBlocks14.java new file mode 100644 index 0000000000..90fc15e884 --- /dev/null +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/textblocks/TextBlocks14.java @@ -0,0 +1,16 @@ +package com.baeldung.java14.textblocks; + +public class TextBlocks14 { + public String getIgnoredNewLines() { + return """ + This is a long test which looks to \ + have a newline but actually does not"""; + } + + public String getEscapedSpaces() { + return """ + line 1 + line 2 \s + """; + } +} diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/serial/MySerialClass.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/serial/MySerialClass.java new file mode 100644 index 0000000000..b28e53bdaa --- /dev/null +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/serial/MySerialClass.java @@ -0,0 +1,50 @@ +package com.baeldung.serial; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamException; +import java.io.ObjectStreamField; +import java.io.Serial; +import java.io.Serializable; + +/** + * Class showcasing the usage of the Java 14 @Serial annotation. + * + * @author Donato Rimenti + */ +public class MySerialClass implements Serializable { + + @Serial + private static final ObjectStreamField[] serialPersistentFields = null; + + @Serial + private static final long serialVersionUID = 1; + + @Serial + private void writeObject(ObjectOutputStream stream) throws IOException { + // ... + } + + @Serial + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + // ... + } + + @Serial + private void readObjectNoData() throws ObjectStreamException { + // ... + } + + @Serial + private Object writeReplace() throws ObjectStreamException { + // ... + return null; + } + + @Serial + private Object readResolve() throws ObjectStreamException { + // ... + return null; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java new file mode 100644 index 0000000000..b2264f30e6 --- /dev/null +++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java @@ -0,0 +1,84 @@ +package com.baeldung.java14.foreign.api; + +import jdk.incubator.foreign.*; +import org.junit.Test; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +import java.lang.invoke.VarHandle; +import java.nio.ByteOrder; + +public class ForeignMemoryUnitTest { + + @Test + public void whenAValueIsSet_thenAccessTheValue() { + long value = 10; + MemoryAddress memoryAddress = + MemorySegment.allocateNative(8).baseAddress(); + VarHandle varHandle = MemoryHandles.varHandle(long.class, + ByteOrder.nativeOrder()); + varHandle.set(memoryAddress, value); + assertThat(varHandle.get(memoryAddress), is(value)); + } + + @Test + public void whenMultipleValuesAreSet_thenAccessAll() { + VarHandle varHandle = MemoryHandles.varHandle(int.class, + ByteOrder.nativeOrder()); + + try(MemorySegment memorySegment = + MemorySegment.allocateNative(100)) { + MemoryAddress base = memorySegment.baseAddress(); + for(int i=0; i<25; i++) { + varHandle.set(base.addOffset((i*4)), i); + } + for(int i=0; i<25; i++) { + assertThat(varHandle.get(base.addOffset((i*4))), is(i)); + } + } + } + + @Test + public void whenSetValuesWithMemoryLayout_thenTheyCanBeRetrieved() { + SequenceLayout sequenceLayout = + MemoryLayout.ofSequence(25, + MemoryLayout.ofValueBits(64, ByteOrder.nativeOrder())); + VarHandle varHandle = + sequenceLayout.varHandle(long.class, + MemoryLayout.PathElement.sequenceElement()); + + try(MemorySegment memorySegment = + MemorySegment.allocateNative(sequenceLayout)) { + MemoryAddress base = memorySegment.baseAddress(); + for(long i=0; i\n" + + " example text\n" + + " \n" + + ""; + assertThat(subject.getBlockOfHtml()).isEqualTo(expected); + } + + @Test + void givenAnOldStyleString_whenComparing_thenEqualsTextBlock() { + String expected = "\n\n \n example text\n \n"; + assertThat(subject.getBlockOfHtml()).isEqualTo(expected); + } + + @Test + void givenAnIndentedString_thenMatchesIndentedOldStyle() { + assertThat(subject.getNonStandardIndent()).isEqualTo(" Indent\n"); + } + + @Test + void givenAMultilineQuery_thenItCanContainUnescapedQuotes() { + assertThat(subject.getQuery()).contains("select \"id\", \"user\""); + } + + @Test + void givenAMultilineQuery_thenItEndWithANewline() { + assertThat(subject.getQuery()).endsWith("\n"); + } + + @Test + void givenATextWithCarriageReturns_thenItContainsBoth() { + assertThat(subject.getTextWithCarriageReturns()).isEqualTo("separated with\r\ncarriage returns"); + } + + @Test + void givenAStringWithEscapedWhitespace_thenItAppearsInTheResultingString() { + assertThat(subject.getTextWithEscapes()).contains("fun with\n\n") + .contains("whitespace\t\r\n") + .contains("and other escapes \"\"\""); + } + + @Test + void givenAFormattedString_thenTheParameterIsReplaced() { + assertThat(subject.getFormattedText("parameter")).contains("Some parameter: parameter"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/textblocks/TextBlocks14UnitTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/textblocks/TextBlocks14UnitTest.java new file mode 100644 index 0000000000..fe671e8638 --- /dev/null +++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/textblocks/TextBlocks14UnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.java14.textblocks; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +class TextBlocks14UnitTest { + private TextBlocks14 subject = new TextBlocks14(); + + @Test + void givenAStringWithEscapedNewLines_thenTheResultHasNoNewLines() { + String expected = "This is a long test which looks to have a newline but actually does not"; + assertThat(subject.getIgnoredNewLines()).isEqualTo(expected); + } + + @Test + void givenAStringWithEscapesSpaces_thenTheResultHasLinesEndingWithSpaces() { + String expected = "line 1\nline 2 \n"; + assertThat(subject.getEscapedSpaces()).isEqualTo(expected); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md index 3d38fbbdbc..c1c09d2192 100644 --- a/core-java-modules/core-java-8-2/README.md +++ b/core-java-modules/core-java-8-2/README.md @@ -3,8 +3,7 @@ This module contains articles about Java 8 core features ### Relevant Articles: -- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes) -- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) + - [Run a Java Application from the Command Line](https://www.baeldung.com/java-run-jar-with-arguments) - [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit) - [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface) diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml index 746755f7a9..00579c49b2 100644 --- a/core-java-modules/core-java-8-2/pom.xml +++ b/core-java-modules/core-java-8-2/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 core-java-8-2 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-8-datetime-2/README.md b/core-java-modules/core-java-8-datetime-2/README.md new file mode 100644 index 0000000000..f16563aacc --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/README.md @@ -0,0 +1,5 @@ +### Relevant Articles: + +- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates) +- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values) +- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1) \ No newline at end of file diff --git a/core-java-modules/core-java-8-datetime-2/pom.xml b/core-java-modules/core-java-8-datetime-2/pom.xml new file mode 100644 index 0000000000..ce98b72781 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + core-java-8-datetime + ${project.parent.version} + core-java-8-datetime + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + joda-time + joda-time + ${joda-time.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + log4j + log4j + ${log4j.version} + test + + + + + core-java-datetime-java8 + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 1.8 + 1.8 + 2.10 + + 3.6.1 + + + diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/localdate/LocalDateExample.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/localdate/LocalDateExample.java new file mode 100644 index 0000000000..f4c9e5431f --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/localdate/LocalDateExample.java @@ -0,0 +1,31 @@ +package com.baeldung.localdate; + +import java.time.LocalDate; +import java.time.Month; +import java.time.format.DateTimeFormatter; + +public class LocalDateExample { + public LocalDate getCustomDateOne(int year, int month, int dayOfMonth) { + return LocalDate.of(year, month, dayOfMonth); + } + + public LocalDate getCustomDateTwo(int year, Month month, int dayOfMonth) { + return LocalDate.of(year, month, dayOfMonth); + } + + public LocalDate getDateFromEpochDay(long epochDay) { + return LocalDate.ofEpochDay(epochDay); + } + + public LocalDate getDateFromYearAndDayOfYear(int year, int dayOfYear) { + return LocalDate.ofYearDay(year, dayOfYear); + } + + public LocalDate getDateFromString(String date) { + return LocalDate.parse(date); + } + + public LocalDate getDateFromStringAndFormatter(String date, String pattern) { + return LocalDate.parse(date, DateTimeFormatter.ofPattern(pattern)); + } +} diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDateTimes.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDateTimes.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDateTimes.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDateTimes.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDates.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDates.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDates.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDates.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomTimes.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomTimes.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomTimes.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomTimes.java diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java new file mode 100644 index 0000000000..d65118ba3a --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.localdate; + +import static org.junit.Assert.assertEquals; + +import java.time.Month; + +import org.junit.Test; + +public class LocalDateExampleUnitTest { + private LocalDateExample date = new LocalDateExample(); + + @Test + public void givenValues_whenUsingOfMethod_thenLocalDate() { + assertEquals("2020-01-08", date.getCustomDateOne(2020, 1, 8).toString()); + } + + @Test + public void givenValuesWithMonthEnum_whenUsingOfMethod_thenLocalDate() { + assertEquals("2020-01-08", date.getCustomDateTwo(2020, Month.JANUARY, 8).toString()); + } + + @Test + public void givenValues_whenUsingEpochDay_thenLocalDate() { + assertEquals("2020-01-08", date.getDateFromEpochDay(18269).toString()); + } + + @Test + public void givenValues_whenUsingYearDay_thenLocalDate() { + assertEquals("2020-01-08", date.getDateFromYearAndDayOfYear(2020, 8).toString()); + } + + @Test + public void givenValues_whenUsingParse_thenLocalDate() { + assertEquals("2020-01-08", date.getDateFromString("2020-01-08").toString()); + } + + @Test + public void givenValuesWithFormatter_whenUsingParse_thenLocalDate() { + assertEquals("2020-01-08", date.getDateFromStringAndFormatter("8-Jan-2020", "d-MMM-yyyy").toString()); + } +} diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDatesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDatesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDatesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDatesUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomTimesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomTimesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomTimesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomTimesUnitTest.java diff --git a/core-java-modules/core-java-8-datetime/README.md b/core-java-modules/core-java-8-datetime/README.md new file mode 100644 index 0000000000..c35683a589 --- /dev/null +++ b/core-java-modules/core-java-8-datetime/README.md @@ -0,0 +1,16 @@ +## Java 8+ Date and Time API + +This module contains articles about the Date and Time API introduced with Java 8. + +### Relevant Articles: +- [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) +- [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) +- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) +- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime) +- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) +- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) +- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone) +- [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates) +- [[Next -->]](/core-java-modules/core-java-datetime-java8-2) diff --git a/core-java-modules/core-java-8-datetime/pom.xml b/core-java-modules/core-java-8-datetime/pom.xml new file mode 100644 index 0000000000..ce98b72781 --- /dev/null +++ b/core-java-modules/core-java-8-datetime/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + core-java-8-datetime + ${project.parent.version} + core-java-8-datetime + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + joda-time + joda-time + ${joda-time.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + log4j + log4j + ${log4j.version} + test + + + + + core-java-datetime-java8 + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 1.8 + 1.8 + 2.10 + + 3.6.1 + + + diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDuration.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDuration.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDuration.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDate.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDate.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDate.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDateTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UsePeriod.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UsePeriod.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UsePeriod.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseToInstant.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseToInstant.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseToInstant.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseZonedDateTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseZonedDateTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/ConversionExample.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/ConversionExample.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/ConversionExample.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/ConversionExample.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java diff --git a/core-java-modules/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml index c2c84a5407..a434be028d 100644 --- a/core-java-modules/core-java-8/pom.xml +++ b/core-java-modules/core-java-8/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-8 0.1.0-SNAPSHOT @@ -48,25 +50,6 @@ true - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - repackage - - - spring-boot - org.baeldung.executable.ExecutableMavenJar - - - - - @@ -74,8 +57,6 @@ 4.1 3.6.1 - - 2.0.4.RELEASE diff --git a/core-java-modules/core-java-9-improvements/README.md b/core-java-modules/core-java-9-improvements/README.md index 5864170e85..c89d0e3c09 100644 --- a/core-java-modules/core-java-9-improvements/README.md +++ b/core-java-modules/core-java-9-improvements/README.md @@ -9,8 +9,3 @@ This module contains articles about the improvements to core Java features intro - [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api) - [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new) - [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture) - -#### Relevant articles not in this module: - -- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api) (see the [core-java-os](/core-java-os) module) - diff --git a/core-java-modules/core-java-9-improvements/pom.xml b/core-java-modules/core-java-9-improvements/pom.xml index 9958bf9364..d1c6bac9ec 100644 --- a/core-java-modules/core-java-9-improvements/pom.xml +++ b/core-java-modules/core-java-9-improvements/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-9-improvements 0.2-SNAPSHOT diff --git a/core-java-modules/core-java-9-jigsaw/pom.xml b/core-java-modules/core-java-9-jigsaw/pom.xml index ecb36c365d..6ad4c3d510 100644 --- a/core-java-modules/core-java-9-jigsaw/pom.xml +++ b/core-java-modules/core-java-9-jigsaw/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-9-jigsaw 0.2-SNAPSHOT diff --git a/core-java-modules/core-java-9-new-features/pom.xml b/core-java-modules/core-java-9-new-features/pom.xml index 9db1112f1d..b0fb6ab7f9 100644 --- a/core-java-modules/core-java-9-new-features/pom.xml +++ b/core-java-modules/core-java-9-new-features/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-9-new-features 0.2-SNAPSHOT diff --git a/core-java-modules/core-java-9-streams/pom.xml b/core-java-modules/core-java-9-streams/pom.xml index 99be29f2b0..7865b336a7 100644 --- a/core-java-modules/core-java-9-streams/pom.xml +++ b/core-java-modules/core-java-9-streams/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-9-streams 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-9/README.md b/core-java-modules/core-java-9/README.md index e2bea5f7e2..0a9bf76ac4 100644 --- a/core-java-modules/core-java-9/README.md +++ b/core-java-modules/core-java-9/README.md @@ -8,7 +8,4 @@ This module contains articles about Java 9 core features - [Introduction to Chronicle Queue](https://www.baeldung.com/java-chronicle-queue) - [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) -- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) - -Note: also contains part of the code for the article -[How to Filter a Collection in Java](https://www.baeldung.com/java-collection-filtering). +- [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list) diff --git a/core-java-modules/core-java-9/pom.xml b/core-java-modules/core-java-9/pom.xml index 23a465caa1..b6dff0a3a4 100644 --- a/core-java-modules/core-java-9/pom.xml +++ b/core-java-modules/core-java-9/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-9 0.2-SNAPSHOT @@ -37,6 +39,11 @@ ${junit.platform.version} test + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + @@ -69,6 +76,7 @@ 1.9 1.9 25.1-jre + 4.1 diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/list/immutable/ImmutableArrayListUnitTest.java b/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/list/immutable/ImmutableArrayListUnitTest.java new file mode 100644 index 0000000000..f148b66dad --- /dev/null +++ b/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/list/immutable/ImmutableArrayListUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.java9.list.immutable; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.collections4.ListUtils; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class ImmutableArrayListUnitTest { + + @Test(expected = UnsupportedOperationException.class) + public final void givenUsingTheJdk_whenUnmodifiableListIsCreated_thenNotModifiable() { + final List list = new ArrayList<>(Arrays.asList("one", "two", "three")); + final List unmodifiableList = Collections.unmodifiableList(list); + unmodifiableList.add("four"); + } + + @Test(expected = UnsupportedOperationException.class) + public final void givenUsingTheJava9_whenUnmodifiableListIsCreated_thenNotModifiable() { + final List list = new ArrayList<>(Arrays.asList("one", "two", "three")); + final List unmodifiableList = List.of(list.toArray(new String[]{})); + unmodifiableList.add("four"); + } + + @Test(expected = UnsupportedOperationException.class) + public final void givenUsingGuava_whenUnmodifiableListIsCreated_thenNotModifiable() { + final List list = new ArrayList<>(Arrays.asList("one", "two", "three")); + final List unmodifiableList = ImmutableList.copyOf(list); + unmodifiableList.add("four"); + } + + @Test(expected = UnsupportedOperationException.class) + public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreated_thenNoLongerModifiable() { + final List list = new ArrayList<>(Arrays.asList("one", "two", "three")); + final ImmutableList unmodifiableList = ImmutableList.builder().addAll(list).build(); + unmodifiableList.add("four"); + } + + @Test(expected = UnsupportedOperationException.class) + public final void givenUsingCommonsCollections_whenUnmodifiableListIsCreated_thenNotModifiable() { + final List list = new ArrayList<>(Arrays.asList("one", "two", "three")); + final List unmodifiableList = ListUtils.unmodifiableList(list); + unmodifiableList.add("four"); + } +} diff --git a/core-java-modules/core-java-annotations/pom.xml b/core-java-modules/core-java-annotations/pom.xml index a97686a5b5..8fc4c15cde 100644 --- a/core-java-modules/core-java-annotations/pom.xml +++ b/core-java-modules/core-java-annotations/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-annotations 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-arrays-2/README.md b/core-java-modules/core-java-arrays-2/README.md deleted file mode 100644 index a78b3327b6..0000000000 --- a/core-java-modules/core-java-arrays-2/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Core Java Arrays (Part 2) - -This module contains articles about Java arrays - -## Relevant Articles - -- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end) -- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array) -- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array) -- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array) -- [Array Operations in Java](https://www.baeldung.com/java-common-array-operations) -- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) -- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element) -- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element) -- [Adding an Element to a Java Array vs an ArrayList](https://www.baeldung.com/java-add-element-to-array-vs-list) -- [[<-- Prev]](/core-java-modules/core-java-arrays) diff --git a/core-java-modules/core-java-arrays-2/pom.xml b/core-java-modules/core-java-arrays-2/pom.xml deleted file mode 100644 index 3f6b7094bb..0000000000 --- a/core-java-modules/core-java-arrays-2/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - core-java-arrays-2 - 0.1.0-SNAPSHOT - core-java-arrays-2 - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - org.assertj - assertj-core - ${assertj-core.version} - test - - - - - core-java-arrays-2 - - - src/main/resources - true - - - - - - - 3.9 - - 3.10.0 - - - diff --git a/core-java-modules/core-java-arrays-convert/README.md b/core-java-modules/core-java-arrays-convert/README.md new file mode 100644 index 0000000000..4bd060a246 --- /dev/null +++ b/core-java-modules/core-java-arrays-convert/README.md @@ -0,0 +1,7 @@ +## Core Java Arrays - Conversions + +This module contains articles about arrays conversion in Java + +## Relevant Articles +- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array) +- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array) diff --git a/core-java-modules/core-java-arrays-convert/pom.xml b/core-java-modules/core-java-arrays-convert/pom.xml new file mode 100644 index 0000000000..bd50289f47 --- /dev/null +++ b/core-java-modules/core-java-arrays-convert/pom.xml @@ -0,0 +1,27 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-arrays-convert + core-java-arrays-convert + jar + + + + com.google.guava + guava + ${guava.version} + + + + + 28.2-jre + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/FloatToByteArray.java b/core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/FloatToByteArray.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/FloatToByteArray.java rename to core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/FloatToByteArray.java diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java b/core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java rename to core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/FloatToByteArrayUnitTest.java b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/FloatToByteArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/FloatToByteArrayUnitTest.java rename to core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/FloatToByteArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java rename to core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java diff --git a/core-java-modules/core-java-arrays-guides/README.md b/core-java-modules/core-java-arrays-guides/README.md new file mode 100644 index 0000000000..2e66080002 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/README.md @@ -0,0 +1,7 @@ +## Core Java Arrays - Guides + +This module contains complete guides about arrays in Java + +### Relevant Articles: +- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) +- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays) \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-guides/pom.xml b/core-java-modules/core-java-arrays-guides/pom.xml new file mode 100644 index 0000000000..ef718d5117 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/pom.xml @@ -0,0 +1,32 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-arrays-guides + core-java-arrays-guides + jar + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + + 1.19 + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayReferenceGuide.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayReferenceGuide.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayReferenceGuide.java rename to core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayReferenceGuide.java diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arrays/ParallelPrefixBenchmark.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/arrays/ParallelPrefixBenchmark.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/arrays/ParallelPrefixBenchmark.java rename to core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/arrays/ParallelPrefixBenchmark.java diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/arrays/ArraysUnitTest.java b/core-java-modules/core-java-arrays-guides/src/test/java/com/baeldung/arrays/ArraysUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/arrays/ArraysUnitTest.java rename to core-java-modules/core-java-arrays-guides/src/test/java/com/baeldung/arrays/ArraysUnitTest.java diff --git a/core-java-modules/core-java-arrays-multidimensional/README.md b/core-java-modules/core-java-arrays-multidimensional/README.md new file mode 100644 index 0000000000..d92747a4fb --- /dev/null +++ b/core-java-modules/core-java-arrays-multidimensional/README.md @@ -0,0 +1,7 @@ +## Core Java Arrays - Multidimensional + +This module contains articles about multidimensional arrays in Java + +### Relevant Articles: +- [Multi-Dimensional Arrays In Java](https://www.baeldung.com/java-jagged-arrays) +- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array) \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-multidimensional/pom.xml b/core-java-modules/core-java-arrays-multidimensional/pom.xml new file mode 100644 index 0000000000..6e49a20521 --- /dev/null +++ b/core-java-modules/core-java-arrays-multidimensional/pom.xml @@ -0,0 +1,15 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-arrays-multidimensional + core-java-arrays-multidimensional + jar + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java b/core-java-modules/core-java-arrays-multidimensional/src/main/java/com/baeldung/array/MultiDimensionalArray.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java rename to core-java-modules/core-java-arrays-multidimensional/src/main/java/com/baeldung/array/MultiDimensionalArray.java diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java b/core-java-modules/core-java-arrays-multidimensional/src/main/java/com/baeldung/array/looping/LoopDiagonally.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java rename to core-java-modules/core-java-arrays-multidimensional/src/main/java/com/baeldung/array/looping/LoopDiagonally.java diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java b/core-java-modules/core-java-arrays-multidimensional/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java rename to core-java-modules/core-java-arrays-multidimensional/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java b/core-java-modules/core-java-arrays-multidimensional/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java rename to core-java-modules/core-java-arrays-multidimensional/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java diff --git a/core-java-modules/core-java-arrays-operations-advanced/README.md b/core-java-modules/core-java-arrays-operations-advanced/README.md new file mode 100644 index 0000000000..af0c00641a --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/README.md @@ -0,0 +1,9 @@ +## Core Java Arrays - Advanced Operations + +This module contains articles about advanced operations on arrays in Java. They assume some background knowledge with arrays in Java. + +### Relevant Articles: +- [How to Copy an Array in Java](https://www.baeldung.com/java-array-copy) +- [Arrays.deepEquals](https://www.baeldung.com/java-arrays-deepequals) +- [Find Sum and Average in a Java Array](https://www.baeldung.com/java-array-sum-average) +- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) diff --git a/core-java-modules/core-java-arrays-operations-advanced/pom.xml b/core-java-modules/core-java-arrays-operations-advanced/pom.xml new file mode 100644 index 0000000000..8989e91189 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/pom.xml @@ -0,0 +1,36 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-arrays-operations-advanced + core-java-arrays-operations-advanced + jar + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + 3.9 + + 3.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SumAndAverageInArray.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/array/SumAndAverageInArray.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SumAndAverageInArray.java rename to core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/array/SumAndAverageInArray.java diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/array/operations/ArraysIntersectionOperations.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/array/operations/ArraysIntersectionOperations.java new file mode 100644 index 0000000000..6c4ce837ad --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/array/operations/ArraysIntersectionOperations.java @@ -0,0 +1,27 @@ +package com.baeldung.array.operations; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.stream.Stream; + +public class ArraysIntersectionOperations { + + public static Integer[] intersectionSimple(final Integer[] a, final Integer[] b) { + return Stream.of(a) + .filter(Arrays.asList(b)::contains) + .toArray(Integer[]::new); + } + + public static Integer[] intersectionSet(final Integer[] a, final Integer[] b) { + return Stream.of(a) + .filter(Arrays.asList(b)::contains) + .distinct() + .toArray(Integer[]::new); + } + + public static Integer[] intersectionMultiSet(final Integer[] a, final Integer[] b) { + return Stream.of(a) + .filter(new LinkedList<>(Arrays.asList(b))::remove) + .toArray(Integer[]::new); + } +} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Address.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraycopy/model/Address.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Address.java rename to core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraycopy/model/Address.java diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraycopy/model/Employee.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java rename to core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraycopy/model/Employee.java diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java rename to core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java similarity index 97% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java rename to core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java index 1560cc5701..b0d4a80b06 100644 --- a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java @@ -2,7 +2,7 @@ package com.baeldung.array.operations; import org.junit.jupiter.api.Test; -import static com.baeldung.array.operations.ArrayOperations.*; +import static com.baeldung.array.operations.ArraysIntersectionOperations.*; import static org.assertj.core.api.Assertions.assertThat; class IntersectionUnitTest { diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java rename to core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arrays/deepequals/ArraysDeepEqualsUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arrays/deepequals/ArraysDeepEqualsUnitTest.java new file mode 100644 index 0000000000..a9b8ed7e3f --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arrays/deepequals/ArraysDeepEqualsUnitTest.java @@ -0,0 +1,96 @@ +package com.baeldung.arrays.deepequals; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Objects; +import org.junit.jupiter.api.Test; + +public class ArraysDeepEqualsUnitTest { + + class Person { + private int id; + private String name; + private int age; + + Person(int id, String name, int age) { + this.id = id; + this.name = name; + this.age = age; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof Person)) + return false; + Person person = (Person) obj; + return id == person.id && name.equals(person.name) && age == person.age; + } + + @Override + public int hashCode() { + return Objects.hash(id, name, age); + } + } + + @Test + void givenTwoUnidimensionalObjectTypeArrays_whenUsingEqualsAndDeepEquals_thenBothShouldReturnTrue() { + Object[] anArray = new Object[] { "string1", "string2", "string3" }; + Object[] anotherArray = new Object[] { "string1", "string2", "string3" }; + + assertTrue(Arrays.equals(anArray, anotherArray)); + assertTrue(Arrays.deepEquals(anArray, anotherArray)); + } + + @Test + void givenTwoUnidimensionalObjectTypeArraysWithNullElements_whenUsingEqualsAndDeepEquals_thenBothShouldReturnTrue() { + Object[] anArray = new Object[] { "string1", null, "string3" }; + Object[] anotherArray = new Object[] { "string1", null, "string3" }; + + assertTrue(Arrays.equals(anArray, anotherArray)); + assertTrue(Arrays.deepEquals(anArray, anotherArray)); + } + + @Test + void givenTwoUnidimensionalObjectTypeArraysWithNestedElements_whenUsingEqualsAndDeepEquals_thenShouldReturnDifferently() { + Object[] anArray = new Object[] { "string1", null, new String[] { "nestedString1", "nestedString2" } }; + Object[] anotherArray = new Object[] { "string1", null, new String[] { "nestedString1", "nestedString2" } }; + + assertFalse(Arrays.equals(anArray, anotherArray)); + assertTrue(Arrays.deepEquals(anArray, anotherArray)); + } + + @Test + void givenTwoMultidimensionalPrimitiveTypeArrays_whenUsingEqualsAndDeepEquals_thenBothShouldReturnDifferently() { + int[][] anArray = { { 1, 2, 3 }, { 4, 5, 6, 9 }, { 7 } }; + int[][] anotherArray = { { 1, 2, 3 }, { 4, 5, 6, 9 }, { 7 } }; + + assertFalse(Arrays.equals(anArray, anotherArray)); + assertTrue(Arrays.deepEquals(anArray, anotherArray)); + } + + @Test + void givenTwoMultidimensionalObjectTypeArrays_whenUsingEqualsAndDeepEquals_thenBothShouldReturnDifferently() { + Person personArray1[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } }; + Person personArray2[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } }; + + assertFalse(Arrays.equals(personArray1, personArray2)); + assertTrue(Arrays.deepEquals(personArray1, personArray2)); + } + + @Test + void givenTwoMultidimensionalObjectTypeArrays_whenUsingDeepEqualsFromObjectsAndArraysClasses_thenBothShouldReturnTrue() { + Person personArray1[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } }; + Person personArray2[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } }; + + assertTrue(Objects.deepEquals(personArray1, personArray2)); + assertTrue(Arrays.deepEquals(personArray1, personArray2)); + } +} diff --git a/core-java-modules/core-java-arrays-operations-basic/README.md b/core-java-modules/core-java-arrays-operations-basic/README.md new file mode 100644 index 0000000000..ca81c23c98 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic/README.md @@ -0,0 +1,12 @@ +## Core Java Arrays - Basic Operations + +This module contains articles about Java array fundamentals. They assume no previous background knowledge on working with arrays. + +### Relevant Articles: +- [Initializing Arrays in Java](https://www.baeldung.com/java-initialize-array) +- [Array Operations in Java](https://www.baeldung.com/java-common-array-operations) +- [Adding an Element to a Java Array vs an ArrayList](https://www.baeldung.com/java-add-element-to-array-vs-list) +- [Check if a Java Array Contains a Value](https://www.baeldung.com/java-array-contains-value) +- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element) +- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element) +- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end) diff --git a/core-java-modules/core-java-arrays-operations-basic/pom.xml b/core-java-modules/core-java-arrays-operations-basic/pom.xml new file mode 100644 index 0000000000..4480c14bb2 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic/pom.xml @@ -0,0 +1,78 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-arrays-operations-basic + core-java-arrays-operations-basic + jar + + + + + org.apache.maven.plugins + maven-shade-plugin + ${shade.plugin.version} + + + package + + shade + + + benchmarks + + + org.openjdk.jmh.Main + + + + + + + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + 3.2.0 + + 3.9 + + 1.19 + + 3.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/AddElementToEndOfArray.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/AddElementToEndOfArray.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/AddElementToEndOfArray.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/AddElementToEndOfArray.java diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java similarity index 86% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java index f35064b783..30c3978a3a 100644 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java +++ b/core-java-modules/core-java-arrays-operations-basic/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(SearchArrayUnitTest.class.getSimpleName()).threads(1) + .include(SearchArrayBenchmark.class.getSimpleName()).threads(1) .forks(1).shouldFailOnError(true).shouldDoGC(true) .jvmArgs("-server").build(); diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayInitializer.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/ArrayInitializer.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayInitializer.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/ArrayInitializer.java diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java diff --git a/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/SearchArrayBenchmark.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/SearchArrayBenchmark.java new file mode 100644 index 0000000000..fc4b513250 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/SearchArrayBenchmark.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 SearchArrayBenchmark { + + @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-modules/core-java-arrays-2/src/main/java/com/baeldung/array/operations/ArrayOperations.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/operations/ArrayOperations.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/operations/ArrayOperations.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/operations/ArrayOperations.java diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/AddElementToEndOfArrayUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/AddElementToEndOfArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/AddElementToEndOfArrayUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/AddElementToEndOfArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/removefirst/RemoveFirstElementUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/removefirst/RemoveFirstElementUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/removefirst/RemoveFirstElementUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/removefirst/RemoveFirstElementUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java diff --git a/core-java-modules/core-java-arrays-sorting/README.md b/core-java-modules/core-java-arrays-sorting/README.md new file mode 100644 index 0000000000..dedc0340c0 --- /dev/null +++ b/core-java-modules/core-java-arrays-sorting/README.md @@ -0,0 +1,9 @@ +## Core Java Arrays - Sorting + +This module contains articles about sorting arrays in Java + +### Relevant Articles: +- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays) +- [Checking If an Array Is Sorted in Java](https://www.baeldung.com/java-check-sorted-array) +- [How to Reverse an Array in Java](https://www.baeldung.com/java-invert-array) +- [Arrays.sort vs Arrays.parallelSort](https://www.baeldung.com/java-arrays-sort-vs-parallelsort) diff --git a/core-java-modules/core-java-arrays-sorting/pom.xml b/core-java-modules/core-java-arrays-sorting/pom.xml new file mode 100644 index 0000000000..127d921b2a --- /dev/null +++ b/core-java-modules/core-java-arrays-sorting/pom.xml @@ -0,0 +1,87 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + ../pom.xml + + 4.0.0 + + core-java-arrays-sorting + core-java-arrays-sorting + jar + + + + + org.apache.maven.plugins + maven-shade-plugin + ${shade.plugin.version} + + + package + + shade + + + benchmarks + + + org.openjdk.jmh.Main + + + + + + + + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + com.google.guava + guava + ${guava.version} + + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + 3.2.0 + + 3.9 + 28.2-jre + + 1.19 + + 3.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayInverter.java b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/array/ArrayInverter.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayInverter.java rename to core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/array/ArrayInverter.java diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/array/SortedArrayChecker.java similarity index 97% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java rename to core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/array/SortedArrayChecker.java index 78a9a8f4d1..8fa64972f2 100644 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java +++ b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/array/SortedArrayChecker.java @@ -1,7 +1,5 @@ package com.baeldung.array; -import com.baeldung.arraycopy.model.Employee; - import java.util.Comparator; public class SortedArrayChecker { diff --git a/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java new file mode 100644 index 0000000000..640d729020 --- /dev/null +++ b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java @@ -0,0 +1,72 @@ +package com.baeldung.arraysort; + +import java.util.Arrays; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +@Fork(2) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +public class ArraySortingBenchmark { + + @State(Scope.Benchmark) + public static class ArrayContainer { + + @Param({ "1000", "10000", "100000", "1000000" }) + int arraySize; + + // initial unsorted array + int[] unsortedArray; + + //cloned array to sort + int[] arrayToSort; + + @Setup(Level.Trial) + public void createUnSortedArray() { + unsortedArray = new int[arraySize]; + for (int i = 0; i < arraySize; i++) { + unsortedArray[i] = new Random().nextInt(1000); + } + } + + @Setup(Level.Invocation) + public void createUnSortedArrayCopy() { + arrayToSort = unsortedArray.clone(); + } + + int[] getArrayToSort() { + return arrayToSort; + } + } + + @Benchmark + public void benchmark_arrays_parallel_sort(ArrayContainer d, Blackhole b) { + int[] arr = d.getArrayToSort(); + Arrays.parallelSort(arr); + b.consume(arr); + } + + @Benchmark + public void benchmark_arrays_sort(ArrayContainer d, Blackhole b) { + int[] arr = d.getArrayToSort(); + Arrays.sort(arr); + b.consume(arr); + } + +} diff --git a/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/sort/Employee.java b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/sort/Employee.java new file mode 100644 index 0000000000..e9c737b74b --- /dev/null +++ b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/sort/Employee.java @@ -0,0 +1,48 @@ +package com.baeldung.sort; + +import java.io.Serializable; + +public class Employee implements Serializable { + private static final long serialVersionUID = -2454619097207585825L; + private int id; + private String name; + private int age; + + public Employee() { + } + + public Employee(int id, String name) { + this.id = id; + this.name = name; + } + + public Employee(int id, String name, int age) { + this.id = id; + this.name = name; + this.age = age; + } + + public int getAge() { + return age; + } + + public int getId() { + return id; + } + + public void setAge(int age) { + this.age = age; + } + + 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-modules/core-java-arrays/src/test/java/com/baeldung/array/ArrayInverterUnitTest.java b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/array/ArrayInverterUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/ArrayInverterUnitTest.java rename to core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/array/ArrayInverterUnitTest.java diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java similarity index 98% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java rename to core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java index 7971e0eab7..5411dcba72 100644 --- a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java +++ b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java @@ -1,6 +1,6 @@ package com.baeldung.array; -import com.baeldung.arraycopy.model.Employee; +import com.baeldung.sort.Employee; import org.junit.Before; import org.junit.Test; diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraysort/SortComparisonUnitTest.java b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/arraysort/SortComparisonUnitTest.java similarity index 97% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraysort/SortComparisonUnitTest.java rename to core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/arraysort/SortComparisonUnitTest.java index d1aba5a886..4b0a18684a 100644 --- a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraysort/SortComparisonUnitTest.java +++ b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/arraysort/SortComparisonUnitTest.java @@ -69,7 +69,7 @@ public class SortComparisonUnitTest { } @Test - public void givenArrayOfIntegers_whenUsingArraysSortMethodWithRange_thenSortRangeOfArrayInAscendingOrder() { + public void givenArrayOfIntegers_whenUsingArraysSortWithRange_thenSortRangeOfArrayAsc() { int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 }; int[] expected = { 10, 4, 1, 2, 6, 7, 8, 9, 3, 5 }; @@ -89,7 +89,7 @@ public class SortComparisonUnitTest { } @Test - public void givenArrayOfIntegers_whenUsingArraysParallelSortMethodWithRange_thenSortRangeOfArrayInAscendingOrder() { + public void givenArrayOfIntegers_whenUsingArraysParallelSortWithRange_thenSortRangeOfArrayAsc() { int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 }; int[] expected = { 10, 4, 1, 2, 6, 7, 8, 9, 3, 5 }; diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/sort/ArraySortUnitTest.java b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/sort/ArraySortUnitTest.java similarity index 98% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/sort/ArraySortUnitTest.java rename to core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/sort/ArraySortUnitTest.java index 59035738fe..b89a870c51 100644 --- a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/sort/ArraySortUnitTest.java +++ b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/sort/ArraySortUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.sort; -import com.baeldung.arraycopy.model.Employee; import org.junit.Before; import org.junit.Test; @@ -86,5 +85,4 @@ public class ArraySortUnitTest { assertArrayEquals(new Employee[]{david, john, mary}, employees); } - } diff --git a/core-java-modules/core-java-arrays/README.md b/core-java-modules/core-java-arrays/README.md deleted file mode 100644 index 42fe3f83a1..0000000000 --- a/core-java-modules/core-java-arrays/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## Core Java Arrays - -This module contains articles about Java arrays - -### Relevant Articles: -- [How to Copy an Array in Java](https://www.baeldung.com/java-array-copy) -- [Check if a Java Array Contains a Value](https://www.baeldung.com/java-array-contains-value) -- [Initializing Arrays in Java](https://www.baeldung.com/java-initialize-array) -- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays) -- [Multi-Dimensional Arrays In Java](https://www.baeldung.com/java-jagged-arrays) -- [Find Sum and Average in a Java Array](https://www.baeldung.com/java-array-sum-average) -- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) -- [Read and Write User Input in Java](https://www.baeldung.com/java-console-input-output) -- [How to Reverse an Array in Java](http://www.baeldung.com/java-invert-array) -- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays) -- [Checking If an Array Is Sorted in Java](https://www.baeldung.com/java-check-sorted-array) -- [[More -->]](/core-java-modules/core-java-arrays-2) diff --git a/core-java-modules/core-java-arrays/pom.xml b/core-java-modules/core-java-arrays/pom.xml deleted file mode 100644 index 20a835594f..0000000000 --- a/core-java-modules/core-java-arrays/pom.xml +++ /dev/null @@ -1,378 +0,0 @@ - - - 4.0.0 - core-java-arrays - 0.1.0-SNAPSHOT - core-java-arrays - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - org.assertj - assertj-core - ${assertj-core.version} - test - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-generator-annprocess.version} - - - - - core-java-arrays - - - src/main/resources - 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 - ${maven-jar-plugin.version} - - - - 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 - ${maven-shade-plugin.version} - - - - shade - - - true - - - org.baeldung.executable.ExecutableMavenJar - - - - - - - - - com.jolira - onejar-maven-plugin - ${onejar-maven-plugin.version} - - - - 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} - - - - repackage - - - spring-boot - org.baeldung.executable.ExecutableMavenJar - - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - java - com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed - - -Xmx300m - -XX:+UseParallelGC - -classpath - - com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed - - - - - - 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 - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - json - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - - run-benchmarks - - none - - exec - - - test - java - - -classpath - - org.openjdk.jmh.Main - .* - - - - - - - - - - - - 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 - - - - - - - - - - - - - 3.9 - - 1.19 - 1.19 - - - 3.10.0 - - - 3.0.0-M1 - 3.0.2 - 1.4.4 - 3.1.1 - 2.0.3.RELEASE - 1.6.0 - - - diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/Find2ndLargestInArray.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/Find2ndLargestInArray.java deleted file mode 100644 index d424bd429f..0000000000 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/Find2ndLargestInArray.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.array; - -public class Find2ndLargestInArray { - - public static int find2ndLargestElement(int[] array) { - int maxElement = array[0]; - int secondLargestElement = -1; - - for (int index = 0; index < array.length; index++) { - if (maxElement <= array[index]) { - secondLargestElement = maxElement; - maxElement = array[index]; - } else if (secondLargestElement < array[index]) { - secondLargestElement = array[index]; - } - } - return secondLargestElement; - } - -} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/FindElementInArray.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/FindElementInArray.java deleted file mode 100644 index 6da889fe91..0000000000 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/FindElementInArray.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.array; - -import java.util.Arrays; - -public class FindElementInArray { - - public static boolean findGivenElementInArrayWithoutUsingStream(int[] array, int element) { - boolean actualResult = false; - - for (int index = 0; index < array.length; index++) { - if (element == array[index]) { - actualResult = true; - break; - } - } - return actualResult; - } - - public static boolean findGivenElementInArrayUsingStream(int[] array, int element) { - return Arrays.stream(array).filter(x -> element == x).findFirst().isPresent(); - } -} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SearchArrayUnitTest.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SearchArrayUnitTest.java deleted file mode 100644 index bed58356cb..0000000000 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SearchArrayUnitTest.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 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-modules/core-java-arrays/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java deleted file mode 100644 index 4493f3fbf5..0000000000 --- a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java +++ /dev/null @@ -1,16 +0,0 @@ -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-modules/core-java-arrays/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java deleted file mode 100644 index 887f50ebcc..0000000000 --- a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java +++ /dev/null @@ -1,35 +0,0 @@ -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-modules/core-java-collections-2/README.md b/core-java-modules/core-java-collections-2/README.md index de5daddb38..e5f6126811 100644 --- a/core-java-modules/core-java-collections-2/README.md +++ b/core-java-modules/core-java-collections-2/README.md @@ -12,4 +12,3 @@ - [Sorting in Java](https://www.baeldung.com/java-sorting) - [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size) - [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections) -- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream) diff --git a/core-java-modules/core-java-collections-2/pom.xml b/core-java-modules/core-java-collections-2/pom.xml index e0e7dd5c82..3a7c70b1a2 100644 --- a/core-java-modules/core-java-collections-2/pom.xml +++ b/core-java-modules/core-java-collections-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-collections-2 core-java-collections-2 diff --git a/core-java-modules/core-java-collections-3/pom.xml b/core-java-modules/core-java-collections-3/pom.xml index f94ff6f71f..1e1695c8bc 100644 --- a/core-java-modules/core-java-collections-3/pom.xml +++ b/core-java-modules/core-java-collections-3/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-collections-3 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-collections-array-list/README.md b/core-java-modules/core-java-collections-array-list/README.md index 302ea82130..3637f835cf 100644 --- a/core-java-modules/core-java-collections-array-list/README.md +++ b/core-java-modules/core-java-collections-array-list/README.md @@ -3,9 +3,8 @@ This module contains articles about the Java ArrayList collection ### Relevant Articles: -- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list) -- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist) -- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list) +- [Guide to the Java ArrayList](https://www.baeldung.com/java-arraylist) +- [Add Multiple Items to an Java ArrayList](https://www.baeldung.com/java-add-items-array-list) - [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist) - [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist) - [Removing an Element From an ArrayList](https://www.baeldung.com/java-arraylist-remove-element) diff --git a/core-java-modules/core-java-collections-array-list/pom.xml b/core-java-modules/core-java-collections-array-list/pom.xml index cf7889fa58..74a6513cac 100644 --- a/core-java-modules/core-java-collections-array-list/pom.xml +++ b/core-java-modules/core-java-collections-array-list/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-collections-array-list 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/collections/ArrayListUnitTest.java similarity index 99% rename from core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java rename to core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/collections/ArrayListUnitTest.java index 5d07628a96..9d14a63295 100644 --- a/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java +++ b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/collections/ArrayListUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.collections; +package com.baeldung.collections; import com.google.common.collect.Sets; import org.junit.Before; diff --git a/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/collections/CoreJavaCollectionsUnitTest.java b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/collections/CoreJavaCollectionsUnitTest.java new file mode 100644 index 0000000000..5fd0e605dd --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/collections/CoreJavaCollectionsUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.collections; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.collections4.ListUtils; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class CoreJavaCollectionsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(CoreJavaCollectionsUnitTest.class); + + @Test + public final void givenUsingTheJdk_whenArrayListIsSynchronized_thenCorrect() { + final List list = new ArrayList<>(Arrays.asList("one", "two", "three")); + final List synchronizedList = Collections.synchronizedList(list); + LOG.debug("Synchronized List is: " + synchronizedList); + } + +} diff --git a/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java b/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java deleted file mode 100644 index 5f7fe356c5..0000000000 --- a/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.baeldung.java.collections; - -import com.google.common.collect.ImmutableList; -import org.apache.commons.collections4.ListUtils; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class CoreJavaCollectionsUnitTest { - - private static final Logger LOG = LoggerFactory.getLogger(CoreJavaCollectionsUnitTest.class); - - - // tests - - - @Test - public final void givenUsingTheJdk_whenArrayListIsSynchronized_thenCorrect() { - final List list = new ArrayList(Arrays.asList("one", "two", "three")); - final List synchronizedList = Collections.synchronizedList(list); - LOG.debug("Synchronized List is: " + synchronizedList); - } - - @Test(expected = UnsupportedOperationException.class) - public final void givenUsingTheJdk_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() { - final List list = new ArrayList(Arrays.asList("one", "two", "three")); - final List unmodifiableList = Collections.unmodifiableList(list); - unmodifiableList.add("four"); - } - - @Test(expected = UnsupportedOperationException.class) - public final void givenUsingGuava_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() { - final List list = new ArrayList(Arrays.asList("one", "two", "three")); - final List unmodifiableList = ImmutableList.copyOf(list); - unmodifiableList.add("four"); - } - - @Test(expected = UnsupportedOperationException.class) - public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() { - final List list = new ArrayList(Arrays.asList("one", "two", "three")); - final ImmutableList unmodifiableList = ImmutableList.builder().addAll(list).build(); - unmodifiableList.add("four"); - } - - @Test(expected = UnsupportedOperationException.class) - public final void givenUsingCommonsCollections_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() { - final List list = new ArrayList(Arrays.asList("one", "two", "three")); - final List unmodifiableList = ListUtils.unmodifiableList(list); - unmodifiableList.add("four"); - } - -} diff --git a/core-java-modules/core-java-collections-list-2/README.md b/core-java-modules/core-java-collections-list-2/README.md index 0d2da41b41..2e43f610a9 100644 --- a/core-java-modules/core-java-collections-list-2/README.md +++ b/core-java-modules/core-java-collections-list-2/README.md @@ -3,13 +3,13 @@ This module contains articles about the Java List collection ### Relevant Articles: -- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) +- [Check If Two Lists are Equal in Java](https://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) - [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items) -- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist) -- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception) +- [A Guide to the Java LinkedList](https://www.baeldung.com/java-linkedlist) +- [Java List UnsupportedOperationException](https://www.baeldung.com/java-list-unsupported-operation-exception) - [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line) - [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list) -- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections) +- [Flattening Nested Collections in Java](https://www.baeldung.com/java-flatten-nested-collections) - [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection) - [Searching for a String in an ArrayList](https://www.baeldung.com/java-search-string-arraylist) - [[<-- Prev]](/core-java-modules/core-java-collections-list)[[Next -->]](/core-java-modules/core-java-collections-list-3) diff --git a/core-java-modules/core-java-collections-list-2/pom.xml b/core-java-modules/core-java-collections-list-2/pom.xml index 05b82a179b..3184da1294 100644 --- a/core-java-modules/core-java-collections-list-2/pom.xml +++ b/core-java-modules/core-java-collections-list-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-collections-list-2 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/java/list/ListAssertJUnitTest.java similarity index 95% rename from core-java-modules/core-java-collections-list-2/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java rename to core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/java/list/ListAssertJUnitTest.java index c609f5badb..fd15d92dac 100644 --- a/core-java-modules/core-java-collections-list-2/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/java/list/ListAssertJUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.lists; +package com.baeldung.java.list; import org.junit.Test; diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/org/baeldung/java/lists/ListJUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/java/list/ListJUnitTest.java similarity index 97% rename from core-java-modules/core-java-collections-list-2/src/test/java/org/baeldung/java/lists/ListJUnitTest.java rename to core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/java/list/ListJUnitTest.java index f9c9d3fda8..6537e2d153 100644 --- a/core-java-modules/core-java-collections-list-2/src/test/java/org/baeldung/java/lists/ListJUnitTest.java +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/java/list/ListJUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.lists; +package com.baeldung.java.list; import org.junit.Assert; import org.junit.Test; diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/java/list/ListTestNgUnitTest.java similarity index 94% rename from core-java-modules/core-java-collections-list-2/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java rename to core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/java/list/ListTestNgUnitTest.java index 86493f6e5d..07002b5613 100644 --- a/core-java-modules/core-java-collections-list-2/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/java/list/ListTestNgUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.lists; +package com.baeldung.java.list; import org.junit.Test; diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/org/baeldung/java/lists/README.md b/core-java-modules/core-java-collections-list-2/src/test/java/org/baeldung/java/lists/README.md deleted file mode 100644 index 2a1e8aeeaa..0000000000 --- a/core-java-modules/core-java-collections-list-2/src/test/java/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/core-java-modules/core-java-collections-list-3/pom.xml b/core-java-modules/core-java-collections-list-3/pom.xml index ced8a732c1..090e756ac6 100644 --- a/core-java-modules/core-java-collections-list-3/pom.xml +++ b/core-java-modules/core-java-collections-list-3/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-collections-list-3 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/duplicatescounter/DuplicatesCounter.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/duplicatescounter/DuplicatesCounter.java index b5138eed7d..e0c0b723e0 100644 --- a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/duplicatescounter/DuplicatesCounter.java +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/duplicatescounter/DuplicatesCounter.java @@ -24,11 +24,21 @@ public class DuplicatesCounter { return resultMap; } - public static Map countByClassicalLoopWithMapCompute(List inputList) { + public static Map countByForEachLoopWithGetOrDefault(List inputList) { Map resultMap = new HashMap<>(); - for (T element : inputList) { - resultMap.compute(element, (k, v) -> v == null ? 1 : v + 1); - } + inputList.forEach(e -> resultMap.put(e, resultMap.getOrDefault(e, 0L) + 1L)); + return resultMap; + } + + public static Map countByForEachLoopWithMapCompute(List inputList) { + Map resultMap = new HashMap<>(); + inputList.forEach(e -> resultMap.compute(e, (k, v) -> v == null ? 1L : v + 1L)); + return resultMap; + } + + public static Map countByForEachLoopWithMapMerge(List inputList) { + Map resultMap = new HashMap<>(); + inputList.forEach(e -> resultMap.merge(e, 1L, Long::sum)); return resultMap; } diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/duplicatescounter/DuplicatesCounterUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/duplicatescounter/DuplicatesCounterUnitTest.java index be9ccded9b..8d6825c590 100644 --- a/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/duplicatescounter/DuplicatesCounterUnitTest.java +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/duplicatescounter/DuplicatesCounterUnitTest.java @@ -11,7 +11,6 @@ import static org.assertj.core.data.MapEntry.entry; class DuplicatesCounterUnitTest { - private static List INPUT_LIST = Lists.list( "expect1", "expect2", "expect2", @@ -24,10 +23,21 @@ class DuplicatesCounterUnitTest { verifyResult(result); } + @Test + void givenInput_whenCountByForEachLoopWithGetOrDefault_thenGetResultMap() { + Map result = DuplicatesCounter.countByForEachLoopWithGetOrDefault(INPUT_LIST); + verifyResult(result); + } @Test - void givenInput_whenCountByClassicalLoopWithMapCompute_thenGetResultMap() { - Map result = DuplicatesCounter.countByClassicalLoopWithMapCompute(INPUT_LIST); + void givenInput_whenCountByForEachLoopWithMapCompute_thenGetResultMap() { + Map result = DuplicatesCounter.countByForEachLoopWithMapCompute(INPUT_LIST); + verifyResult(result); + } + + @Test + void givenInput_whenCountByForEachLoopWithMapMerge_thenGetResultMap() { + Map result = DuplicatesCounter.countByForEachLoopWithMapMerge(INPUT_LIST); verifyResult(result); } diff --git a/core-java-modules/core-java-collections-list/pom.xml b/core-java-modules/core-java-collections-list/pom.xml index 3227c94e78..e6dce5a0db 100644 --- a/core-java-modules/core-java-collections-list/pom.xml +++ b/core-java-modules/core-java-collections-list/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-collections-list 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-collections-list/src/test/java/org/baeldung/java/collections/JavaCollectionCleanupUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/collections/JavaCollectionCleanupUnitTest.java similarity index 98% rename from core-java-modules/core-java-collections-list/src/test/java/org/baeldung/java/collections/JavaCollectionCleanupUnitTest.java rename to core-java-modules/core-java-collections-list/src/test/java/com/baeldung/collections/JavaCollectionCleanupUnitTest.java index 537262607a..96813df862 100644 --- a/core-java-modules/core-java-collections-list/src/test/java/org/baeldung/java/collections/JavaCollectionCleanupUnitTest.java +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/collections/JavaCollectionCleanupUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.collections; +package com.baeldung.collections; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; diff --git a/core-java-modules/core-java-collections-list/src/test/java/org/baeldung/RandomListElementUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/random/RandomListElementUnitTest.java similarity index 98% rename from core-java-modules/core-java-collections-list/src/test/java/org/baeldung/RandomListElementUnitTest.java rename to core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/random/RandomListElementUnitTest.java index 4f5ba0f82f..95e013b481 100644 --- a/core-java-modules/core-java-collections-list/src/test/java/org/baeldung/RandomListElementUnitTest.java +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/random/RandomListElementUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung.list.random; import com.google.common.collect.Lists; import org.junit.Test; diff --git a/core-java-modules/core-java-collections-maps-2/README.md b/core-java-modules/core-java-collections-maps-2/README.md new file mode 100644 index 0000000000..f49ba25c8c --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/README.md @@ -0,0 +1,16 @@ +## Java Collections Cookbooks and Examples + +This module contains articles about Map data structures in Java. + +### Relevant Articles: +- [Map of Primitives in Java](https://www.baeldung.com/java-map-primitives) +- [Copying a HashMap in Java](https://www.baeldung.com/java-copy-hashmap) +- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) +- [Guide to WeakHashMap in Java](https://www.baeldung.com/java-weakhashmap) +- [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion) +- [Iterate over a Map in Java](https://www.baeldung.com/java-iterate-map) +- [Merging Two Maps with Java 8](https://www.baeldung.com/java-merge-maps) +- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort) +- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max) +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps) [[next -->]](/core-java-modules/core-java-collections-maps-3) diff --git a/core-java-modules/core-java-collections-maps-2/pom.xml b/core-java-modules/core-java-collections-maps-2/pom.xml new file mode 100644 index 0000000000..a08a4ac072 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/pom.xml @@ -0,0 +1,79 @@ + + + 4.0.0 + core-java-collections-maps-2 + 0.1.0-SNAPSHOT + core-java-collections-maps-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.eclipse.collections + eclipse-collections + ${eclipse-collections.version} + + + net.sf.trove4j + trove4j + ${trove4j.version} + + + it.unimi.dsi + fastutil + ${fastutil.version} + + + colt + colt + ${colt.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + one.util + streamex + ${streamex.version} + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 0.6.5 + 4.1 + 1.7.0 + 8.2.0 + 3.0.2 + 8.1.0 + 1.2.0 + 3.11.1 + + + \ No newline at end of file diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/Product.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/Product.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java similarity index 77% rename from java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java index 2015909870..ba29d5c454 100644 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java @@ -3,6 +3,8 @@ package com.baeldung.map; import org.junit.jupiter.api.Test; import java.util.HashMap; +import java.util.Map; +import java.util.Objects; import static org.junit.jupiter.api.Assertions.*; @@ -121,4 +123,52 @@ class ProductUnitTest { assertNull(productsByName.get("E-Bike")); } + @Test + public void givenMutableKeyWhenKeyChangeThenValueNotFound() { + // Given + MutableKey key = new MutableKey("initial"); + + Map items = new HashMap<>(); + items.put(key, "success"); + + // When + key.setName("changed"); + + // Then + assertNull(items.get(key)); + } + + static class MutableKey { + private String name; + + public MutableKey(String name) { + this.name = name; + } + + 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; + } + MutableKey that = (MutableKey) o; + return Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + } + } diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-3/README.md b/core-java-modules/core-java-collections-maps-3/README.md new file mode 100644 index 0000000000..7386f7e9b7 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-3/README.md @@ -0,0 +1,9 @@ +## Java Collections Cookbooks and Examples + +This module contains articles about Map data structures in Java. + +### Relevant Articles: +- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap) +- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) +- [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2) diff --git a/core-java-modules/core-java-collections-maps-3/pom.xml b/core-java-modules/core-java-collections-maps-3/pom.xml new file mode 100644 index 0000000000..95414c12c2 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-3/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + core-java-collections-maps-3 + 0.1.0-SNAPSHOT + core-java-collections-maps-3 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + + + + + + + \ No newline at end of file diff --git a/java-collections-maps/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java rename to core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/computeifabsent/ComputeIfAbsentUnitTest.java b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/computeifabsent/ComputeIfAbsentUnitTest.java new file mode 100644 index 0000000000..391a059f05 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/computeifabsent/ComputeIfAbsentUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.map.computeifabsent; + +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class ComputeIfAbsentUnitTest { + + @Test + public void whenKeyIsPresent_thenFetchTheValue() { + Map stringLength = new HashMap<>(); + stringLength.put("John", 5); + assertEquals((long)stringLength.computeIfAbsent("John", s -> s.length()), 5); + } + + @Test + public void whenKeyIsNotPresent_thenComputeTheValueUsingMappingFunctionAndStore() { + Map stringLength = new HashMap<>(); + assertEquals((long)stringLength.computeIfAbsent("John", s -> s.length()), 4); + assertEquals((long)stringLength.get("John"), 4); + } + + @Test + public void whenMappingFunctionReturnsNull_thenDoNotRecordMapping() { + Map stringLength = new HashMap<>(); + assertEquals(stringLength.computeIfAbsent("John", s -> null), null); + assertNull(stringLength.get("John")); + } + + @Test(expected = RuntimeException.class) + public void whenMappingFunctionThrowsException_thenExceptionIsRethrown() { + Map stringLength = new HashMap<>(); + stringLength.computeIfAbsent("John", s -> {throw new RuntimeException();}); + } +} diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java rename to core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps/README.md b/core-java-modules/core-java-collections-maps/README.md new file mode 100644 index 0000000000..15cb32fbe8 --- /dev/null +++ b/core-java-modules/core-java-collections-maps/README.md @@ -0,0 +1,15 @@ +## Java Collections Cookbooks and Examples + +This module contains articles about Map data structures in Java. + +### Relevant Articles: +- [Guide to the Guava BiMap](https://www.baeldung.com/guava-bimap) +- [A Guide to LinkedHashMap in Java](https://www.baeldung.com/java-linked-hashmap) +- [A Guide to TreeMap in Java](https://www.baeldung.com/java-treemap) +- [How to Store Duplicate Keys in a Map in Java?](https://www.baeldung.com/java-map-duplicate-keys) +- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value) +- [How to Check If a Key Exists in a Map](https://www.baeldung.com/java-map-key-exists) +- [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps) +- [Guide to Apache Commons MultiValuedMap](https://www.baeldung.com/apache-commons-multi-valued-map) +- [The Java HashMap Under the Hood](https://www.baeldung.com/java-hashmap-advanced) +- More articles: [[next -->]](/core-java-modules/core-java-collections-maps-2) diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml new file mode 100644 index 0000000000..c0dd705c1c --- /dev/null +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + core-java-collections-maps + 0.1.0-SNAPSHOT + core-java-collections-maps + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 4.1 + 3.6.1 + + diff --git a/java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java similarity index 100% rename from java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java rename to core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java diff --git a/java-collections-maps/src/main/java/com/baeldung/map/MyKey.java b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyKey.java similarity index 100% rename from java-collections-maps/src/main/java/com/baeldung/map/MyKey.java rename to core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyKey.java diff --git a/java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java similarity index 100% rename from java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java rename to core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java diff --git a/core-kotlin/src/main/resources/logback.xml b/core-java-modules/core-java-collections-maps/src/main/resources/logback.xml similarity index 100% rename from core-kotlin/src/main/resources/logback.xml rename to core-java-modules/core-java-collections-maps/src/main/resources/logback.xml diff --git a/java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java diff --git a/core-java-modules/core-java-collections-set/README.md b/core-java-modules/core-java-collections-set/README.md index 2b34ef3449..b97cd3216f 100644 --- a/core-java-modules/core-java-collections-set/README.md +++ b/core-java-modules/core-java-collections-set/README.md @@ -11,3 +11,4 @@ This module contains articles about the Java Set collection - [Guide to EnumSet](https://www.baeldung.com/java-enumset) - [Set Operations in Java](https://www.baeldung.com/java-set-operations) - [Copying Sets in Java](https://www.baeldung.com/java-copy-sets) +- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index d21bbeef77..c89ba0c091 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-collections-set 0.1.0-SNAPSHOT @@ -32,7 +34,23 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + 11 + 11 4.3 2.8.5 diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java similarity index 97% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java rename to core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java index 7dbcd2a3a3..2af040b13e 100644 --- a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java +++ b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java @@ -1,4 +1,4 @@ -package com.baeldung.java9.set; +package com.baeldung.set; import com.google.common.collect.ImmutableSet; diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java b/core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java similarity index 97% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java rename to core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java index 28e71affcc..d89927dfd6 100644 --- a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java +++ b/core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java @@ -1,9 +1,10 @@ -package com.baeldung.java9; +package com.baeldung.set; + +import org.junit.Test; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import org.junit.Test; import static org.junit.Assert.assertEquals; diff --git a/core-java-modules/core-java-collections/README.md b/core-java-modules/core-java-collections/README.md index 340c2b286e..12e3c5ac17 100644 --- a/core-java-modules/core-java-collections/README.md +++ b/core-java-modules/core-java-collections/README.md @@ -3,7 +3,6 @@ This module contains articles about Java collections ### Relevant Articles: -- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection) - [Introduction to the Java ArrayDeque](https://www.baeldung.com/java-array-deque) - [An Introduction to Java.util.Hashtable Class](https://www.baeldung.com/java-hash-table) - [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe) @@ -13,4 +12,4 @@ This module contains articles about Java collections - [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack) - [Guide to the Java Queue Interface](https://www.baeldung.com/java-queue) - [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections) -- [[More -->]](/core-java-modules/core-java-collections-2) \ No newline at end of file +- [[More -->]](/core-java-modules/core-java-collections-2) diff --git a/core-java-modules/core-java-collections/pom.xml b/core-java-modules/core-java-collections/pom.xml index c9cbe94a4f..515d19d7fb 100644 --- a/core-java-modules/core-java-collections/pom.xml +++ b/core-java-modules/core-java-collections/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-collections 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-concurrency-2/README.md b/core-java-modules/core-java-concurrency-2/README.md index 749d174968..23471a237e 100644 --- a/core-java-modules/core-java-concurrency-2/README.md +++ b/core-java-modules/core-java-concurrency-2/README.md @@ -4,4 +4,5 @@ ### Relevant Articles: - [Using a Mutex Object in Java](https://www.baeldung.com/java-mutex) +- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded) diff --git a/core-java-modules/core-java-concurrency-2/pom.xml b/core-java-modules/core-java-concurrency-2/pom.xml index 690fe97ae6..dfb5674c8e 100644 --- a/core-java-modules/core-java-concurrency-2/pom.xml +++ b/core-java-modules/core-java-concurrency-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-concurrency-2 0.1.0-SNAPSHOT @@ -13,6 +15,38 @@ 0.0.1-SNAPSHOT ../../parent-java + + + + junit + junit + 4.13 + test + + + com.googlecode.thread-weaver + threadweaver + 0.2 + test + + + com.google.code.tempus-fugit + tempus-fugit + 1.1 + test + + + com.googlecode.multithreadedtc + multithreadedtc + 1.01 + test + + + org.openjdk.jcstress + jcstress-core + 0.5 + + core-java-concurrency-2 @@ -22,6 +56,51 @@ true + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${javac.target} + ${javac.target} + ${javac.target} + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + main + package + + shade + + + jcstress + + + org.openjdk.jcstress.Main + + + META-INF/TestList + + + + + + + + + + 1.8 + diff --git a/core-java-modules/core-java-concurrency-2/src/main/java/com/baeldung/concurrent/MyCounter.java b/core-java-modules/core-java-concurrency-2/src/main/java/com/baeldung/concurrent/MyCounter.java new file mode 100644 index 0000000000..a678b047a8 --- /dev/null +++ b/core-java-modules/core-java-concurrency-2/src/main/java/com/baeldung/concurrent/MyCounter.java @@ -0,0 +1,22 @@ +package com.baeldung.concurrent; + +public class MyCounter { + + private int count; + + public void increment() { + int temp = count; + count = temp + 1; + } + + public synchronized void incrementWithWait() throws InterruptedException { + int temp = count; + wait(100); + count = temp + 1; + } + + public int getCount() { + return count; + } + +} diff --git a/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java new file mode 100644 index 0000000000..6c76505347 --- /dev/null +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.concurrent; + +import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE; +import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE_INTERESTING; + +import org.openjdk.jcstress.annotations.Actor; +import org.openjdk.jcstress.annotations.Arbiter; +import org.openjdk.jcstress.annotations.JCStressTest; +import org.openjdk.jcstress.annotations.Outcome; +import org.openjdk.jcstress.annotations.State; +import org.openjdk.jcstress.infra.results.I_Result; + +@JCStressTest +@Outcome(id = "1", expect = ACCEPTABLE_INTERESTING, desc = "One update lost.") +@Outcome(id = "2", expect = ACCEPTABLE, desc = "Both updates.") +@State +public class MyCounterJCStressUnitTest { + + private MyCounter counter; + + @Actor + public void actor1() { + counter.increment(); + } + + @Actor + public void actor2() { + counter.increment(); + } + + @Arbiter + public void arbiter(I_Result r) { + r.r1 = counter.getCount(); + } + +} diff --git a/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java new file mode 100644 index 0000000000..8a0bedf6c2 --- /dev/null +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.concurrent; + +import org.junit.Ignore; +import org.junit.Test; + +import edu.umd.cs.mtc.MultithreadedTestCase; +import edu.umd.cs.mtc.TestFramework; + +public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase { + + private MyCounter counter; + + @Override + public void initialize() { + counter = new MyCounter(); + } + + public void thread1() throws InterruptedException { + counter.increment(); + } + + public void thread2() throws InterruptedException { + counter.increment(); + } + + @SuppressWarnings("deprecation") + @Override + public void finish() { + assertEquals(2, counter.getCount()); + } + + @Ignore + @Test + public void testCounter() throws Throwable { + TestFramework.runManyTimes(new MyCounterMultithreadedTCUnitTest(), 1000); + } +} diff --git a/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java new file mode 100644 index 0000000000..9a405e7e24 --- /dev/null +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.Ignore; +import org.junit.Test; + +public class MyCounterSimpleUnitTest { + + @Test + public void testCounter() { + MyCounter counter = new MyCounter(); + for (int i = 0; i < 500; i++) + counter.increment(); + assertEquals(500, counter.getCount()); + } + + @Ignore + @Test + public void testCounterWithConcurrency() throws InterruptedException { + int numberOfThreads = 100; + ExecutorService service = Executors.newFixedThreadPool(10); + CountDownLatch latch = new CountDownLatch(numberOfThreads); + MyCounter counter = new MyCounter(); + for (int i = 0; i < numberOfThreads; i++) { + service.execute(() -> { + counter.increment(); + latch.countDown(); + }); + } + latch.await(); + assertEquals(numberOfThreads, counter.getCount()); + } + + @Ignore + @Test + public void testSummationWithConcurrencyAndWait() throws InterruptedException { + int numberOfThreads = 2; + ExecutorService service = Executors.newFixedThreadPool(10); + CountDownLatch latch = new CountDownLatch(numberOfThreads); + MyCounter counter = new MyCounter(); + for (int i = 0; i < numberOfThreads; i++) { + service.submit(() -> { + try { + counter.incrementWithWait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + latch.countDown(); + }); + } + latch.await(); + assertEquals(numberOfThreads, counter.getCount()); + } + +} diff --git a/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java new file mode 100644 index 0000000000..36a2031e78 --- /dev/null +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; + +import com.google.code.tempusfugit.concurrency.ConcurrentRule; +import com.google.code.tempusfugit.concurrency.RepeatingRule; +import com.google.code.tempusfugit.concurrency.annotations.Concurrent; +import com.google.code.tempusfugit.concurrency.annotations.Repeating; + +public class MyCounterTempusFugitUnitTest { + + @Rule + public ConcurrentRule concurrently = new ConcurrentRule(); + @Rule + public RepeatingRule rule = new RepeatingRule(); + + private static MyCounter counter = new MyCounter(); + + @Ignore + @Test + @Concurrent(count = 2) + @Repeating(repetition = 10) + public void runsMultipleTimes() { + counter.increment(); + } + + @AfterClass + public static void annotatedTestRunsMultipleTimes() throws InterruptedException { + assertEquals(counter.getCount(), 20); + } + +} diff --git a/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java new file mode 100644 index 0000000000..e65a963584 --- /dev/null +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import org.junit.Ignore; +import org.junit.Test; + +import com.google.testing.threadtester.AnnotatedTestRunner; +import com.google.testing.threadtester.ThreadedAfter; +import com.google.testing.threadtester.ThreadedBefore; +import com.google.testing.threadtester.ThreadedMain; +import com.google.testing.threadtester.ThreadedSecondary; + +public class MyCounterThreadWeaverUnitTest { + + private MyCounter counter; + + @ThreadedBefore + public void before() { + counter = new MyCounter(); + } + + @ThreadedMain + public void mainThread() { + counter.increment(); + } + + @ThreadedSecondary + public void secondThread() { + counter.increment(); + } + + @ThreadedAfter + public void after() { + assertEquals(2, counter.getCount()); + } + + @Ignore + @Test + public void testCounter() { + new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced-2/pom.xml b/core-java-modules/core-java-concurrency-advanced-2/pom.xml index 7e76219c4e..8752e7b7db 100644 --- a/core-java-modules/core-java-concurrency-advanced-2/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-concurrency-advanced-2 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java b/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java index e9c8056ff5..a04994d558 100644 --- a/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java +++ b/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java @@ -1,22 +1,27 @@ package com.baeldung.threadlocalrandom; import org.openjdk.jmh.runner.Runner; -import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.ChainedOptionsBuilder; import org.openjdk.jmh.runner.options.OptionsBuilder; +import com.google.common.collect.ImmutableList; + public class ThreadLocalRandomBenchMarkRunner { public static void main(String[] args) throws Exception { - Options options = new OptionsBuilder().include(ThreadLocalRandomBenchMarker.class.getSimpleName()) - .threads(1) + ChainedOptionsBuilder options = new OptionsBuilder().include(ThreadLocalRandomBenchMarker.class.getSimpleName()) .forks(1) .shouldFailOnError(true) .shouldDoGC(true) - .jvmArgs("-server") - .build(); - - new Runner(options).run(); + .jvmArgs("-server"); + for (Integer i : ImmutableList.of(1, 2, 8, 32)) { + new Runner( + options + .threads(i) + .build()) + .run(); + } } } diff --git a/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java b/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java index 8a0e2d2826..b0852bc40d 100644 --- a/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java +++ b/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java @@ -1,64 +1,34 @@ package com.baeldung.threadlocalrandom; -import java.util.ArrayList; -import java.util.List; import java.util.Random; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Level; 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.annotations.Warmup; -@BenchmarkMode(Mode.AverageTime) +@BenchmarkMode(Mode.Throughput) @Warmup(iterations = 1) @OutputTimeUnit(TimeUnit.MICROSECONDS) @State(Scope.Benchmark) public class ThreadLocalRandomBenchMarker { + private final Random random = new Random(); - List> randomCallables = new ArrayList<>(); - List> threadLocalRandomCallables = new ArrayList<>(); - - @Setup(Level.Iteration) - public void init() { - Random random = new Random(); - randomCallables = new ArrayList<>(); - threadLocalRandomCallables = new ArrayList<>(); - for (int i = 0; i < 1000; i++) { - randomCallables.add(() -> { - return random.nextInt(); - }); - } - - for (int i = 0; i < 1000; i++) { - threadLocalRandomCallables.add(() -> { - return ThreadLocalRandom.current() - .nextInt(); - }); - } + @Benchmark + public int randomValuesUsingRandom() { + return random.nextInt(); } @Benchmark - public void randomValuesUsingRandom() throws InterruptedException { - ExecutorService executor = Executors.newWorkStealingPool(); - executor.invokeAll(randomCallables); - executor.shutdown(); - } - - @Benchmark - public void randomValuesUsingThreadLocalRandom() throws InterruptedException { - ExecutorService executor = Executors.newWorkStealingPool(); - executor.invokeAll(threadLocalRandomCallables); - executor.shutdown(); + public int randomValuesUsingThreadLocalRandom() { + return ThreadLocalRandom + .current() + .nextInt(); } } diff --git a/core-java-modules/core-java-concurrency-advanced-3/README.md b/core-java-modules/core-java-concurrency-advanced-3/README.md index 409d3aa464..b11cde5158 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/README.md +++ b/core-java-modules/core-java-concurrency-advanced-3/README.md @@ -8,4 +8,7 @@ This module contains articles about advanced topics about multithreading with co - [Common Concurrency Pitfalls in Java](https://www.baeldung.com/java-common-concurrency-pitfalls) - [Guide to RejectedExecutionHandler](https://www.baeldung.com/java-rejectedexecutionhandler) -[[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2) +- [Guide to Work Stealing in Java](https://www.baeldung.com/java-work-stealing) +- [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming) +- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock) +- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2) diff --git a/core-java-modules/core-java-concurrency-advanced-3/pom.xml b/core-java-modules/core-java-concurrency-advanced-3/pom.xml index df9834181f..cf81214125 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 core-java-concurrency-advanced-3 @@ -23,6 +24,37 @@ ${assertj.version} test + + + com.jcabi + jcabi-aspects + ${jcabi-aspects.version} + + + + org.aspectj + aspectjrt + ${aspectjrt.version} + runtime + + + + com.google.guava + guava + ${guava.version} + + + + org.cactoos + cactoos + ${cactoos.version} + + + + com.ea.async + ea-async + ${ea-async.version} + @@ -36,6 +68,30 @@ ${maven.compiler.target} + + com.jcabi + jcabi-maven-plugin + ${jcabi-maven-plugin.version} + + + + ajc + + + + + + org.aspectj + aspectjtools + ${aspectjtools.version} + + + org.aspectj + aspectjweaver + ${aspectjweaver.version} + + + @@ -49,6 +105,14 @@ 3.14.0 1.8 1.8 + 0.22.6 + 1.9.5 + 28.2-jre + 0.43 + 1.2.3 + 0.14.1 + 1.9.1 + 1.9.1 diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/EAAsyncExample.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/EAAsyncExample.java new file mode 100644 index 0000000000..c7c893e731 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/EAAsyncExample.java @@ -0,0 +1,57 @@ +package com.baeldung.async; + +import static com.ea.async.Async.await; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import com.ea.async.Async; + +public class EAAsyncExample { + + static { + Async.init(); + } + + public static void main(String[] args) throws Exception { + usingCompletableFuture(); + usingAsyncAwait(); + } + + public static void usingCompletableFuture() throws InterruptedException, ExecutionException, Exception { + CompletableFuture completableFuture = hello() + .thenComposeAsync(hello -> mergeWorld(hello)) + .thenAcceptAsync(helloWorld -> print(helloWorld)) + .exceptionally( throwable -> { + System.out.println(throwable.getCause()); + return null; + }); + completableFuture.get(); + } + + public static CompletableFuture hello() { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + return completableFuture; + } + + public static CompletableFuture mergeWorld(String s) { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { + return s + " World!"; + }); + return completableFuture; + } + + public static void print(String str) { + CompletableFuture.runAsync(() -> System.out.println(str)); + } + + private static void usingAsyncAwait() { + try { + String hello = await(hello()); + String helloWorld = await(mergeWorld(hello)); + await(CompletableFuture.runAsync(() -> print(helloWorld))); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/JavaAsync.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/JavaAsync.java new file mode 100644 index 0000000000..6f36f46154 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/JavaAsync.java @@ -0,0 +1,183 @@ +package com.baeldung.async; + +import static com.ea.async.Async.await; + +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import com.google.common.util.concurrent.AsyncCallable; +import com.google.common.util.concurrent.Callables; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import com.jcabi.aspects.Async; +import com.jcabi.aspects.Loggable; + +public class JavaAsync { + + static { + com.ea.async.Async.init(); + } + + private static final ExecutorService threadpool = Executors.newCachedThreadPool(); + + public static void main (String[] args) throws InterruptedException, ExecutionException { + int number = 20; + + //Thread Example + factorialUsingThread(number).start(); + + //FutureTask Example + Future futureTask = factorialUsingFutureTask(number); + System.out.println("Factorial of " + number + " is: " + futureTask.get()); + + // CompletableFuture Example + Future completableFuture = factorialUsingCompletableFuture(number); + System.out.println("Factorial of " + number + " is: " + completableFuture.get()); + + // EA Async example + System.out.println("Factorial of " + number + " is: " + factorialUsingEAAsync(number)); + + // cactoos async example + Future asyncFuture = factorialUsingCactoos(number); + System.out.println("Factorial of " + number + " is: " + asyncFuture.get()); + + // Guava example + ListenableFuture guavaFuture = factorialUsingGuavaServiceSubmit(number); + System.out.println("Factorial of " + number + " is: " + guavaFuture.get()); + + ListenableFuture guavaFutures = factorialUsingGuavaFutures(number); + System.out.println("Factorial of " + number + " is: " + guavaFutures.get()); + + // @async jcabi-aspect example + Future aspectFuture = factorialUsingJcabiAspect(number); + System.out.println("Factorial of " + number + " is: " + aspectFuture.get()); + + } + + /** + * Finds factorial of a number + * @param number + * @return + */ + public static long factorial(int number) { + long result = 1; + for(int i=number;i>0;i--) { + result *= i; + } + return result; + } + + /** + * Finds factorial of a number using Thread + * @param number + * @return + */ + @Loggable + public static Thread factorialUsingThread(int number) { + Thread newThread = new Thread(() -> { + System.out.println("Factorial of " + number + " is: " + factorial(number)); + }); + + return newThread; + } + + /** + * Finds factorial of a number using FutureTask + * @param number + * @return + */ + @Loggable + public static Future factorialUsingFutureTask(int number) { + Future futureTask = threadpool.submit(() -> factorial(number)); + + while (!futureTask.isDone()) { + System.out.println("FutureTask is not finished yet..."); + } + + return futureTask; + } + + /** + * Finds factorial of a number using CompletableFuture + * @param number + * @return + */ + @Loggable + public static Future factorialUsingCompletableFuture(int number) { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> factorial(number)); + return completableFuture; + } + + /** + * Finds factorial of a number using EA Async + * @param number + * @return + */ + @Loggable + public static long factorialUsingEAAsync(int number) { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> factorial(number)); + long result = await(completableFuture); + return result; + } + + /** + * Finds factorial of a number using Async of Cactoos + * @param number + * @return + * @throws InterruptedException + * @throws ExecutionException + */ + @Loggable + public static Future factorialUsingCactoos(int number) throws InterruptedException, ExecutionException { + org.cactoos.func.Async asyncFunction = new org.cactoos.func.Async(input -> factorial(input)); + Future asyncFuture = asyncFunction.apply(number); + return asyncFuture; + } + + /** + * Finds factorial of a number using Guava's ListeningExecutorService.submit() + * @param number + * @return + */ + @Loggable + public static ListenableFuture factorialUsingGuavaServiceSubmit(int number) { + ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool); + ListenableFuture factorialFuture = (ListenableFuture) service.submit(()-> factorial(number)); + return factorialFuture; + } + + /** + * Finds factorial of a number using Guava's Futures.submitAsync() + * @param number + * @return + */ + @Loggable + public static ListenableFuture factorialUsingGuavaFutures(int number) { + ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool); + AsyncCallable asyncCallable = Callables.asAsyncCallable(new Callable() { + public Long call() { + return factorial(number); + } + }, service); + return Futures.submitAsync(asyncCallable, service); + } + + /** + * Finds factorial of a number using @Async of jcabi-aspects + * @param number + * @return + */ + @Async + @Loggable + public static Future factorialUsingJcabiAspect(int number) { + Future factorialFuture = CompletableFuture.supplyAsync(() -> factorial(number)); + return factorialFuture; + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java new file mode 100644 index 0000000000..1a46e1ba52 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java @@ -0,0 +1,34 @@ +package com.baeldung.atomicstampedreference; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicStampedReference; + +public class StampedAccount { + + private AtomicInteger stamp = new AtomicInteger(0); + private AtomicStampedReference account = new AtomicStampedReference<>(0, 0); + + public int getBalance() { + return this.account.get(new int[1]); + } + + public int getStamp() { + int[] stamps = new int[1]; + this.account.get(stamps); + return stamps[0]; + } + + public boolean deposit(int funds) { + int[] stamps = new int[1]; + int current = this.account.get(stamps); + int newStamp = this.stamp.incrementAndGet(); + return this.account.compareAndSet(current, current + funds, stamps[0], newStamp); + } + + public boolean withdrawal(int funds) { + int[] stamps = new int[1]; + int current = this.account.get(stamps); + int newStamp = this.stamp.incrementAndGet(); + return this.account.compareAndSet(current, current - funds, stamps[0], newStamp); + } +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/deadlockAndLivelock/DeadlockExample.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/deadlockAndLivelock/DeadlockExample.java new file mode 100644 index 0000000000..bcdaf302ea --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/deadlockAndLivelock/DeadlockExample.java @@ -0,0 +1,60 @@ +package com.baeldung.deadlockAndLivelock; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +public class DeadlockExample { + + private Lock lock1 = new ReentrantLock(true); + private Lock lock2 = new ReentrantLock(true); + + public static void main(String[] args) { + DeadlockExample deadlock = new DeadlockExample(); + new Thread(deadlock::operation1, "T1").start(); + new Thread(deadlock::operation2, "T2").start(); + + } + + public void operation1() { + lock1.lock(); + print("lock1 acquired, waiting to acquire lock2."); + sleep(50); + + lock2.lock(); + print("lock2 acquired"); + + print("executing first operation."); + + lock2.unlock(); + lock1.unlock(); + + } + + public void operation2() { + lock2.lock(); + print("lock2 acquired, waiting to acquire lock1."); + sleep(50); + + lock1.lock(); + print("lock1 acquired"); + + print("executing second operation."); + + lock1.unlock(); + lock2.unlock(); + } + + public void print(String message) { + System.out.println("Thread " + Thread.currentThread() + .getName() + ": " + message); + } + + public void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/deadlockAndLivelock/LivelockExample.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/deadlockAndLivelock/LivelockExample.java new file mode 100644 index 0000000000..b0d66a92c2 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/deadlockAndLivelock/LivelockExample.java @@ -0,0 +1,86 @@ +package com.baeldung.deadlockAndLivelock; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +public class LivelockExample { + + private Lock lock1 = new ReentrantLock(true); + private Lock lock2 = new ReentrantLock(true); + + public static void main(String[] args) { + LivelockExample livelock = new LivelockExample(); + new Thread(livelock::operation1, "T1").start(); + new Thread(livelock::operation2, "T2").start(); + + } + + public void operation1() { + while (true) { + tryLock(lock1, 50); + print("lock1 acquired, trying to acquire lock2."); + sleep(50); + + if (tryLock(lock2)) { + print("lock2 acquired."); + } else { + print("cannot acquire lock2, releasing lock1."); + lock1.unlock(); + continue; + } + + print("executing first operation."); + break; + } + lock2.unlock(); + lock1.unlock(); + } + + public void operation2() { + while (true) { + tryLock(lock2, 50); + print("lock2 acquired, trying to acquire lock1."); + sleep(50); + + if (tryLock(lock1)) { + print("lock1 acquired."); + } else { + print("cannot acquire lock1, releasing lock2."); + lock2.unlock(); + continue; + } + + print("executing second operation."); + break; + } + lock1.unlock(); + lock2.unlock(); + } + + public void print(String message) { + System.out.println("Thread " + Thread.currentThread() + .getName() + ": " + message); + } + + public void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public void tryLock(Lock lock, long millis) { + try { + lock.tryLock(10, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public boolean tryLock(Lock lock) { + return lock.tryLock(); + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/lockfree/NonBlockingQueue.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/lockfree/NonBlockingQueue.java new file mode 100644 index 0000000000..9140dc287d --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/lockfree/NonBlockingQueue.java @@ -0,0 +1,81 @@ +package com.baeldung.lockfree; + +import java.util.NoSuchElementException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +public class NonBlockingQueue { + + private final AtomicReference> head, tail; + private final AtomicInteger size; + + public NonBlockingQueue() { + head = new AtomicReference<>(null); + tail = new AtomicReference<>(null); + size = new AtomicInteger(); + size.set(0); + } + + public void add(T element) { + if (element == null) { + throw new NullPointerException(); + } + + Node node = new Node<>(element); + Node currentTail; + do { + currentTail = tail.get(); + node.setPrevious(currentTail); + } while(!tail.compareAndSet(currentTail, node)); + + if(node.previous != null) { + node.previous.next = node; + } + + head.compareAndSet(null, node); //if we are inserting the first element + size.incrementAndGet(); + } + + public T get() { + if(head.get() == null) { + throw new NoSuchElementException(); + } + + Node currentHead; + Node nextNode; + do { + currentHead = head.get(); + nextNode = currentHead.getNext(); + } while(!head.compareAndSet(currentHead, nextNode)); + + size.decrementAndGet(); + return currentHead.getValue(); + } + + public int size() { + return this.size.get(); + } + + private class Node { + private final T value; + private volatile Node next; + private volatile Node previous; + + public Node(T value) { + this.value = value; + this.next = null; + } + + public T getValue() { + return value; + } + + public Node getNext() { + return next; + } + + public void setPrevious(Node previous) { + this.previous = previous; + } + } +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/workstealing/PrimeNumbers.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/workstealing/PrimeNumbers.java new file mode 100644 index 0000000000..b31ec85cd4 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/workstealing/PrimeNumbers.java @@ -0,0 +1,85 @@ +package com.baeldung.workstealing; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.RecursiveAction; +import java.util.concurrent.atomic.AtomicInteger; + +public class PrimeNumbers extends RecursiveAction { + + private int lowerBound; + private int upperBound; + private int granularity; + static final List GRANULARITIES + = Arrays.asList(1, 10, 100, 1000, 10000); + private AtomicInteger noOfPrimeNumbers; + + PrimeNumbers(int lowerBound, int upperBound, int granularity, AtomicInteger noOfPrimeNumbers) { + this.lowerBound = lowerBound; + this.upperBound = upperBound; + this.granularity = granularity; + this.noOfPrimeNumbers = noOfPrimeNumbers; + } + + PrimeNumbers(int upperBound) { + this(1, upperBound, 100, new AtomicInteger(0)); + } + + private PrimeNumbers(int lowerBound, int upperBound, AtomicInteger noOfPrimeNumbers) { + this(lowerBound, upperBound, 100, noOfPrimeNumbers); + } + + private List subTasks() { + List subTasks = new ArrayList<>(); + + for (int i = 1; i <= this.upperBound / granularity; i++) { + int upper = i * granularity; + int lower = (upper - granularity) + 1; + subTasks.add(new PrimeNumbers(lower, upper, noOfPrimeNumbers)); + } + return subTasks; + } + + @Override + protected void compute() { + if (((upperBound + 1) - lowerBound) > granularity) { + ForkJoinTask.invokeAll(subTasks()); + } else { + findPrimeNumbers(); + } + } + + void findPrimeNumbers() { + for (int num = lowerBound; num <= upperBound; num++) { + if (isPrime(num)) { + noOfPrimeNumbers.getAndIncrement(); + } + } + } + + private boolean isPrime(int number) { + if (number == 2) { + return true; + } + + if (number == 1 || number % 2 == 0) { + return false; + } + + int noOfNaturalNumbers = 0; + + for (int i = 1; i <= number; i++) { + if (number % i == 0) { + noOfNaturalNumbers++; + } + } + + return noOfNaturalNumbers == 2; + } + + public int noOfPrimeNumbers() { + return noOfPrimeNumbers.intValue(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java new file mode 100644 index 0000000000..ce83355073 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.atomicstampedreference; + +import org.junit.Assert; +import org.junit.Test; + +public class ThreadStampedAccountUnitTest { + + @Test + public void givenMultiThread_whenStampedAccount_thenSetBalance() throws InterruptedException { + StampedAccount account = new StampedAccount(); + Thread t = new Thread(() -> { + while (!account.withdrawal(100)) + Thread.yield(); + }); + t.start(); + Assert.assertTrue(account.deposit(100)); + t.join(1_000); + Assert.assertFalse(t.isAlive()); + Assert.assertSame(0, account.getBalance()); + } +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java index 5016cc1d06..1301fe2778 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.rejection; import org.junit.After; +import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; @@ -28,24 +29,26 @@ public class SaturationPolicyUnitTest { } } + @Ignore @Test public void givenAbortPolicy_WhenSaturated_ThenShouldThrowRejectedExecutionException() { executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new AbortPolicy()); - executor.execute(() -> waitFor(100)); + executor.execute(() -> waitFor(250)); assertThatThrownBy(() -> executor.execute(() -> System.out.println("Will be rejected"))).isInstanceOf(RejectedExecutionException.class); } + @Ignore @Test public void givenCallerRunsPolicy_WhenSaturated_ThenTheCallerThreadRunsTheTask() { executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new CallerRunsPolicy()); - executor.execute(() -> waitFor(100)); + executor.execute(() -> waitFor(250)); - long startTime = System.nanoTime(); - executor.execute(() -> waitFor(100)); - double blockedDuration = (System.nanoTime() - startTime) / 1_000_000.0; + long startTime = System.currentTimeMillis(); + executor.execute(() -> waitFor(500)); + long blockedDuration = System.currentTimeMillis() - startTime; - assertThat(blockedDuration).isGreaterThanOrEqualTo(100); + assertThat(blockedDuration).isGreaterThanOrEqualTo(500); } @Test diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersUnitManualTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersUnitManualTest.java new file mode 100644 index 0000000000..4fbbef4e61 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersUnitManualTest.java @@ -0,0 +1,101 @@ +package com.baeldung.workstealing; + +import org.junit.Test; +import org.openjdk.jmh.annotations.*; +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.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.Logger; + +import static org.junit.Assert.fail; + +public class PrimeNumbersUnitManualTest { + + private static Logger logger = Logger.getAnonymousLogger(); + + @Test + public void givenPrimesCalculated_whenUsingPoolsAndOneThread_thenOneThreadSlowest() { + Options opt = new OptionsBuilder() + .include(Benchmarker.class.getSimpleName()) + .forks(1) + .build(); + + try { + new Runner(opt).run(); + } catch (RunnerException e) { + fail(); + } + } + + @Test + public void givenNewWorkStealingPool_whenGettingPrimes_thenStealCountChanges() { + StringBuilder info = new StringBuilder(); + + for (int granularity : PrimeNumbers.GRANULARITIES) { + int parallelism = ForkJoinPool.getCommonPoolParallelism(); + ForkJoinPool pool = + (ForkJoinPool) Executors.newWorkStealingPool(parallelism); + + stealCountInfo(info, granularity, pool); + } + logger.info("\nExecutors.newWorkStealingPool ->" + info.toString()); + } + + @Test + public void givenCommonPool_whenGettingPrimes_thenStealCountChangesSlowly() { + StringBuilder info = new StringBuilder(); + + for (int granularity : PrimeNumbers.GRANULARITIES) { + ForkJoinPool pool = ForkJoinPool.commonPool(); + stealCountInfo(info, granularity, pool); + } + logger.info("\nForkJoinPool.commonPool ->" + info.toString()); + } + + private void stealCountInfo(StringBuilder info, int granularity, ForkJoinPool forkJoinPool) { + PrimeNumbers primes = new PrimeNumbers(1, 10000, granularity, new AtomicInteger(0)); + forkJoinPool.invoke(primes); + forkJoinPool.shutdown(); + + long steals = forkJoinPool.getStealCount(); + String output = "\nGranularity: [" + granularity + "], Steals: [" + steals + "]"; + info.append(output); + } + + + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + @State(Scope.Benchmark) + @Fork(value = 2, warmups = 1, jvmArgs = {"-Xms2G", "-Xmx2G"}) + public static class Benchmarker { + + @Benchmark + public void singleThread() { + PrimeNumbers primes = new PrimeNumbers(10000); + primes.findPrimeNumbers(); // get prime numbers using a single thread + } + + @Benchmark + public void commonPoolBenchmark() { + PrimeNumbers primes = new PrimeNumbers(10000); + ForkJoinPool pool = ForkJoinPool.commonPool(); + pool.invoke(primes); + pool.shutdown(); + } + + @Benchmark + public void newWorkStealingPoolBenchmark() { + PrimeNumbers primes = new PrimeNumbers(10000); + int parallelism = ForkJoinPool.getCommonPoolParallelism(); + ForkJoinPool stealer = (ForkJoinPool) Executors.newWorkStealingPool(parallelism); + stealer.invoke(primes); + stealer.shutdown(); + } + } +} diff --git a/core-java-modules/core-java-concurrency-advanced/pom.xml b/core-java-modules/core-java-concurrency-advanced/pom.xml index 65ca811737..d39712468f 100644 --- a/core-java-modules/core-java-concurrency-advanced/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-concurrency-advanced 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java index 063c835481..78b54713b5 100644 --- a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java +++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java @@ -4,7 +4,7 @@ package com.baeldung.concurrent.volatilekeyword; public class SharedObject { private volatile int count=0; - void increamentCount(){ + void incrementCount(){ count++; } public int getCount(){ diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/TaskRunner.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/TaskRunner.java new file mode 100644 index 0000000000..f0493d4911 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/TaskRunner.java @@ -0,0 +1,25 @@ +package com.baeldung.concurrent.volatilekeyword; + +public class TaskRunner { + + private static int number; + private volatile static boolean ready; + + private static class Reader extends Thread { + + @Override + public void run() { + while (!ready) { + Thread.yield(); + } + + System.out.println(number); + } + } + + public static void main(String[] args) { + new Reader().start(); + number = 42; + ready = true; + } +} diff --git a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java index 731ae887e1..45517cefd7 100644 --- a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java +++ b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java @@ -10,7 +10,7 @@ public class SharedObjectManualTest { public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { SharedObject sharedObject = new SharedObject(); - Thread writer = new Thread(() -> sharedObject.increamentCount()); + Thread writer = new Thread(() -> sharedObject.incrementCount()); writer.start(); Thread.sleep(100); @@ -31,11 +31,11 @@ public class SharedObjectManualTest { @Test public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { SharedObject sharedObject = new SharedObject(); - Thread writerOne = new Thread(() -> sharedObject.increamentCount()); + Thread writerOne = new Thread(() -> sharedObject.incrementCount()); writerOne.start(); Thread.sleep(100); - Thread writerTwo = new Thread(() -> sharedObject.increamentCount()); + Thread writerTwo = new Thread(() -> sharedObject.incrementCount()); writerTwo.start(); Thread.sleep(100); diff --git a/core-java-modules/core-java-concurrency-basic-2/README.md b/core-java-modules/core-java-concurrency-basic-2/README.md index e3f7a94e14..c7143baf36 100644 --- a/core-java-modules/core-java-concurrency-basic-2/README.md +++ b/core-java-modules/core-java-concurrency-basic-2/README.md @@ -8,4 +8,5 @@ This module contains articles about basic Java concurrency - [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep) - [Guide to the Synchronized Keyword in Java](https://www.baeldung.com/java-synchronized) - [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle) -- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic) \ No newline at end of file +- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference) +- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic) diff --git a/core-java-modules/core-java-concurrency-basic-2/pom.xml b/core-java-modules/core-java-concurrency-basic-2/pom.xml index 0fee2c04ff..8c9bbef54c 100644 --- a/core-java-modules/core-java-concurrency-basic-2/pom.xml +++ b/core-java-modules/core-java-concurrency-basic-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-concurrency-basic-2 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/atomic/AtomicMarkableReferenceUnitTest.java b/core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/atomic/AtomicMarkableReferenceUnitTest.java new file mode 100644 index 0000000000..5f526344be --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/atomic/AtomicMarkableReferenceUnitTest.java @@ -0,0 +1,189 @@ +package com.baeldung.concurrent.atomic; + +import java.util.concurrent.atomic.AtomicMarkableReference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class AtomicMarkableReferenceUnitTest { + + class Employee { + private int id; + private String name; + + Employee(int id, String name) { + 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; + } + } + + @Test + void givenMarkValueAsTrue_whenUsingIsMarkedMethod_thenMarkValueShouldBeTrue() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenMarkValueAsFalse_whenUsingIsMarkedMethod_thenMarkValueShouldBeFalse() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, false); + + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void whenUsingGetReferenceMethod_thenCurrentReferenceShouldBeReturned() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Assertions.assertEquals(employee, employeeNode.getReference()); + } + + @Test + void whenUsingGetMethod_thenCurrentReferenceAndMarkShouldBeReturned() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + boolean[] markHolder = new boolean[1]; + Employee currentEmployee = employeeNode.get(markHolder); + + Assertions.assertEquals(employee, currentEmployee); + Assertions.assertTrue(markHolder[0]); + } + + @Test + void givenNewReferenceAndMark_whenUsingSetMethod_thenCurrentReferenceAndMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Employee newEmployee = new Employee(124, "John"); + employeeNode.set(newEmployee, false); + + Assertions.assertEquals(newEmployee, employeeNode.getReference()); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenTheSameObjectReference_whenUsingAttemptMarkMethod_thenMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Assertions.assertTrue(employeeNode.attemptMark(employee, false)); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenDifferentObjectReference_whenUsingAttemptMarkMethod_thenMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee expectedEmployee = new Employee(123, "Mike"); + + Assertions.assertFalse(employeeNode.attemptMark(expectedEmployee, false)); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertTrue(employeeNode.compareAndSet(employee, newEmployee, true, false)); + Assertions.assertEquals(newEmployee, employeeNode.getReference()); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.compareAndSet(new Employee(1234, "Steve"), newEmployee, true, false)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndNotCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.compareAndSet(employee, newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndNotCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.compareAndSet(new Employee(1234, "Steve"), newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertTrue(employeeNode.weakCompareAndSet(employee, newEmployee, true, false)); + Assertions.assertEquals(newEmployee, employeeNode.getReference()); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.weakCompareAndSet(new Employee(1234, "Steve"), newEmployee, true, false)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndNotCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.weakCompareAndSet(employee, newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndNotCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.weakCompareAndSet(new Employee(1234, "Steve"), newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } +} diff --git a/core-java-modules/core-java-concurrency-basic/pom.xml b/core-java-modules/core-java-concurrency-basic/pom.xml index 9d9d2cb663..c15200da1f 100644 --- a/core-java-modules/core-java-concurrency-basic/pom.xml +++ b/core-java-modules/core-java-concurrency-basic/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-concurrency-basic 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java index 5fcb28cd2a..ebd027ea68 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java @@ -9,7 +9,7 @@ import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCount import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable; import com.baeldung.concurrent.threadsafety.services.AtomicCounter; import com.baeldung.concurrent.threadsafety.services.Counter; -import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import com.baeldung.concurrent.threadsafety.services.ObjectLockCounter; import com.baeldung.concurrent.threadsafety.services.MessageService; import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter; import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter; @@ -48,9 +48,9 @@ public class Application { System.out.println(future3.get()); System.out.println(future4.get()); - ExtrinsicLockCounter extrinsicLockCounter = new ExtrinsicLockCounter(); - Future future5 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter)); - Future future6 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter)); + ObjectLockCounter objectLockCounter = new ObjectLockCounter(); + Future future5 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(objectLockCounter)); + Future future6 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(objectLockCounter)); System.out.println(future5.get()); System.out.println(future6.get()); diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java index 370e5d1f00..dcc929d3c4 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java @@ -1,13 +1,13 @@ package com.baeldung.concurrent.threadsafety.callables; -import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import com.baeldung.concurrent.threadsafety.services.ObjectLockCounter; import java.util.concurrent.Callable; public class ExtrinsicLockCounterCallable implements Callable { - private final ExtrinsicLockCounter counter; + private final ObjectLockCounter counter; - public ExtrinsicLockCounterCallable(ExtrinsicLockCounter counter) { + public ExtrinsicLockCounterCallable(ObjectLockCounter counter) { this.counter = counter; } diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java deleted file mode 100644 index 0a6ff3f60e..0000000000 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.concurrent.threadsafety.services; - -public class ExtrinsicLockCounter { - - private int counter; - private final Object lock = new Object(); - - public ExtrinsicLockCounter() { - this.counter = 0; - } - - public void incrementCounter() { - synchronized (lock) { - counter += 1; - } - } - - public int getCounter() { - synchronized (lock) { - return counter; - } - } -} diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ObjectLockCounter.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ObjectLockCounter.java new file mode 100644 index 0000000000..f31cf899ba --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ObjectLockCounter.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadsafety.services; + +public class ObjectLockCounter { + + private int counter; + private final Object lock = new Object(); + + public ObjectLockCounter() { + this.counter = 0; + } + + public void incrementCounter() { + synchronized (lock) { + counter += 1; + } + } + + public int getCounter() { + synchronized (lock) { + return counter; + } + } +} diff --git a/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ExtrinsicLockCounterUnitTest.java b/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ExtrinsicLockCounterUnitTest.java deleted file mode 100644 index 0fc3dd3a54..0000000000 --- a/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ExtrinsicLockCounterUnitTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.concurrent.threadsafety; - -import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable; -import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; -import org.junit.Test; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ExtrinsicLockCounterUnitTest { - - @Test - public void whenCalledIncrementCounter_thenCorrect() throws Exception { - ExecutorService executorService = Executors.newFixedThreadPool(2); - ExtrinsicLockCounter counter = new ExtrinsicLockCounter(); - Future future1 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); - Future future2 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); - - // Just to make sure both are completed - future1.get(); - future2.get(); - - assertThat(counter.getCounter()).isEqualTo(2); - } -} diff --git a/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ObjectLockCounterUnitTest.java b/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ObjectLockCounterUnitTest.java new file mode 100644 index 0000000000..b0ac80a3aa --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ObjectLockCounterUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.concurrent.threadsafety; + +import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable; +import com.baeldung.concurrent.threadsafety.services.ObjectLockCounter; +import org.junit.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ObjectLockCounterUnitTest { + + @Test + public void whenCalledIncrementCounter_thenCorrect() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + ObjectLockCounter counter = new ObjectLockCounter(); + Future future1 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); + Future future2 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); + + // Just to make sure both are completed + future1.get(); + future2.get(); + + assertThat(counter.getCounter()).isEqualTo(2); + } +} diff --git a/core-java-modules/core-java-concurrency-collections-2/README.md b/core-java-modules/core-java-concurrency-collections-2/README.md new file mode 100644 index 0000000000..91da6c623c --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Lock Striping](https://www.baeldung.com/java-lock-stripping) diff --git a/core-java-modules/core-java-concurrency-collections-2/pom.xml b/core-java-modules/core-java-concurrency-collections-2/pom.xml new file mode 100644 index 0000000000..65a91c9a9c --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + com.baeldung.concurrent.lock + core-java-concurrency-collections-2 + 0.0.1-SNAPSHOT + + + + com.google.guava + guava + ${guava.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + + src + + + maven-compiler-plugin + 3.8.0 + + 1.8 + 1.8 + + + + + + + 1.21 + 28.2-jre + + + \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessBenchmark.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessBenchmark.java new file mode 100644 index 0000000000..ceb53ce077 --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessBenchmark.java @@ -0,0 +1,54 @@ +package com.baeldung.concurrent.lock; + +import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.Map; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +@State(Scope.Thread) +@Fork(value = 2) +@Warmup(iterations = 0) +public class ConcurrentAccessBenchmark { + static final int SLOTS = 4; + static final int THREADS = 10000; + static final int BUCKETS = Runtime.getRuntime().availableProcessors() * SLOTS; + SingleLock singleLock = new SingleLock(); + StripedLock stripedLock = new StripedLock(BUCKETS); + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map singleLockHashMap() throws InterruptedException { + return singleLock.doWork(new HashMap(), THREADS, SLOTS); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map stripedLockHashMap() throws InterruptedException { + return stripedLock.doWork(new HashMap(), THREADS, SLOTS); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map singleLockConcurrentHashMap() throws InterruptedException { + return singleLock.doWork(new ConcurrentHashMap(), THREADS, SLOTS); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map stripedLockConcurrentHashMap() throws InterruptedException { + return stripedLock.doWork(new ConcurrentHashMap(), THREADS, SLOTS); + } +} diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessExperiment.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessExperiment.java new file mode 100644 index 0000000000..ec6d3895da --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessExperiment.java @@ -0,0 +1,26 @@ +package com.baeldung.concurrent.lock; + +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +import com.google.common.base.Supplier; + +public abstract class ConcurrentAccessExperiment { + + public final Map doWork(Map map, int threads, int slots) { + CompletableFuture[] requests = new CompletableFuture[threads * slots]; + + for (int i = 0; i < threads; i++) { + requests[slots * i + 0] = CompletableFuture.supplyAsync(putSupplier(map, i)); + requests[slots * i + 1] = CompletableFuture.supplyAsync(getSupplier(map, i)); + requests[slots * i + 2] = CompletableFuture.supplyAsync(getSupplier(map, i)); + requests[slots * i + 3] = CompletableFuture.supplyAsync(getSupplier(map, i)); + } + CompletableFuture.allOf(requests).join(); + + return map; + } + + protected abstract Supplier putSupplier(Map map, int key); + protected abstract Supplier getSupplier(Map map, int key); +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/SingleLock.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/SingleLock.java new file mode 100644 index 0000000000..4dff459df6 --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/SingleLock.java @@ -0,0 +1,36 @@ +package com.baeldung.concurrent.lock; + +import java.util.Map; +import java.util.concurrent.locks.ReentrantLock; + +import com.google.common.base.Supplier; + +public class SingleLock extends ConcurrentAccessExperiment { + ReentrantLock lock; + + public SingleLock() { + lock = new ReentrantLock(); + } + + protected Supplier putSupplier(Map map, int key) { + return (()-> { + lock.lock(); + try { + return map.put("key" + key, "value" + key); + } finally { + lock.unlock(); + } + }); + } + + protected Supplier getSupplier(Map map, int key) { + return (()-> { + lock.lock(); + try { + return map.get("key" + key); + } finally { + lock.unlock(); + } + }); + } +} diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/StripedLock.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/StripedLock.java new file mode 100644 index 0000000000..47c47d8813 --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/StripedLock.java @@ -0,0 +1,41 @@ +package com.baeldung.concurrent.lock; + +import java.util.Map; +import java.util.concurrent.locks.Lock; + +import com.google.common.base.Supplier; +import com.google.common.util.concurrent.Striped; + +public class StripedLock extends ConcurrentAccessExperiment { + Striped stripedLock; + + public StripedLock(int buckets) { + stripedLock = Striped.lock(buckets); + } + + protected Supplier putSupplier(Map map, int key) { + return (()-> { + int bucket = key % stripedLock.size(); + Lock lock = stripedLock.get(bucket); + lock.lock(); + try { + return map.put("key" + key, "value" + key); + } finally { + lock.unlock(); + } + }); + } + + protected Supplier getSupplier(Map map, int key) { + return (()-> { + int bucket = key % stripedLock.size(); + Lock lock = stripedLock.get(bucket); + lock.lock(); + try { + return map.get("key" + key); + } finally { + lock.unlock(); + } + }); + } +} diff --git a/core-java-modules/core-java-concurrency-collections/pom.xml b/core-java-modules/core-java-concurrency-collections/pom.xml index f731b1acd1..5c038639a7 100644 --- a/core-java-modules/core-java-concurrency-collections/pom.xml +++ b/core-java-modules/core-java-concurrency-collections/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-concurrency-collections 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-concurrency-collections/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java b/core-java-modules/core-java-concurrency-collections/src/test/java/com/baeldung/java/stream/ThreadPoolInParallelStreamIntegrationTest.java similarity index 97% rename from core-java-modules/core-java-concurrency-collections/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java rename to core-java-modules/core-java-concurrency-collections/src/test/java/com/baeldung/java/stream/ThreadPoolInParallelStreamIntegrationTest.java index 502672dea1..7ee849b0a2 100644 --- a/core-java-modules/core-java-concurrency-collections/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java +++ b/core-java-modules/core-java-concurrency-collections/src/test/java/com/baeldung/java/stream/ThreadPoolInParallelStreamIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.streams; +package com.baeldung.java.stream; import org.junit.Test; diff --git a/core-java-modules/core-java-date-operations-1/README.md b/core-java-modules/core-java-date-operations-1/README.md new file mode 100644 index 0000000000..b63fab63db --- /dev/null +++ b/core-java-modules/core-java-date-operations-1/README.md @@ -0,0 +1,15 @@ +## Core Date Operations (Part 1) +This module contains articles about date operations in Java. + +### Relevant Articles: +- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) +- [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) +- [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) +- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) +- [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) +- [Introduction to Joda-Time](http://www.baeldung.com/joda-time) +- [[Next -->]](/core-java-modules/core-java-date-operations-2) \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations-1/pom.xml b/core-java-modules/core-java-date-operations-1/pom.xml new file mode 100644 index 0000000000..54cbc79678 --- /dev/null +++ b/core-java-modules/core-java-date-operations-1/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + core-java-date-operations-1 + ${project.parent.version} + core-java-date-operations-1 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + joda-time + joda-time + ${joda-time.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.darwinsys + hirondelle-date4j + RELEASE + test + + + + + core-java-date-operations-1 + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 2.10 + + 3.6.1 + 1.9 + 1.9 + + + diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/AgeCalculator.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/date/AgeCalculator.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/AgeCalculator.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/date/AgeCalculator.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/DateWithoutTime.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/date/DateWithoutTime.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/DateWithoutTime.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/date/DateWithoutTime.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/AddHoursToDate.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/AddHoursToDate.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/AddHoursToDate.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/AddHoursToDate.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/java9/time/TimeApi.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/java9/time/TimeApi.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/java9/time/TimeApi.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/java9/time/TimeApi.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/DateDiffUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateDiffUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/DateDiffUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java diff --git a/core-java-modules/core-java-date-operations-2/README.md b/core-java-modules/core-java-date-operations-2/README.md new file mode 100644 index 0000000000..19c7b98d30 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/README.md @@ -0,0 +1,11 @@ +## Core Date Operations (Part 2) +This module contains articles about date operations in Java. + +### Relevant Articles: +- [Get the Current Date Prior to Java 8](https://www.baeldung.com/java-get-the-current-date-legacy) +- [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends) +- [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day) +- [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime) +- [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone) +- [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week) +- [[<-- Prev]](/core-java-modules/core-java-date-operations-1) diff --git a/core-java-modules/core-java-date-operations-2/pom.xml b/core-java-modules/core-java-date-operations-2/pom.xml new file mode 100644 index 0000000000..ea5f852b0d --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + core-java-date-operations-2 + ${project.parent.version} + core-java-date-operations-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + joda-time + joda-time + ${joda-time.version} + + + com.darwinsys + hirondelle-date4j + ${hirondelle-date4j.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 2.10 + 1.5.1 + 3.14.0 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java similarity index 85% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java index ae8d21c29c..ab48934f1a 100644 --- a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java +++ b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java @@ -1,55 +1,65 @@ -package com.baeldung.date.comparison; - -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.Calendar; -import java.util.Date; -import java.util.TimeZone; - -import org.apache.commons.lang3.time.DateUtils; - -import hirondelle.date4j.DateTime; - -public class DateComparisonUtils { - - public static boolean isSameDayUsingLocalDate(Date date1, Date date2) { - LocalDate localDate1 = date1.toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDate(); - LocalDate localDate2 = date2.toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDate(); - return localDate1.isEqual(localDate2); - } - - public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) { - SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd"); - return fmt.format(date1) - .equals(fmt.format(date2)); - } - - public static boolean isSameDayUsingCalendar(Date date1, Date date2) { - Calendar calendar1 = Calendar.getInstance(); - calendar1.setTime(date1); - Calendar calendar2 = Calendar.getInstance(); - calendar2.setTime(date2); - return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH); - } - - public static boolean isSameDayUsingApacheCommons(Date date1, Date date2) { - return DateUtils.isSameDay(date1, date2); - } - - public static boolean isSameDayUsingJoda(Date date1, Date date2) { - org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1); - org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2); - return localDate1.equals(localDate2); - } - - public static boolean isSameDayUsingDate4j(Date date1, Date date2) { - DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault()); - DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault()); - return dateObject1.isSameDayAs(dateObject2); - } -} +package com.baeldung.date.comparison; + +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.temporal.ChronoUnit; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import org.apache.commons.lang3.time.DateUtils; + +import hirondelle.date4j.DateTime; + +public class DateComparisonUtils { + + public static boolean isSameDayUsingLocalDate(Date date1, Date date2) { + LocalDate localDate1 = date1.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + LocalDate localDate2 = date2.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + return localDate1.isEqual(localDate2); + } + + public static boolean isSameDayUsingInstant(Date date1, Date date2) { + Instant instant1 = date1.toInstant() + .truncatedTo(ChronoUnit.DAYS); + Instant instant2 = date2.toInstant() + .truncatedTo(ChronoUnit.DAYS); + return instant1.equals(instant2); + } + + public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) { + SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd"); + return fmt.format(date1) + .equals(fmt.format(date2)); + } + + public static boolean isSameDayUsingCalendar(Date date1, Date date2) { + Calendar calendar1 = Calendar.getInstance(); + calendar1.setTime(date1); + Calendar calendar2 = Calendar.getInstance(); + calendar2.setTime(date2); + return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH); + } + + public static boolean isSameDayUsingApacheCommons(Date date1, Date date2) { + return DateUtils.isSameDay(date1, date2); + } + + public static boolean isSameDayUsingJoda(Date date1, Date date2) { + org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1); + org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2); + return localDate1.equals(localDate2); + } + + public static boolean isSameDayUsingDate4j(Date date1, Date date2) { + DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault()); + DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault()); + return dateObject1.isSameDayAs(dateObject2); + } +} diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/CalendarUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/CalendarUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/CalendarUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/CalendarUtils.java diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/DateUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/DateUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/DateUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/DateUtils.java diff --git a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractor.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractor.java new file mode 100644 index 0000000000..b027790e35 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractor.java @@ -0,0 +1,35 @@ +package com.baeldung.datetime.dayofweek; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.format.TextStyle; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +public class DayOfWeekExtractor { + + public static int getDayNumberOld(Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal.get(Calendar.DAY_OF_WEEK); + } + + public static String getDayStringOld(Date date, Locale locale ) { + DateFormat formatter = new SimpleDateFormat("EEEE", locale); + return formatter.format(date); + } + + public static int getDayNumberNew(LocalDate date) { + DayOfWeek day = date.getDayOfWeek(); + return day.getValue(); + } + + public static String getDayStringNew(LocalDate date, Locale locale ) { + DayOfWeek day = date.getDayOfWeek(); + return day.getDisplayName(TextStyle.FULL, locale); + } + +} diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/DateUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/DateUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/DateUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/DateUtils.java diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimeUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/TimeUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimeUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/TimeUtils.java diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTime.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTime.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTime.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTime.java diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtils.java diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java similarity index 90% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java index db55aadcca..477c348ea2 100644 --- a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java @@ -1,53 +1,57 @@ -package com.baeldung.date.comparison; - -import org.junit.Test; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Date; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class DateComparisonUtilsUnitTest { - - private Date day1Morning = toDate(LocalDateTime.of(2019, 10, 19, 6, 30, 40)); - private Date day1Evening = toDate(LocalDateTime.of(2019, 10, 19, 18, 30, 50)); - private Date day2Morning = toDate(LocalDateTime.of(2019, 10, 20, 6, 30, 50)); - - private Date toDate(LocalDateTime localDateTime) { - return Date.from(localDateTime.atZone(ZoneId.systemDefault()) - .toInstant()); - } - - @Test - public void givenDatesWithDifferentTime_whenIsSameDay_thenReturnsTrue() { - assertTrue(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day1Evening)); - assertTrue(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day1Evening)); - assertTrue(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day1Evening)); - assertTrue(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day1Evening)); - assertTrue(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day1Evening)); - assertTrue(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day1Evening)); - } - - @Test - public void givenDates_whenIsDifferentDay_thenReturnsFalse() { - assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Evening, day2Morning)); - - assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Evening, day2Morning)); - - assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Evening, day2Morning)); - - assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Evening, day2Morning)); - - assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Evening, day2Morning)); - - assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Evening, day2Morning)); - } -} +package com.baeldung.date.comparison; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +import org.junit.Test; + +public class DateComparisonUtilsUnitTest { + + private Date day1Morning = toDate(LocalDateTime.of(2019, 10, 19, 6, 30, 40)); + private Date day1Evening = toDate(LocalDateTime.of(2019, 10, 19, 18, 30, 50)); + private Date day2Morning = toDate(LocalDateTime.of(2019, 10, 20, 6, 30, 50)); + + private Date toDate(LocalDateTime localDateTime) { + return Date.from(localDateTime.atZone(ZoneId.systemDefault()) + .toInstant()); + } + + @Test + public void givenDatesWithDifferentTime_whenIsSameDay_thenReturnsTrue() { + assertTrue(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day1Evening)); + } + + @Test + public void givenDates_whenIsDifferentDay_thenReturnsFalse() { + assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Evening, day2Morning)); + } +} diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java diff --git a/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java new file mode 100644 index 0000000000..9bc2a17f28 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.datetime; + +import org.junit.Test; + +import java.text.ParseException; +import java.util.Date; + +import static org.junit.Assert.assertEquals; + +public class DateUtilsUnitTest { + + @Test + public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException { + long milliseconds = new Date(2020 - 1900, 0, 1).getTime(); + assertEquals(DateUtils.getDate(milliseconds), DateUtils.getDate("2020/01/01", "yyyy/MM/dd")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractorUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractorUnitTest.java new file mode 100644 index 0000000000..0dfd50dca2 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractorUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.datetime.dayofweek; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Locale; + +import org.junit.Test; + +public class DayOfWeekExtractorUnitTest { + + private DateFormat oldDateParser = new SimpleDateFormat("yyyy-MM-dd"); + + @Test + public void givenFeb29_2020_thenOldSaturdayNumber() throws ParseException { + assertThat(DayOfWeekExtractor.getDayNumberOld(oldDateParser.parse("2020-02-29")) == Calendar.SATURDAY); + } + + @Test + public void givenFeb29_2020_and_localeUS_thenOldSaturdayText() throws ParseException { + assertThat("Saturday".equals(DayOfWeekExtractor.getDayStringOld(oldDateParser.parse("2020-02-29"), Locale.US)) ); + } + + @Test + public void givenFeb29_2020_and_localeDE_thenOldSaturdayText() throws ParseException { + assertThat("Samstag".equals(DayOfWeekExtractor.getDayStringOld(oldDateParser.parse("2020-02-29"), Locale.GERMANY)) ); + } + + @Test + public void givenFeb29_2020_thenNewSaturdayNumber() throws ParseException { + assertThat(DayOfWeekExtractor.getDayNumberNew(LocalDate.parse("2020-02-29")) == Calendar.SATURDAY); + } + + @Test + public void givenFeb29_2020_and_localeUS_thenNewSaturdayText() throws ParseException { + assertThat("Saturday".equals(DayOfWeekExtractor.getDayStringOld(oldDateParser.parse("2020-02-29"), Locale.US)) ); + } + + @Test + public void givenFeb29_2020_and_localeDE_thenNewSaturdayText() throws ParseException { + assertThat("Samstag".equals(DayOfWeekExtractor.getDayStringOld(oldDateParser.parse("2020-02-29"), Locale.GERMANY)) ); + } + + +} + + + diff --git a/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java new file mode 100644 index 0000000000..9ccaa9a845 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.datetime.sql; + +import static org.junit.Assert.assertEquals; + +import java.text.ParseException; +import java.time.LocalDate; + +import org.junit.Test; + +public class DateUtilsUnitTest { + + @Test(expected = IllegalArgumentException.class) + public void givenDateAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { + DateUtils.getDate("2020 01 01"); + } + + @Test + public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException { + assertEquals(DateUtils.getDate("2020-01-01"), DateUtils.getDate("2020/01/01", "yyyy/MM/dd")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java diff --git a/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java new file mode 100644 index 0000000000..836d0d55e7 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.datetime.sql; + +import org.junit.Test; + +import java.text.ParseException; + +import static org.junit.Assert.assertEquals; + +public class TimestampUtilsUnitTest { + + @Test(expected = IllegalArgumentException.class) + public void givenTimestampAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { + TimestampUtils.getTimestamp("2020/01/01 10:11-12"); + } + + @Test + public void givenTimestampAndPattern_thenTimestampIsCorrectlyReturned() throws ParseException { + assertEquals(TimestampUtils.getTimestamp("2020-01-01 10:11:12"), TimestampUtils.getTimestamp("2020/01/01 10:11-12", "yyyy/MM/dd hh:mm-ss")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/timezone/ModifyDefaultTimezoneUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/jvmtimezone/ModifyDefaultTimezoneUnitTest.java similarity index 79% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/timezone/ModifyDefaultTimezoneUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/jvmtimezone/ModifyDefaultTimezoneUnitTest.java index 05d36d2c6c..7a266b46c3 100644 --- a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/timezone/ModifyDefaultTimezoneUnitTest.java +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/jvmtimezone/ModifyDefaultTimezoneUnitTest.java @@ -1,9 +1,8 @@ -package com.baeldung.timezone; +package com.baeldung.jvmtimezone; import org.junit.Test; import java.util.Calendar; -import java.util.Date; import java.util.TimeZone; import static org.junit.Assert.assertEquals; @@ -13,9 +12,7 @@ public class ModifyDefaultTimezoneUnitTest { @Test public void givenDefaultTimezoneSet_thenDateTimezoneIsCorrect() { TimeZone.setDefault(TimeZone.getTimeZone("Portugal")); - Date date = new Date(); Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Portugal")); } diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/timezone/ModifyTimezonePropertyUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/jvmtimezone/ModifyTimezonePropertyUnitTest.java similarity index 79% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/timezone/ModifyTimezonePropertyUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/jvmtimezone/ModifyTimezonePropertyUnitTest.java index 8f65f520f8..ec0d183e78 100644 --- a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/timezone/ModifyTimezonePropertyUnitTest.java +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/jvmtimezone/ModifyTimezonePropertyUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.timezone; +package com.baeldung.jvmtimezone; import org.junit.After; import org.junit.Before; @@ -14,7 +14,7 @@ public class ModifyTimezonePropertyUnitTest { @Before public void setup() { - System.setProperty("user.timezone", "IST"); + System.setProperty("user.timezone", "Asia/Kolkata"); TimeZone.setDefault(null); } @@ -25,10 +25,8 @@ public class ModifyTimezonePropertyUnitTest { @Test public void givenTimezonePropertySet_thenDateTimezoneIsCorrect() { - Date date = new Date(); Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("IST")); + assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Asia/Kolkata")); } } \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTimeUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTimeUnitTest.java similarity index 75% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTimeUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTimeUnitTest.java index a6fd6c03c2..fa9ceca173 100644 --- a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTimeUnitTest.java +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTimeUnitTest.java @@ -4,6 +4,7 @@ import org.junit.Test; import java.time.OffsetDateTime; import java.util.Date; +import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -18,12 +19,19 @@ public class ConvertToOffsetDateTimeUnitTest { @Test public void givenDate_whenHasOffset_thenConvertWithOffset() { + TimeZone prevTimezone = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + Date date = new Date(); date.setHours(6); date.setMinutes(30); + OffsetDateTime odt = ConvertToOffsetDateTime.convert(date, 3, 30); assertEquals(10, odt.getHour()); assertEquals(0, odt.getMinute()); + + // Reset the timezone to its original value to prevent side effects + TimeZone.setDefault(prevTimezone); } } diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtilsUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtilsUnitTest.java diff --git a/core-java-modules/core-java-date-operations/README.md b/core-java-modules/core-java-date-operations/README.md deleted file mode 100644 index 24bb493dce..0000000000 --- a/core-java-modules/core-java-date-operations/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Core Date Operations -This module contains articles about date operations in Java. - -### Relevant Articles: -- [Get the Current Date Prior to Java 8](https://www.baeldung.com/java-get-the-current-date-legacy) -- [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends) -- [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day) -- [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime) diff --git a/core-java-modules/core-java-date-operations/pom.xml b/core-java-modules/core-java-date-operations/pom.xml deleted file mode 100644 index 4d267964ee..0000000000 --- a/core-java-modules/core-java-date-operations/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - 4.0.0 - core-java-date-operations - ${project.parent.version} - core-java-date-operations - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - joda-time - joda-time - ${joda-time.version} - - - com.darwinsys - hirondelle-date4j - ${hirondelle-date4j.version} - - - - - 2.10 - 1.5.1 - - - \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java deleted file mode 100644 index 8711455265..0000000000 --- a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.datetime; - -import org.junit.Test; - -import java.text.ParseException; -import java.util.Date; - -import static org.junit.Assert.assertEquals; - -public class DateUtilsUnitTest { - - @Test - public void givenTimeMillis_thenDateIsReturned() { - Date now = DateUtils.getNow(); - assertEquals(DateUtils.getDate(now.getTime()), now); - } - - @Test - public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException { - long milliseconds = new Date(2020 - 1900, 0, 1).getTime(); - assertEquals(DateUtils.getDate(milliseconds), DateUtils.getDate("2020/01/01", "yyyy/MM/dd")); - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java deleted file mode 100644 index 945086c86f..0000000000 --- a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.datetime.sql; - -import static org.junit.Assert.assertEquals; - -import java.text.ParseException; -import java.time.LocalDate; - -import org.junit.Test; - -public class DateUtilsUnitTest { - - @Test - public void givenCurrentDate_thenTodayIsReturned() { - assertEquals(DateUtils.getNow().toLocalDate(), LocalDate.now()); - } - - @Test(expected = IllegalArgumentException.class) - public void givenDateAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { - DateUtils.getDate("2020 01 01"); - } - - @Test - public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException { - assertEquals(DateUtils.getDate("2020-01-01"), DateUtils.getDate("2020/01/01", "yyyy/MM/dd")); - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java deleted file mode 100644 index 2faf8fab0e..0000000000 --- a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.datetime.sql; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import com.baeldung.datetime.sql.TimestampUtils; - -import java.text.ParseException; -import java.util.Date; - -public class TimestampUtilsUnitTest { - - @Test - public void givenCurrentTimestamp_thenNowIsReturned() { - assertEquals(TimestampUtils.getNow() - .getTime(), new Date().getTime()); - } - - @Test(expected = IllegalArgumentException.class) - public void givenTimestampAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { - TimestampUtils.getTimestamp("2020/01/01 10:11-12"); - } - - @Test - public void givenTimestampAndPattern_thenTimestampIsCorrectlyReturned() throws ParseException { - assertEquals(TimestampUtils.getTimestamp("2020-01-01 10:11:12"), TimestampUtils.getTimestamp("2020/01/01 10:11-12", "yyyy/MM/dd hh:mm-ss")); - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-computations/README.md b/core-java-modules/core-java-datetime-computations/README.md deleted file mode 100644 index 591ddeaa94..0000000000 --- a/core-java-modules/core-java-datetime-computations/README.md +++ /dev/null @@ -1,15 +0,0 @@ -## Java Date/time computations Cookbooks and Examples - -This module contains articles about date and time computations in Java. - -### Relevant Articles: -- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) -- [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) -- [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) -- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) -- [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) -- [Introduction to Joda-Time](http://www.baeldung.com/joda-time) diff --git a/core-java-modules/core-java-datetime-computations/pom.xml b/core-java-modules/core-java-datetime-computations/pom.xml deleted file mode 100644 index af6b110296..0000000000 --- a/core-java-modules/core-java-datetime-computations/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - 4.0.0 - core-java-datetime-computations - ${project.parent.version} - core-java-datetime-computations - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - joda-time - joda-time - ${joda-time.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - org.assertj - assertj-core - ${assertj.version} - test - - - com.darwinsys - hirondelle-date4j - RELEASE - test - - - - - core-java-datetime-computations - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - - - 2.10 - - 3.6.1 - 1.9 - 1.9 - - - diff --git a/core-java-modules/core-java-datetime-conversion/pom.xml b/core-java-modules/core-java-datetime-conversion/pom.xml index e2b143aa88..e2dd579335 100644 --- a/core-java-modules/core-java-datetime-conversion/pom.xml +++ b/core-java-modules/core-java-datetime-conversion/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-datetime-conversion ${project.parent.version} diff --git a/core-java-modules/core-java-datetime-java8/README.md b/core-java-modules/core-java-datetime-java8/README.md deleted file mode 100644 index dfbe9c997f..0000000000 --- a/core-java-modules/core-java-datetime-java8/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Java 8+ Date and Time API - -This module contains articles about the Date and Time API introduced with Java 8. - -### Relevant Articles: -- [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) -- [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) -- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) -- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime) -- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) -- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) -- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone) -- [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates) -- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates) diff --git a/core-java-modules/core-java-datetime-java8/pom.xml b/core-java-modules/core-java-datetime-java8/pom.xml deleted file mode 100644 index 34323fe76c..0000000000 --- a/core-java-modules/core-java-datetime-java8/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - 4.0.0 - core-java-datetime-java8 - ${project.parent.version} - core-java-datetime-java8 - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - joda-time - joda-time - ${joda-time.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - log4j - log4j - ${log4j.version} - test - - - - - core-java-datetime-java8 - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - - - 1.9 - 1.9 - 2.10 - - 3.6.1 - - - diff --git a/core-java-modules/core-java-datetime-string/pom.xml b/core-java-modules/core-java-datetime-string/pom.xml index dd793f7fe8..ceb7641320 100644 --- a/core-java-modules/core-java-datetime-string/pom.xml +++ b/core-java-modules/core-java-datetime-string/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-datetime-string ${project.parent.version} diff --git a/core-java-modules/core-java-exceptions-2/README.md b/core-java-modules/core-java-exceptions-2/README.md index 3ad5189b5e..1b8457acc4 100644 --- a/core-java-modules/core-java-exceptions-2/README.md +++ b/core-java-modules/core-java-exceptions-2/README.md @@ -2,4 +2,10 @@ This module contains articles about core java exceptions -### +### Relevant Articles: + +- [Is It a Bad Practice to Catch Throwable?](https://www.baeldung.com/java-catch-throwable-bad-practice) +- [Wrapping vs Rethrowing Exceptions in Java](https://www.baeldung.com/java-wrapping-vs-rethrowing-exceptions) +- [java.net.UnknownHostException: Invalid Hostname for Server](https://www.baeldung.com/java-unknownhostexception) +- [How to Handle Java SocketException](https://www.baeldung.com/java-socketexception) +- [Java Suppressed Exceptions](https://www.baeldung.com/java-suppressed-exceptions) diff --git a/core-java-modules/core-java-exceptions-2/pom.xml b/core-java-modules/core-java-exceptions-2/pom.xml index 2f7f613faf..cf8de3d5b6 100644 --- a/core-java-modules/core-java-exceptions-2/pom.xml +++ b/core-java-modules/core-java-exceptions-2/pom.xml @@ -1,24 +1,37 @@ - - 4.0.0 + + 4.0.0 - core-java-exceptions-2 - core-java-exceptions-2 - jar + core-java-exceptions-2 + core-java-exceptions-2 + jar - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + - - http://maven.apache.org + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + - - UTF-8 - + + http://maven.apache.org + + + UTF-8 + + 3.10.0 + diff --git a/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/exceptions/CatchingThrowable.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/exceptions/CatchingThrowable.java new file mode 100644 index 0000000000..20b06cdd26 --- /dev/null +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/exceptions/CatchingThrowable.java @@ -0,0 +1,38 @@ +package com.baeldung.exceptions; + +import java.util.Set; +import java.util.UUID; + +public class CatchingThrowable { + + class CapacityException extends Exception { + CapacityException(String message) { + super(message); + } + } + + class StorageAPI { + + public void addIDsToStorage(int capacity, Set storage) throws CapacityException { + if (capacity < 1) { + throw new CapacityException("Capacity of less than 1 is not allowed"); + } + int count = 0; + while (count < capacity) { + storage.add(UUID.randomUUID().toString()); + count++; + } + } + + // other methods go here ... + } + + public void add(StorageAPI api, int capacity, Set storage) { + try { + api.addIDsToStorage(capacity, storage); + } catch (Throwable throwable) { + // do something here + } + } + +} diff --git a/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/exceptions/UnknownHostExceptionHandling.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/exceptions/UnknownHostExceptionHandling.java new file mode 100644 index 0000000000..0e1c36f64c --- /dev/null +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/exceptions/UnknownHostExceptionHandling.java @@ -0,0 +1,28 @@ +package com.baeldung.exceptions; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.UnknownHostException; + +public class UnknownHostExceptionHandling { + + public static int getResponseCode(String hostname) throws IOException { + URL url = new URL(hostname.trim()); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + int resCode = -1; + try { + resCode = con.getResponseCode(); + } catch (UnknownHostException e){ + con.disconnect(); + } + return resCode; + } + + public static int getResponseCodeUnhandled(String hostname) throws IOException { + URL url = new URL(hostname.trim()); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + int resCode = con.getResponseCode(); + return resCode; + } +} diff --git a/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/socketexception/SocketClient.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/socketexception/SocketClient.java new file mode 100644 index 0000000000..5c3596e890 --- /dev/null +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/socketexception/SocketClient.java @@ -0,0 +1,32 @@ +package com.baeldung.socketexception; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.Socket; + +public class SocketClient { + + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void startConnection(String ip, int port) throws IOException { + clientSocket = new Socket(ip, port); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + } + + public String sendMessage(String msg) throws IOException { + out.println(msg); + return in.readLine(); + } + + public void stopConnection() throws IOException { + in.close(); + out.close(); + clientSocket.close(); + } + +} diff --git a/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/socketexception/SocketServer.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/socketexception/SocketServer.java new file mode 100644 index 0000000000..ad6fab738f --- /dev/null +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/socketexception/SocketServer.java @@ -0,0 +1,45 @@ +package com.baeldung.socketexception; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; + +public class SocketServer { + + private ServerSocket serverSocket; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + clientSocket = serverSocket.accept(); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String msg = in.readLine(); + if (msg.contains("hi")) + out.println("hi"); + else + out.println("didn't understand"); + close(); + stop(); + } catch (IOException e) { + + } + } + + private void close() throws IOException { + in.close(); + out.close(); + } + + private void stop() throws IOException { + clientSocket.close(); + serverSocket.close(); + } + +} diff --git a/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/suppressed/ExceptionalResource.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/suppressed/ExceptionalResource.java new file mode 100644 index 0000000000..8892e097b1 --- /dev/null +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/suppressed/ExceptionalResource.java @@ -0,0 +1,13 @@ +package com.baeldung.suppressed; + +public class ExceptionalResource implements AutoCloseable { + + public void processSomething() { + throw new IllegalArgumentException("Thrown from processSomething()"); + } + + @Override + public void close() throws Exception { + throw new NullPointerException("Thrown from close()"); + } +} diff --git a/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/suppressed/SuppressedExceptionsDemo.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/suppressed/SuppressedExceptionsDemo.java new file mode 100644 index 0000000000..6ff23fd041 --- /dev/null +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/suppressed/SuppressedExceptionsDemo.java @@ -0,0 +1,44 @@ +package com.baeldung.suppressed; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +public class SuppressedExceptionsDemo { + + public static void demoSuppressedException(String filePath) throws IOException { + FileInputStream fileIn = null; + try { + fileIn = new FileInputStream(filePath); + } catch (FileNotFoundException e) { + throw new IOException(e); + } finally { + fileIn.close(); + } + } + + public static void demoAddSuppressedException(String filePath) throws IOException { + Throwable firstException = null; + FileInputStream fileIn = null; + try { + fileIn = new FileInputStream(filePath); + } catch (IOException e) { + firstException = e; + } finally { + try { + fileIn.close(); + } catch (NullPointerException npe) { + if (firstException != null) { + npe.addSuppressed(firstException); + } + throw npe; + } + } + } + + public static void demoExceptionalResource() throws Exception { + try (ExceptionalResource exceptionalResource = new ExceptionalResource()) { + exceptionalResource.processSomething(); + } + } +} diff --git a/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/exceptions/UnknownHostExceptionHandlingUnitTest.java b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/exceptions/UnknownHostExceptionHandlingUnitTest.java new file mode 100644 index 0000000000..d4b53e2dce --- /dev/null +++ b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/exceptions/UnknownHostExceptionHandlingUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.exceptions; + +import java.io.IOException; +import java.net.UnknownHostException; + +import org.junit.Test; + +public class UnknownHostExceptionHandlingUnitTest { + + @Test(expected = UnknownHostException.class) + public void givenUnknownHost_whenResolve_thenUnknownHostException() throws IOException { + UnknownHostExceptionHandling.getResponseCodeUnhandled("http://locaihost"); + } + +} diff --git a/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/socketexception/SocketExceptionHandlingUnitTest.java b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/socketexception/SocketExceptionHandlingUnitTest.java new file mode 100644 index 0000000000..08b21c6299 --- /dev/null +++ b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/socketexception/SocketExceptionHandlingUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.socketexception; + +import java.io.IOException; +import java.net.SocketException; +import java.util.concurrent.Executors; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class SocketExceptionHandlingUnitTest { + + @BeforeClass + public static void runServer() throws IOException, InterruptedException { + Executors.newSingleThreadExecutor() + .submit(() -> new SocketServer().start(6699)); + Thread.sleep(100); + } + + @Test + public void givenRunningServer_whenConnectToClosedSocket_thenHandleException() throws IOException { + SocketClient client = new SocketClient(); + client.startConnection("127.0.0.1", 6699); + try { + client.sendMessage("hi"); + client.sendMessage("hi again"); + } catch (SocketException e) { + client.stopConnection(); + } + } + +} diff --git a/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/suppressed/SuppressedExceptionsUnitTest.java b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/suppressed/SuppressedExceptionsUnitTest.java new file mode 100644 index 0000000000..7664ee6847 --- /dev/null +++ b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/suppressed/SuppressedExceptionsUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.suppressed; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.FileNotFoundException; +import java.io.IOException; + +import org.junit.Test; +import static org.hamcrest.CoreMatchers.instanceOf; + +public class SuppressedExceptionsUnitTest { + + @Test(expected = NullPointerException.class) + public void givenNonExistentFileName_whenAttemptFileOpen_thenNullPointerException() throws IOException { + SuppressedExceptionsDemo.demoSuppressedException("/non-existent-path/non-existent-file.txt"); + } + + @Test + public void givenNonExistentFileName_whenAttemptFileOpenStoreSuppressed_thenSuppressedExceptionAvailable() { + try { + SuppressedExceptionsDemo.demoAddSuppressedException("/non-existent-path/non-existent-file.txt"); + } catch (Exception e) { + assertThat(e, instanceOf(NullPointerException.class)); + assertEquals(1, e.getSuppressed().length); + assertThat(e.getSuppressed()[0], instanceOf(FileNotFoundException.class)); + } + } + + @Test + public void whenUsingExceptionalResource_thenSuppressedExceptionAvailable() { + try { + SuppressedExceptionsDemo.demoExceptionalResource(); + } catch (Exception e) { + assertThat(e, instanceOf(IllegalArgumentException.class)); + assertEquals("Thrown from processSomething()", e.getMessage()); + assertEquals(1, e.getSuppressed().length); + assertThat(e.getSuppressed()[0], instanceOf(NullPointerException.class)); + assertEquals("Thrown from close()", e.getSuppressed()[0].getMessage()); + } + } +} diff --git a/core-java-modules/core-java-exceptions/pom.xml b/core-java-modules/core-java-exceptions/pom.xml index 303a09d5b7..0778b6b5a3 100644 --- a/core-java-modules/core-java-exceptions/pom.xml +++ b/core-java-modules/core-java-exceptions/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 com.baeldung.exceptions core-java-exceptions @@ -28,6 +29,11 @@ ${lombok.version} provided + + org.apache.commons + commons-lang3 + ${commons.lang3.version} + org.assertj @@ -39,6 +45,7 @@ 1.5.0-b01 + 3.10 3.10.0 diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/Arithmetic.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/Arithmetic.java new file mode 100644 index 0000000000..db29198b39 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/Arithmetic.java @@ -0,0 +1,20 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ArrayIndexOutOfBounds.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ArrayIndexOutOfBounds.java new file mode 100644 index 0000000000..54c95f224c --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ArrayIndexOutOfBounds.java @@ -0,0 +1,24 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ClassCast.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ClassCast.java new file mode 100644 index 0000000000..8f8a6cf9e6 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ClassCast.java @@ -0,0 +1,36 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/FileNotFound.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/FileNotFound.java new file mode 100644 index 0000000000..a9f2e5ee84 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/FileNotFound.java @@ -0,0 +1,25 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandler.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandler.java new file mode 100644 index 0000000000..f2e89f44e3 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandler.java @@ -0,0 +1,28 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalArgument.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalArgument.java new file mode 100644 index 0000000000..d54757dfac --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalArgument.java @@ -0,0 +1,18 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalState.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalState.java new file mode 100644 index 0000000000..0a812d2b82 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalState.java @@ -0,0 +1,32 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/InterruptedExceptionExample.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/InterruptedExceptionExample.java new file mode 100644 index 0000000000..d0c8bb2cd0 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/InterruptedExceptionExample.java @@ -0,0 +1,28 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/MalformedURL.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/MalformedURL.java new file mode 100644 index 0000000000..9a02f005fd --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/MalformedURL.java @@ -0,0 +1,25 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NullPointer.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NullPointer.java new file mode 100644 index 0000000000..445cbecdc8 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NullPointer.java @@ -0,0 +1,36 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NumberFormat.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NumberFormat.java new file mode 100644 index 0000000000..576fe51f78 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NumberFormat.java @@ -0,0 +1,23 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ParseExceptionExample.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ParseExceptionExample.java new file mode 100644 index 0000000000..e3b3e04b10 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ParseExceptionExample.java @@ -0,0 +1,25 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/StringIndexOutOfBounds.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/StringIndexOutOfBounds.java new file mode 100644 index 0000000000..0ee132e568 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/StringIndexOutOfBounds.java @@ -0,0 +1,23 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinder.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinder.java new file mode 100644 index 0000000000..06610f3874 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinder.java @@ -0,0 +1,95 @@ +package com.baeldung.exceptions.rootcausefinder; + +import java.time.LocalDate; +import java.time.Period; +import java.time.format.DateTimeParseException; +import java.util.Objects; + +/** + * Utility class to find root cause exceptions. + */ +public class RootCauseFinder { + + public static Throwable findCauseUsingPlainJava(Throwable throwable) { + Objects.requireNonNull(throwable); + Throwable rootCause = throwable; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + return rootCause; + } + + /** + * Calculates the age of a person from a given date. + */ + static class AgeCalculator { + + private AgeCalculator() { + } + + public static int calculateAge(String birthDate) throws CalculationException { + if (birthDate == null || birthDate.isEmpty()) { + throw new IllegalArgumentException(); + } + + try { + return Period + .between(parseDate(birthDate), LocalDate.now()) + .getYears(); + } catch (DateParseException ex) { + throw new CalculationException(ex); + } + } + + private static LocalDate parseDate(String birthDateAsString) throws DateParseException { + + LocalDate birthDate; + try { + birthDate = LocalDate.parse(birthDateAsString); + } catch (DateTimeParseException ex) { + throw new InvalidFormatException(birthDateAsString, ex); + } + + if (birthDate.isAfter(LocalDate.now())) { + throw new DateOutOfRangeException(birthDateAsString); + } + + return birthDate; + } + + } + + static class CalculationException extends Exception { + + CalculationException(DateParseException ex) { + super(ex); + } + } + + static class DateParseException extends Exception { + + DateParseException(String input) { + super(input); + } + + DateParseException(String input, Throwable thr) { + super(input, thr); + } + } + + static class InvalidFormatException extends DateParseException { + + InvalidFormatException(String input, Throwable thr) { + super("Invalid date format: " + input, thr); + } + } + + static class DateOutOfRangeException extends DateParseException { + + DateOutOfRangeException(String date) { + super("Date out of range: " + date); + } + + } + +} diff --git a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandlerUnitTest.java b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandlerUnitTest.java new file mode 100644 index 0000000000..74ceb3b442 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandlerUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.exceptions.globalexceptionhandler; + +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-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinderUnitTest.java b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinderUnitTest.java new file mode 100644 index 0000000000..f42388857a --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinderUnitTest.java @@ -0,0 +1,99 @@ +package com.baeldung.exceptions.rootcausefinder; + +import com.baeldung.exceptions.rootcausefinder.RootCauseFinder.CalculationException; +import com.baeldung.exceptions.rootcausefinder.RootCauseFinder.DateOutOfRangeException; +import com.google.common.base.Throwables; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; +import java.time.format.DateTimeParseException; +import java.time.temporal.ChronoUnit; + +import static com.baeldung.exceptions.rootcausefinder.RootCauseFinder.AgeCalculator; +import static com.baeldung.exceptions.rootcausefinder.RootCauseFinder.findCauseUsingPlainJava; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests the {@link RootCauseFinder}. + */ +public class RootCauseFinderUnitTest { + + @Test + public void givenBirthDate_whenCalculatingAge_thenAgeReturned() { + try { + int age = AgeCalculator.calculateAge("1990-01-01"); + Assertions.assertEquals(1990, LocalDate + .now() + .minus(age, ChronoUnit.YEARS) + .getYear()); + } catch (CalculationException e) { + Assertions.fail(e.getMessage()); + } + } + + @Test + public void givenWrongFormatDate_whenFindingRootCauseUsingJava_thenRootCauseFound() { + try { + AgeCalculator.calculateAge("010102"); + } catch (CalculationException ex) { + assertTrue(findCauseUsingPlainJava(ex) instanceof DateTimeParseException); + } + } + + @Test + public void givenOutOfRangeDate_whenFindingRootCauseUsingJava_thenRootCauseFound() { + try { + AgeCalculator.calculateAge("2020-04-04"); + } catch (CalculationException ex) { + assertTrue(findCauseUsingPlainJava(ex) instanceof DateOutOfRangeException); + } + } + + @Test + public void givenNullDate_whenFindingRootCauseUsingJava_thenRootCauseFound() { + try { + AgeCalculator.calculateAge(null); + } catch (Exception ex) { + assertTrue(findCauseUsingPlainJava(ex) instanceof IllegalArgumentException); + } + } + + @Test + public void givenWrongFormatDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseFound() { + try { + AgeCalculator.calculateAge("010102"); + } catch (CalculationException ex) { + assertTrue(ExceptionUtils.getRootCause(ex) instanceof DateTimeParseException); + } + } + + @Test + public void givenOutOfRangeDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseFound() { + try { + AgeCalculator.calculateAge("2020-04-04"); + } catch (CalculationException ex) { + assertTrue(ExceptionUtils.getRootCause(ex) instanceof DateOutOfRangeException); + } + } + + @Test + public void givenWrongFormatDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() { + try { + AgeCalculator.calculateAge("010102"); + } catch (CalculationException ex) { + assertTrue(Throwables.getRootCause(ex) instanceof DateTimeParseException); + } + } + + @Test + public void givenOutOfRangeDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() { + try { + AgeCalculator.calculateAge("2020-04-04"); + } catch (CalculationException ex) { + assertTrue(Throwables.getRootCause(ex) instanceof DateOutOfRangeException); + } + } + +} diff --git a/core-java-modules/core-java-function/pom.xml b/core-java-modules/core-java-function/pom.xml index 0e61f73c84..1a853d5580 100644 --- a/core-java-modules/core-java-function/pom.xml +++ b/core-java-modules/core-java-function/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-function 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-io-2/README.md b/core-java-modules/core-java-io-2/README.md index 3251d2153e..84cabc5992 100644 --- a/core-java-modules/core-java-io-2/README.md +++ b/core-java-modules/core-java-io-2/README.md @@ -11,5 +11,6 @@ This module contains articles about core Java input and output (IO) - [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files) - [Java – Append Data to a File](https://www.baeldung.com/java-append-to-file) - [How to Copy a File with Java](https://www.baeldung.com/java-copy-file) -- [Create a Directory in Java](https://www.baeldung.com/java-create-directory) +- [Create a Directory in Java](https://www.baeldung.com/java-create-directory) +- [Java IO vs NIO](https://www.baeldung.com/java-io-vs-nio) - [[<-- Prev]](/core-java-modules/core-java-io) diff --git a/core-java-modules/core-java-io-2/pom.xml b/core-java-modules/core-java-io-2/pom.xml index 0c271737d9..ec27c76435 100644 --- a/core-java-modules/core-java-io-2/pom.xml +++ b/core-java-modules/core-java-io-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-io-2 0.1.0-SNAPSHOT @@ -45,6 +47,14 @@ ${assertj.version} test + + + com.github.tomakehurst + wiremock + 2.26.3 + test + + diff --git a/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/BlockingClientUnitTest.java b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/BlockingClientUnitTest.java new file mode 100644 index 0000000000..cd3d688763 --- /dev/null +++ b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/BlockingClientUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.blockingnonblocking; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import java.io.*; +import java.net.Socket; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.junit.Assert.assertTrue; + +public class BlockingClientUnitTest { + private static final String REQUESTED_RESOURCE = "/test.json"; + + @Rule public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort()); + + @Before + public void setup() { + stubFor(get(urlEqualTo(REQUESTED_RESOURCE)).willReturn(aResponse() + .withStatus(200) + .withBody("{ \"response\" : \"It worked!\" }\r\n\r\n"))); + } + + @Test + public void givenJavaIOSocket_whenReadingAndWritingWithStreams_thenSuccess() throws IOException { + // given an IO socket and somewhere to store our result + Socket socket = new Socket("localhost", wireMockRule.port()); + StringBuilder ourStore = new StringBuilder(); + + // when we write and read (using try-with-resources so our resources are auto-closed) + try (InputStream serverInput = socket.getInputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(serverInput)); + OutputStream clientOutput = socket.getOutputStream(); + PrintWriter writer = new PrintWriter(new OutputStreamWriter(clientOutput))) { + writer.print("GET " + REQUESTED_RESOURCE + " HTTP/1.0\r\n\r\n"); + writer.flush(); // important - without this the request is never sent, and the test will hang on readLine() + + for (String line; (line = reader.readLine()) != null; ) { + ourStore.append(line); + ourStore.append(System.lineSeparator()); + } + } + + // then we read and saved our data + assertTrue(ourStore + .toString() + .contains("It worked!")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/NonBlockingClientUnitTest.java b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/NonBlockingClientUnitTest.java new file mode 100644 index 0000000000..3e606476e6 --- /dev/null +++ b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/blockingnonblocking/NonBlockingClientUnitTest.java @@ -0,0 +1,94 @@ +package com.baeldung.blockingnonblocking; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.channels.SocketChannel; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.StandardCharsets; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.junit.Assert.assertTrue; + +public class NonBlockingClientUnitTest { + private String REQUESTED_RESOURCE = "/test.json"; + + @Rule public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort()); + + @Before + public void setup() { + stubFor(get(urlEqualTo(REQUESTED_RESOURCE)).willReturn(aResponse() + .withStatus(200) + .withBody("{ \"response\" : \"It worked!\" }"))); + } + + @Test + public void givenJavaNIOSocketChannel_whenReadingAndWritingWithBuffers_thenSuccess() throws IOException { + // given a NIO SocketChannel and a charset + InetSocketAddress address = new InetSocketAddress("localhost", wireMockRule.port()); + SocketChannel socketChannel = SocketChannel.open(address); + Charset charset = StandardCharsets.UTF_8; + + // when we write and read using buffers + socketChannel.write(charset.encode(CharBuffer.wrap("GET " + REQUESTED_RESOURCE + " HTTP/1.0\r\n\r\n"))); + + ByteBuffer byteBuffer = ByteBuffer.allocate(8192); // or allocateDirect if we need direct memory access + CharBuffer charBuffer = CharBuffer.allocate(8192); + CharsetDecoder charsetDecoder = charset.newDecoder(); + StringBuilder ourStore = new StringBuilder(); + while (socketChannel.read(byteBuffer) != -1 || byteBuffer.position() > 0) { + byteBuffer.flip(); + storeBufferContents(byteBuffer, charBuffer, charsetDecoder, ourStore); + byteBuffer.compact(); + } + socketChannel.close(); + + // then we read and saved our data + assertTrue(ourStore + .toString() + .contains("It worked!")); + } + + @Test + public void givenJavaNIOSocketChannel_whenReadingAndWritingWithSmallBuffers_thenSuccess() throws IOException { + // given a NIO SocketChannel and a charset + InetSocketAddress address = new InetSocketAddress("localhost", wireMockRule.port()); + SocketChannel socketChannel = SocketChannel.open(address); + Charset charset = StandardCharsets.UTF_8; + + // when we write and read using buffers that are too small for our message + socketChannel.write(charset.encode(CharBuffer.wrap("GET " + REQUESTED_RESOURCE + " HTTP/1.0\r\n\r\n"))); + + ByteBuffer byteBuffer = ByteBuffer.allocate(8); // or allocateDirect if we need direct memory access + CharBuffer charBuffer = CharBuffer.allocate(8); + CharsetDecoder charsetDecoder = charset.newDecoder(); + StringBuilder ourStore = new StringBuilder(); + while (socketChannel.read(byteBuffer) != -1 || byteBuffer.position() > 0) { + byteBuffer.flip(); + storeBufferContents(byteBuffer, charBuffer, charsetDecoder, ourStore); + byteBuffer.compact(); + } + socketChannel.close(); + + // then we read and saved our data + assertTrue(ourStore + .toString() + .contains("It worked!")); + } + + void storeBufferContents(ByteBuffer byteBuffer, CharBuffer charBuffer, CharsetDecoder charsetDecoder, StringBuilder ourStore) { + charsetDecoder.decode(byteBuffer, charBuffer, true); + charBuffer.flip(); + ourStore.append(charBuffer); + charBuffer.clear(); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-apis/pom.xml b/core-java-modules/core-java-io-apis/pom.xml index 6eb869c537..9628027309 100644 --- a/core-java-modules/core-java-io-apis/pom.xml +++ b/core-java-modules/core-java-io-apis/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-io-apis 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java b/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java index a4317af372..1883f40681 100644 --- a/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java +++ b/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.file; +import org.junit.Ignore; import org.junit.Test; import java.io.*; @@ -73,6 +74,7 @@ public class FileClassUnitTest { assertFalse(writable); } + @Ignore @Test public void givenWriteOnlyFile_whenCreateNewFile_thenCantReadFile() { File parentDir = makeDir("writeDir"); diff --git a/core-java-modules/core-java-io-conversions-2/README.md b/core-java-modules/core-java-io-conversions-2/README.md new file mode 100644 index 0000000000..4a28bf37c5 --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/README.md @@ -0,0 +1,9 @@ +## Core Java IO Conversions (Part 2) + +This module contains articles about core Java input/output(IO) conversions. + +### Relevant Articles: +- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string) +- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes) +- [Java – Write an InputStream to a File](https://www.baeldung.com/convert-input-stream-to-a-file) +- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions) diff --git a/core-java-modules/core-java-io-conversions-2/pom.xml b/core-java-modules/core-java-io-conversions-2/pom.xml new file mode 100644 index 0000000000..e95d1f4b67 --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + core-java-io-conversions-2 + 0.1.0-SNAPSHOT + core-java-io-conversions-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + core-java-io-conversions + + + src/main/resources + true + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java rename to core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java diff --git a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java rename to core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java diff --git a/core-java-modules/core-java-io-conversions/src/test/resources/targetFile.tmp b/core-java-modules/core-java-io-conversions-2/src/test/resources/sample.txt similarity index 100% rename from core-java-modules/core-java-io-conversions/src/test/resources/targetFile.tmp rename to core-java-modules/core-java-io-conversions-2/src/test/resources/sample.txt diff --git a/core-java-modules/core-java-io-conversions-2/src/test/resources/targetFile.tmp b/core-java-modules/core-java-io-conversions-2/src/test/resources/targetFile.tmp new file mode 100644 index 0000000000..5e1c309dae --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/src/test/resources/targetFile.tmp @@ -0,0 +1 @@ +Hello World \ No newline at end of file diff --git a/core-java-modules/core-java-io-conversions/README.md b/core-java-modules/core-java-io-conversions/README.md index cdb7df04d0..1f12c87241 100644 --- a/core-java-modules/core-java-io-conversions/README.md +++ b/core-java-modules/core-java-io-conversions/README.md @@ -3,10 +3,8 @@ This module contains articles about core Java input/output(IO) conversions. ### Relevant Articles: -- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string) - [Java – Convert File to InputStream](https://www.baeldung.com/convert-file-to-input-stream) - [Java – Byte Array to Writer](https://www.baeldung.com/java-convert-byte-array-to-writer) -- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes) - [Java – String to Reader](https://www.baeldung.com/java-convert-string-to-reader) - [Java – Byte Array to Reader](https://www.baeldung.com/java-convert-byte-array-to-reader) - [Java – File to Reader](https://www.baeldung.com/java-convert-file-to-reader) @@ -15,3 +13,4 @@ This module contains articles about core Java input/output(IO) conversions. - [Java – Write a Reader to File](https://www.baeldung.com/java-write-reader-to-file) - [Java – Reader to Byte Array](https://www.baeldung.com/java-convert-reader-to-byte-array) - [Java – Reader to InputStream](https://www.baeldung.com/java-convert-reader-to-inputstream) +- More articles: [[next -->]](/core-java-modules/core-java-io-conversions-2) diff --git a/core-java-modules/core-java-io-conversions/pom.xml b/core-java-modules/core-java-io-conversions/pom.xml index c3a1b2fe2d..f5ccaa45a3 100644 --- a/core-java-modules/core-java-io-conversions/pom.xml +++ b/core-java-modules/core-java-io-conversions/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-io-conversions 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-io/README.md b/core-java-modules/core-java-io/README.md index 5c4978722f..2c6c3363cb 100644 --- a/core-java-modules/core-java-io/README.md +++ b/core-java-modules/core-java-io/README.md @@ -13,4 +13,5 @@ This module contains articles about core Java input and output (IO) - [Getting a File’s Mime Type in Java](https://www.baeldung.com/java-file-mime-type) - [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv) - [How to Avoid the Java FileNotFoundException When Loading Resources](https://www.baeldung.com/java-classpath-resource-cannot-be-opened) +- [Create a Directory in Java](https://www.baeldung.com/java-create-directory) - [[More -->]](/core-java-modules/core-java-io-2) diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index 1c568a610d..103a809f90 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-io 0.1.0-SNAPSHOT @@ -73,7 +75,7 @@ -Xmx300m -XX:+UseParallelGC -classpath - + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed @@ -127,7 +129,7 @@ java -classpath - + org.openjdk.jmh.Main .* diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/readfile/FileOperationsManualTest.java b/core-java-modules/core-java-io/src/test/java/com/baeldung/readfile/FileOperationsManualTest.java deleted file mode 100644 index b837c6b4dd..0000000000 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/readfile/FileOperationsManualTest.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.baeldung.readfile; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.hamcrest.CoreMatchers; -import org.hamcrest.Matchers; -import org.junit.Test; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -public class FileOperationsManualTest { - - @Test - public void givenFileName_whenUsingClassloader_thenFileData() throws IOException { - String expectedData = "Hello World from fileTest.txt!!!"; - - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("fileTest.txt").getFile()); - InputStream inputStream = new FileInputStream(file); - String data = readFromInputStream(inputStream); - - assertEquals(expectedData, data.trim()); - } - - @Test - public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException { - String expectedData = "Hello World from fileTest.txt!!!"; - - Class clazz = FileOperationsManualTest.class; - InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt"); - String data = readFromInputStream(inputStream); - - assertEquals(expectedData, data.trim()); - } - - @Test - public void givenFileName_whenUsingJarFile_thenFileData() throws IOException { - String expectedData = "MIT License"; - - Class clazz = Matchers.class; - InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt"); - String data = readFromInputStream(inputStream); - - assertThat(data.trim(), CoreMatchers.containsString(expectedData)); - } - - @Test - public void givenURLName_whenUsingURL_thenFileData() throws IOException { - String expectedData = "Example Domain"; - - URL urlObject = new URL("http://www.example.com/"); - - URLConnection urlConnection = urlObject.openConnection(); - - InputStream inputStream = urlConnection.getInputStream(); - String data = readFromInputStream(inputStream); - - assertThat(data.trim(), CoreMatchers.containsString(expectedData)); - } - - @Test - public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException { - String expectedData = "Hello World from fileTest.txt!!!"; - - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("fileTest.txt").getFile()); - String data = FileUtils.readFileToString(file, "UTF-8"); - - assertEquals(expectedData, data.trim()); - } - - @Test - public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException { - String expectedData = "Hello World from fileTest.txt!!!"; - - Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); - - byte[] fileBytes = Files.readAllBytes(path); - String data = new String(fileBytes); - - assertEquals(expectedData, data.trim()); - } - - @Test - public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException { - String expectedData = "Hello World from fileTest.txt!!!"; - - Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); - - Stream lines = Files.lines(path); - String data = lines.collect(Collectors.joining("\n")); - lines.close(); - - assertEquals(expectedData, data.trim()); - } - - private String readFromInputStream(InputStream inputStream) throws IOException { - StringBuilder resultStringBuilder = new StringBuilder(); - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - resultStringBuilder.append(line).append("\n"); - } - } - - return resultStringBuilder.toString(); - } - - @Test - public void givenFileName_whenUsingIOUtils_thenFileData() throws IOException { - String expectedData = "This is a content of the file"; - - FileInputStream fis = new FileInputStream("src/test/resources/fileToRead.txt"); - String data = IOUtils.toString(fis, "UTF-8"); - - assertEquals(expectedData, data.trim()); - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/readfile/JavaReadFromFileUnitTest.java b/core-java-modules/core-java-io/src/test/java/com/baeldung/readfile/JavaReadFromFileUnitTest.java index a4ccaad594..aa37a22e1f 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/readfile/JavaReadFromFileUnitTest.java +++ b/core-java-modules/core-java-io/src/test/java/com/baeldung/readfile/JavaReadFromFileUnitTest.java @@ -1,11 +1,15 @@ package com.baeldung.readfile; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matchers; import org.junit.Test; -import org.junit.Ignore; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.*; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; @@ -13,55 +17,148 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Scanner; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class JavaReadFromFileUnitTest { - private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class); - @Test public void whenReadWithBufferedReader_thenCorrect() throws IOException { - final String expected_value = "Hello world"; + final String expected_value = "Hello, world!"; - final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read.in")); + final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/fileTest.txt")); final String currentLine = reader.readLine(); reader.close(); assertEquals(expected_value, currentLine); } + @Test + public void givenFileName_whenUsingClassloader_thenFileData() throws IOException { + String expectedData = "Hello, world!"; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("fileTest.txt").getFile()); + InputStream inputStream = new FileInputStream(file); + String data = readFromInputStream(inputStream); + + assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException { + String expectedData = "Hello, world!"; + + Class clazz = JavaReadFromFileUnitTest.class; + InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt"); + String data = readFromInputStream(inputStream); + + assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFileName_whenUsingJarFile_thenFileData() throws IOException { + String expectedData = "BSD License"; + + Class clazz = Matchers.class; + InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt"); + String data = readFromInputStream(inputStream); + + assertThat(data.trim(), CoreMatchers.containsString(expectedData)); + } + + @Test + public void givenURLName_whenUsingURL_thenFileData() throws IOException { + String expectedData = "Example Domain"; + + URL urlObject = new URL("http://www.example.com/"); + + URLConnection urlConnection = urlObject.openConnection(); + + InputStream inputStream = urlConnection.getInputStream(); + String data = readFromInputStream(inputStream); + + assertThat(data.trim(), CoreMatchers.containsString(expectedData)); + } + + @Test + public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException { + String expectedData = "Hello, world!"; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("fileTest.txt").getFile()); + String data = FileUtils.readFileToString(file, "UTF-8"); + + assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException { + String expectedData = "Hello, world!"; + + Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); + + byte[] fileBytes = Files.readAllBytes(path); + String data = new String(fileBytes); + + assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException { + String expectedData = "Hello, world!"; + + Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); + + Stream lines = Files.lines(path); + String data = lines.collect(Collectors.joining("\n")); + lines.close(); + + assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFileName_whenUsingIOUtils_thenFileData() throws IOException { + String expectedData = "Hello, world!"; + + FileInputStream fis = new FileInputStream("src/test/resources/fileTest.txt"); + String data = IOUtils.toString(fis, "UTF-8"); + + assertEquals(expectedData, data.trim()); + } + @Test public void whenReadWithScanner_thenCorrect() throws IOException { - final Scanner scanner = new Scanner(new File("src/test/resources/test_read1.in")); + final Scanner scanner = new Scanner(new File("src/test/resources/fileTest.txt")); scanner.useDelimiter(" "); assertTrue(scanner.hasNext()); - assertEquals("Hello", scanner.next()); - assertEquals("world", scanner.next()); - assertEquals(1, scanner.nextInt()); + assertEquals("Hello,", scanner.next()); + assertEquals("world!", scanner.next()); scanner.close(); - } @Test public void whenReadWithScannerTwoDelimiters_thenCorrect() throws IOException { - final Scanner scanner = new Scanner(new File("src/test/resources/test_read2.in")); - scanner.useDelimiter(",| "); + final Scanner scanner = new Scanner(new File("src/test/resources/fileTest.txt")); + scanner.useDelimiter("\\s|,"); - assertTrue(scanner.hasNextInt()); - assertEquals(2, scanner.nextInt()); - assertEquals(3, scanner.nextInt()); - assertEquals(4, scanner.nextInt()); + assertTrue(scanner.hasNext()); + assertEquals("Hello", scanner.next()); + assertEquals("", scanner.next()); + assertEquals("world!", scanner.next()); scanner.close(); } @Test public void whenReadWithStreamTokenizer_thenCorrectTokens() throws IOException { - final FileReader reader = new FileReader("src/test/resources/test_read3.in"); + final FileReader reader = new FileReader("src/test/resources/fileTestTokenizer.txt"); final StreamTokenizer tokenizer = new StreamTokenizer(reader); tokenizer.nextToken(); @@ -78,49 +175,36 @@ public class JavaReadFromFileUnitTest { @Test public void whenReadWithDataInputStream_thenCorrect() throws IOException { - final String expected_value = "Hello"; + String expectedValue = "Hello, world!"; + String file ="src/test/resources/fileTest.txt"; - String result; - final DataInputStream reader = new DataInputStream(new FileInputStream("src/test/resources/test_read4.in")); - result = reader.readUTF(); - reader.close(); + String result = null; - assertEquals(expected_value, result); - } + DataInputStream reader = new DataInputStream(new FileInputStream(file)); + int nBytesToRead = reader.available(); + if(nBytesToRead > 0) { + byte[] bytes = new byte[nBytesToRead]; + reader.read(bytes); + result = new String(bytes); + } - public void whenReadTwoFilesWithSequenceInputStream_thenCorrect() throws IOException { - final int expected_value1 = 2000; - final int expected_value2 = 5000; - - final FileInputStream stream1 = new FileInputStream("src/test/resources/test_read5.in"); - final FileInputStream stream2 = new FileInputStream("src/test/resources/test_read6.in"); - - final SequenceInputStream sequence = new SequenceInputStream(stream1, stream2); - final DataInputStream reader = new DataInputStream(sequence); - - assertEquals(expected_value1, reader.readInt()); - assertEquals(expected_value2, reader.readInt()); - - reader.close(); - stream2.close(); + assertEquals(expectedValue, result); } @Test - @Ignore // TODO public void whenReadUTFEncodedFile_thenCorrect() throws IOException { final String expected_value = "青空"; - final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); + final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/fileTestUtf8.txt"), "UTF-8")); final String currentLine = reader.readLine(); reader.close(); - LOG.debug(currentLine); - + assertEquals(expected_value, currentLine); } @Test public void whenReadFileContentsIntoString_thenCorrect() throws IOException { - final String expected_value = "Hello world \n Test line \n"; - final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read8.in")); + final String expected_value = "Hello, world!\n"; + final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/fileTest.txt")); final StringBuilder builder = new StringBuilder(); String currentLine = reader.readLine(); while (currentLine != null) { @@ -136,8 +220,8 @@ public class JavaReadFromFileUnitTest { @Test public void whenReadWithFileChannel_thenCorrect() throws IOException { - final String expected_value = "Hello world"; - final RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r"); + final String expected_value = "Hello, world!"; + final RandomAccessFile reader = new RandomAccessFile("src/test/resources/fileTest.txt", "r"); final FileChannel channel = reader.getChannel(); int bufferSize = 1024; @@ -154,8 +238,8 @@ public class JavaReadFromFileUnitTest { @Test public void whenReadSmallFileJava7_thenCorrect() throws IOException { - final String expected_value = "Hello world"; - final Path path = Paths.get("src/test/resources/test_read.in"); + final String expected_value = "Hello, world!"; + final Path path = Paths.get("src/test/resources/fileTest.txt"); final String read = Files.readAllLines(path, Charset.defaultCharset()).get(0); assertEquals(expected_value, read); @@ -163,12 +247,24 @@ public class JavaReadFromFileUnitTest { @Test public void whenReadLargeFileJava7_thenCorrect() throws IOException { - final String expected_value = "Hello world"; + final String expected_value = "Hello, world!"; - final Path path = Paths.get("src/test/resources/test_read.in"); + final Path path = Paths.get("src/test/resources/fileTest.txt"); final BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset()); final String line = reader.readLine(); assertEquals(expected_value, line); } + private String readFromInputStream(InputStream inputStream) throws IOException { + StringBuilder resultStringBuilder = new StringBuilder(); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + resultStringBuilder.append(line).append("\n"); + } + } + + return resultStringBuilder.toString(); + } + } diff --git a/core-java-modules/core-java-io/src/test/resources/fileTest.txt b/core-java-modules/core-java-io/src/test/resources/fileTest.txt index ce4bea208b..5dd01c177f 100644 --- a/core-java-modules/core-java-io/src/test/resources/fileTest.txt +++ b/core-java-modules/core-java-io/src/test/resources/fileTest.txt @@ -1 +1 @@ -Hello World from fileTest.txt!!! \ No newline at end of file +Hello, world! \ No newline at end of file diff --git a/core-java-modules/core-java-io/src/test/resources/test_read3.in b/core-java-modules/core-java-io/src/test/resources/fileTestTokenizer.txt similarity index 100% rename from core-java-modules/core-java-io/src/test/resources/test_read3.in rename to core-java-modules/core-java-io/src/test/resources/fileTestTokenizer.txt diff --git a/core-java-modules/core-java-io/src/test/resources/test_read7.in b/core-java-modules/core-java-io/src/test/resources/fileTestUtf8.txt similarity index 100% rename from core-java-modules/core-java-io/src/test/resources/test_read7.in rename to core-java-modules/core-java-io/src/test/resources/fileTestUtf8.txt diff --git a/core-java-modules/core-java-io/src/test/resources/test_read1.in b/core-java-modules/core-java-io/src/test/resources/test_read1.in deleted file mode 100644 index 1e46242993..0000000000 --- a/core-java-modules/core-java-io/src/test/resources/test_read1.in +++ /dev/null @@ -1 +0,0 @@ -Hello world 1 \ No newline at end of file diff --git a/core-java-modules/core-java-io/src/test/resources/test_read2.in b/core-java-modules/core-java-io/src/test/resources/test_read2.in deleted file mode 100644 index fe47dc003b..0000000000 --- a/core-java-modules/core-java-io/src/test/resources/test_read2.in +++ /dev/null @@ -1 +0,0 @@ -2,3 4 \ No newline at end of file diff --git a/core-java-modules/core-java-io/src/test/resources/test_read4.in b/core-java-modules/core-java-io/src/test/resources/test_read4.in deleted file mode 100644 index 5727d54bfc..0000000000 Binary files a/core-java-modules/core-java-io/src/test/resources/test_read4.in and /dev/null differ diff --git a/core-java-modules/core-java-io/src/test/resources/test_read8.in b/core-java-modules/core-java-io/src/test/resources/test_read8.in deleted file mode 100644 index 10fc1aac8a..0000000000 --- a/core-java-modules/core-java-io/src/test/resources/test_read8.in +++ /dev/null @@ -1,2 +0,0 @@ -Hello world - Test line diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml index a3e8941622..1d87bcda5f 100644 --- a/core-java-modules/core-java-jar/pom.xml +++ b/core-java-modules/core-java-jar/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-jar 0.1.0-SNAPSHOT @@ -99,7 +101,7 @@ true libs/ - org.baeldung.executable.ExecutableMavenJar + com.baeldung.executable.ExecutableMavenJar @@ -118,7 +120,7 @@ ${project.basedir} - org.baeldung.executable.ExecutableMavenJar + com.baeldung.executable.ExecutableMavenJar @@ -142,7 +144,7 @@ true - org.baeldung.executable.ExecutableMavenJar + com.baeldung.executable.ExecutableMavenJar @@ -157,7 +159,7 @@ - org.baeldung.executable.ExecutableMavenJar + com.baeldung.executable.ExecutableMavenJar true ${project.build.finalName}-onejar.${project.packaging} @@ -179,7 +181,7 @@ spring-boot - org.baeldung.executable.ExecutableMavenJar + com.baeldung.executable.ExecutableMavenJar @@ -196,7 +198,7 @@ -Xmx300m -XX:+UseParallelGC -classpath - + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed @@ -207,8 +209,8 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} @@ -262,7 +264,7 @@ java -classpath - + org.openjdk.jmh.Main .* @@ -397,6 +399,8 @@ 3.1.1 2.0.3.RELEASE 1.6.0 + 1.8 + 1.8 diff --git a/core-java-modules/core-java-jndi/pom.xml b/core-java-modules/core-java-jndi/pom.xml index 13504886d6..4a491a1a47 100644 --- a/core-java-modules/core-java-jndi/pom.xml +++ b/core-java-modules/core-java-jndi/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 com.baeldung.jndi core-java-jndi @@ -9,44 +10,54 @@ core-java-jndi - com.baeldung - parent-modules + com.baeldung.core-java-modules + core-java-modules 1.0.0-SNAPSHOT - ../../ org.junit.jupiter junit-jupiter - 5.5.1 + ${jupiter.version} test + + org.junit.jupiter + junit-jupiter-api + ${jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${jupiter.version} + org.springframework spring-core - 5.0.9.RELEASE + ${spring.version} org.springframework spring-context - 5.0.9.RELEASE + ${spring.version} org.springframework spring-jdbc - 5.0.9.RELEASE + ${spring.version} org.springframework spring-test - 5.0.9.RELEASE + ${spring.version} test com.h2database h2 - 1.4.199 + ${h2.version} @@ -56,11 +67,19 @@ org.apache.maven.plugins maven-compiler-plugin - 1.8 - 1.8 + ${source.version} + ${target.version} + + 5.0.9.RELEASE + 1.4.199 + 5.5.1 + 1.8 + 1.8 + + diff --git a/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java index 49d4facffb..218807568c 100644 --- a/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java +++ b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java @@ -1,5 +1,12 @@ package com.baeldung.jndi.exceptions; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import javax.naming.InitialContext; +import javax.naming.NameNotFoundException; +import javax.naming.NoInitialContextException; + +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; @@ -7,12 +14,6 @@ import org.junit.jupiter.api.TestMethodOrder; import org.springframework.jndi.JndiTemplate; import org.springframework.mock.jndi.SimpleNamingContextBuilder; -import javax.naming.InitialContext; -import javax.naming.NameNotFoundException; -import javax.naming.NoInitialContextException; - -import static org.junit.jupiter.api.Assertions.assertThrows; - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class JndiExceptionsUnitTest { diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml index ddf52d8fef..fe6689dcc3 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 consumermodule 1.0 @@ -16,7 +18,7 @@ com.baeldung.servicemodule servicemodule - 1.0 + ${servicemodule.version} @@ -29,4 +31,8 @@ + + 1.0 + + diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml index 78a9d1eaad..fd59c151e6 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 com.baeldung.decoupling-pattern1 decoupling-pattern1 @@ -19,10 +20,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 11 - 11 + ${source.version} + ${target.version} @@ -31,6 +32,9 @@ UTF-8 + 3.8.0 + 11 + 11 \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml index ece85fd5dc..c2da228ce6 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml @@ -1,8 +1,9 @@ - + 4.0.0 - com.baeldung.servicemodule servicemodule jar diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml index 734774af0e..e6b351b1b9 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml @@ -1,15 +1,16 @@ - + 4.0.0 com.baeldung.consumermodule consumermodule 1.0 - decoupling-pattern2 - com.baeldung.decoupling-pattern2 + com.baeldung.decoupling-pattern2 + decoupling-pattern2 1.0-SNAPSHOT @@ -17,12 +18,12 @@ com.baeldung.servicemodule servicemodule - 1.0 + ${servicemodule.version} com.baeldung.providermodule providermodule - 1.0 + ${providermodule.version} @@ -35,4 +36,9 @@ + + 1.0 + 1.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml index 2f84c69fd6..17bca54edb 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 com.baeldung.decoupling-pattern2 decoupling-pattern2 @@ -20,14 +21,20 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 11 - 11 + ${source.version} + ${target.version} + + 3.8.0 + 11 + 11 + + \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml index 5ec36c581e..3e8d5c0c39 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml @@ -1,15 +1,16 @@ - + 4.0.0 com.baeldung.providermodule providermodule 1.0 - decoupling-pattern2 - com.baeldung.decoupling-pattern2 + com.baeldung.decoupling-pattern2 + decoupling-pattern2 1.0-SNAPSHOT @@ -17,7 +18,7 @@ com.baeldung.servicemodule servicemodule - 1.0 + ${servicemodule.version} @@ -30,4 +31,9 @@ + + 1.0 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml index 9249ea5d89..51d64998df 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml @@ -1,15 +1,15 @@ - + 4.0.0 - com.baeldung.servicemodule servicemodule 1.0 - decoupling-pattern2 - >com.baeldung.decoupling-pattern2 + com.baeldung.decoupling-pattern2 + decoupling-pattern2 1.0-SNAPSHOT diff --git a/core-java-modules/core-java-jpms/pom.xml b/core-java-modules/core-java-jpms/pom.xml new file mode 100644 index 0000000000..4610baab49 --- /dev/null +++ b/core-java-modules/core-java-jpms/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + core-java-jpms + 0.0.1-SNAPSHOT + core-java-jpms + pom + + + com.baeldung.core-java-modules + core-java-modules + 1.0.0-SNAPSHOT + + + + decoupling-pattern1 + decoupling-pattern2 + + + diff --git a/core-java-modules/core-java-jvm/README.md b/core-java-modules/core-java-jvm/README.md index 89600ad924..2f80ea7372 100644 --- a/core-java-modules/core-java-jvm/README.md +++ b/core-java-modules/core-java-jvm/README.md @@ -10,3 +10,5 @@ This module contains articles about working with the Java Virtual Machine (JVM). - [Class Loaders in Java](https://www.baeldung.com/java-classloaders) - [A Guide to System.exit()](https://www.baeldung.com/java-system-exit) - [Guide to System.gc()](https://www.baeldung.com/java-system-gc) +- [Runtime.getRuntime().halt() vs System.exit() in Java](https://www.baeldung.com/java-runtime-halt-vs-system-exit) +- [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks) diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml index 61c31ce82f..edf7a4f3c5 100644 --- a/core-java-modules/core-java-jvm/pom.xml +++ b/core-java-modules/core-java-jvm/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-jvm 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoManualTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoManualTest.java new file mode 100644 index 0000000000..d56dea62f4 --- /dev/null +++ b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoManualTest.java @@ -0,0 +1,14 @@ +package com.baeldung.exitvshalt; + +import org.junit.Test; + +public class JvmExitDemoManualTest { + + JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo(); + + @Test + public void givenProcessComplete_whenExitCalled_thenTriggerShutdownHook() { + jvmExitAndHaltDemo.processAndExit(); + } + +} diff --git a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoUnitTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoUnitTest.java deleted file mode 100644 index 0c50651af0..0000000000 --- a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoUnitTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.exitvshalt; - -import org.junit.Test; - -public class JvmExitDemoUnitTest { - - JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo(); - - @Test - public void givenProcessComplete_whenExitCalled_thenTriggerShutdownHook() { - jvmExitAndHaltDemo.processAndExit(); - } - -} diff --git a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoManualTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoManualTest.java new file mode 100644 index 0000000000..4fe0999a9c --- /dev/null +++ b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoManualTest.java @@ -0,0 +1,14 @@ +package com.baeldung.exitvshalt; + +import org.junit.Test; + +public class JvmHaltDemoManualTest { + + JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo(); + + @Test + public void givenProcessComplete_whenHaltCalled_thenDoNotTriggerShutdownHook() { + jvmExitAndHaltDemo.processAndHalt(); + } + +} diff --git a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoUnitTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoUnitTest.java deleted file mode 100644 index 9f08e95c6a..0000000000 --- a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoUnitTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.exitvshalt; - -import org.junit.Test; - -public class JvmHaltDemoUnitTest { - - JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo(); - - @Test - public void givenProcessComplete_whenHaltCalled_thenDoNotTriggerShutdownHook() { - jvmExitAndHaltDemo.processAndHalt(); - } - -} diff --git a/core-java-modules/core-java-lambdas/pom.xml b/core-java-modules/core-java-lambdas/pom.xml index fbcd9d5870..421ca2f394 100644 --- a/core-java-modules/core-java-lambdas/pom.xml +++ b/core-java-modules/core-java-lambdas/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 core-java-lambdas 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index 57d9d8347b..9e510575fc 100644 --- a/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -1,18 +1,17 @@ package com.baeldung.java8; -import static org.hamcrest.Matchers.equalTo; +import com.baeldung.java8.entity.Human; +import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; +import org.junit.Assert; +import org.junit.Test; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -import org.junit.Assert; -import org.junit.Test; - -import com.baeldung.java8.entity.Human; -import com.google.common.collect.Lists; -import com.google.common.primitives.Ints; +import static org.hamcrest.Matchers.equalTo; public class Java8SortUnitTest { @@ -113,11 +112,11 @@ public class Java8SortUnitTest { humans.sort(Comparator.comparing(Human::getName)); Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12))); } - + @Test public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { final List letters = Lists.newArrayList("B", "A", "C"); - + final List sortedLetters = letters.stream().sorted().collect(Collectors.toList()); Assert.assertThat(sortedLetters.get(0), equalTo("A")); } @@ -126,7 +125,7 @@ public class Java8SortUnitTest { public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); final Comparator nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName()); - + final List sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList()); Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12))); } @@ -164,4 +163,48 @@ public class Java8SortUnitTest { Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10))); } + @Test(expected = NullPointerException.class) + public final void givenANullElement_whenSortingEntitiesByName_thenThrowsNPE() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12)); + + humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName())); + } + + @Test + public final void givenANullElement_whenSortingEntitiesByNameManually_thenMovesTheNullToLast() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12), null); + + humans.sort((h1, h2) -> { + if (h1 == null) return h2 == null ? 0 : 1; + else if (h2 == null) return -1; + + return h1.getName().compareTo(h2.getName()); + }); + + Assert.assertNotNull(humans.get(0)); + Assert.assertNull(humans.get(1)); + Assert.assertNull(humans.get(2)); + } + + @Test + public final void givenANullElement_whenSortingEntitiesByName_thenMovesTheNullToLast() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12), null); + + humans.sort(Comparator.nullsLast(Comparator.comparing(Human::getName))); + + Assert.assertNotNull(humans.get(0)); + Assert.assertNull(humans.get(1)); + Assert.assertNull(humans.get(2)); + } + + @Test + public final void givenANullElement_whenSortingEntitiesByName_thenMovesTheNullToStart() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12), null); + + humans.sort(Comparator.nullsFirst(Comparator.comparing(Human::getName))); + + Assert.assertNull(humans.get(0)); + Assert.assertNull(humans.get(1)); + Assert.assertNotNull(humans.get(2)); + } } diff --git a/core-java-modules/core-java-lang-2/README.md b/core-java-modules/core-java-lang-2/README.md index 5d51f3cea4..3ade982397 100644 --- a/core-java-modules/core-java-lang-2/README.md +++ b/core-java-modules/core-java-lang-2/README.md @@ -6,4 +6,9 @@ This module contains articles about core features in the Java language - [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects) - [Command-Line Arguments in Java](https://www.baeldung.com/java-command-line-arguments) - [What is a POJO Class?](https://www.baeldung.com/java-pojo-class) +- [Java Default Parameters Using Method Overloading](https://www.baeldung.com/java-default-parameters-method-overloading) +- [How to Return Multiple Values From a Java Method](https://www.baeldung.com/java-method-return-multiple-values) +- [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword) +- [The Java Headless Mode](https://www.baeldung.com/java-headless-mode) +- [Comparing Long Values in Java](https://www.baeldung.com/java-compare-long-values) - [[<-- Prev]](/core-java-modules/core-java-lang) diff --git a/core-java-modules/core-java-lang-2/pom.xml b/core-java-modules/core-java-lang-2/pom.xml index 5657e64b17..5aa80ce3df 100644 --- a/core-java-modules/core-java-lang-2/pom.xml +++ b/core-java-modules/core-java-lang-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-lang-2 0.1.0-SNAPSHOT @@ -15,10 +17,15 @@ + + org.apache.commons + commons-lang3 + 3.9 + commons-beanutils commons-beanutils - 1.9.4 + ${commons.beanutils.version} org.openjdk.jmh @@ -57,6 +64,7 @@ 1.19 1.19 3.12.2 + 1.9.4 diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExample.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExample.java new file mode 100644 index 0000000000..bb0bad8cf4 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExample.java @@ -0,0 +1,14 @@ +package com.baeldung.finallykeyword; + +public class FinallyExample { + + public void printCount(String count) { + try { + System.out.println("The count is " + Integer.parseInt(count)); + } catch (NumberFormatException e) { + System.out.println("No count"); + } finally { + System.out.println("In finally"); + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExecutedCases.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExecutedCases.java new file mode 100644 index 0000000000..68a3763da0 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExecutedCases.java @@ -0,0 +1,53 @@ +package com.baeldung.finallykeyword; + +public class FinallyExecutedCases { + + public void noExceptionFinally() { + try { + System.out.println("Inside try"); + } finally { + System.out.println("Inside finally"); + } + } + + public void unhandledException() throws Exception { + try { + System.out.println("Inside try"); + throw new Exception(); + } finally { + System.out.println("Inside finally"); + } + } + + public void handledException() { + try { + System.out.println("Inside try"); + throw new Exception(); + } catch (Exception e) { + System.out.println("Inside catch"); + } finally { + System.out.println("Inside finally"); + } + } + + public String returnFromTry() { + try { + System.out.println("Inside try"); + return "from try"; + } finally { + System.out.println("Inside finally"); + } + } + + public String returnFromCatch() { + try { + System.out.println("Inside try"); + throw new Exception(); + } catch (Exception e) { + System.out.println("Inside catch"); + return "from catch"; + } finally { + System.out.println("Inside finally"); + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyNotExecutedCases.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyNotExecutedCases.java new file mode 100644 index 0000000000..92c0ea729d --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyNotExecutedCases.java @@ -0,0 +1,54 @@ +package com.baeldung.finallykeyword; + +public class FinallyNotExecutedCases { + + public void callingSystemExit() { + try { + System.out.println("Inside try"); + System.exit(1); + } finally { + System.out.println("Inside finally"); + } + } + + public void callingRuntimeHalt() { + try { + System.out.println("Inside try"); + Runtime.getRuntime() + .halt(1); + } finally { + System.out.println("Inside finally"); + } + } + + public void infiniteLoop() { + try { + System.out.println("Inside try"); + while (true) { + } + } finally { + System.out.println("Inside finally"); + } + } + + public void daemonThread() throws InterruptedException { + Runnable runnable = () -> { + try { + System.out.println("Inside try"); + } finally { + try { + Thread.sleep(1000); + System.out.println("Inside finally"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }; + Thread regular = new Thread(runnable); + Thread daemon = new Thread(runnable); + daemon.setDaemon(true); + regular.start(); + Thread.sleep(300); + daemon.start(); + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinally.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinally.java new file mode 100644 index 0000000000..f1a56441f2 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinally.java @@ -0,0 +1,33 @@ +package com.baeldung.finallykeyword; + +public class PitfallsWhenUsingFinally { + + public String disregardsUnCaughtException() { + try { + System.out.println("Inside try"); + throw new RuntimeException(); + } finally { + System.out.println("Inside finally"); + return "from finally"; + } + } + + public String ignoringOtherReturns() { + try { + System.out.println("Inside try"); + return "from try"; + } finally { + System.out.println("Inside finally"); + return "from finally"; + } + } + + public String throwsException() { + try { + System.out.println("Inside try"); + return "from try"; + } finally { + throw new RuntimeException(); + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/headlessmode/FlexibleApp.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/headlessmode/FlexibleApp.java new file mode 100644 index 0000000000..50f33d239d --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/headlessmode/FlexibleApp.java @@ -0,0 +1,27 @@ +package com.baeldung.headlessmode; + +import java.awt.GraphicsEnvironment; + +import javax.swing.JOptionPane; + +public class FlexibleApp { + public static final int HEADLESS = 0; + public static final int HEADED = 1; + public FlexibleApp() { + + if (GraphicsEnvironment.isHeadless()) { + System.out.println("Hello World"); + } else { + JOptionPane.showMessageDialog(null, "Hello World"); + } + + } + + public static int iAmFlexible() { + if (GraphicsEnvironment.isHeadless()) { + return HEADLESS; + } else { + return HEADED; + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Coordinates.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Coordinates.java new file mode 100644 index 0000000000..4a292b9b18 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Coordinates.java @@ -0,0 +1,49 @@ +package com.baeldung.methodmultiplereturnvalues; + +public class Coordinates { + + private double longitude; + private double latitude; + private String placeName; + + public Coordinates() {} + + public Coordinates(double longitude, double latitude, String placeName) { + this.longitude = longitude; + this.latitude = latitude; + this.placeName = placeName; + } + + public double calculateDistance(Coordinates c) { + + double s1 = Math.abs(this.longitude - c.longitude); + double s2 = Math.abs(this.latitude - c.latitude); + + return Math.hypot(s1, s2); + } + + public double getLongitude() { + return longitude; + } + + public void setLongitude(double longitude) { + this.longitude = longitude; + } + + public double getLatitude() { + return latitude; + } + + public void setLatitude(double latitude) { + this.latitude = latitude; + } + + public String getPlaceName() { + return placeName; + } + + public void setPlaceName(String placeName) { + this.placeName = placeName; + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsPair.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsPair.java new file mode 100644 index 0000000000..2f505443c2 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsPair.java @@ -0,0 +1,20 @@ +package com.baeldung.methodmultiplereturnvalues; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; + +import java.util.Comparator; +import java.util.List; + +class MultipleReturnValuesUsingApacheCommonsPair { + + static ImmutablePair getMostDistantPoint( + List coordinatesList, + Coordinates target) { + return coordinatesList.stream() + .map(coordinates -> ImmutablePair.of(coordinates, coordinates.calculateDistance(target))) + .max(Comparator.comparingDouble(Pair::getRight)) + .get(); + + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsTriple.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsTriple.java new file mode 100644 index 0000000000..4da297a51f --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsTriple.java @@ -0,0 +1,23 @@ +package com.baeldung.methodmultiplereturnvalues; + +import org.apache.commons.lang3.tuple.ImmutableTriple; + +import java.util.List; +import java.util.stream.Collectors; + +class MultipleReturnValuesUsingApacheCommonsTriple { + + static ImmutableTriple getMinAvgMaxTriple( + List coordinatesList, + Coordinates target) { + + List distanceList = coordinatesList.stream() + .map(coordinates -> coordinates.calculateDistance(target)) + .collect(Collectors.toList()); + Double minDistance = distanceList.stream().mapToDouble(Double::doubleValue).min().getAsDouble(); + Double avgDistance = distanceList.stream().mapToDouble(Double::doubleValue).average().orElse(0.0D); + Double maxDistance = distanceList.stream().mapToDouble(Double::doubleValue).max().getAsDouble(); + + return ImmutableTriple.of(minDistance, avgDistance, maxDistance); + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArrays.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArrays.java new file mode 100644 index 0000000000..9763422618 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArrays.java @@ -0,0 +1,27 @@ +package com.baeldung.methodmultiplereturnvalues; + +class MultipleReturnValuesUsingArrays { + + + static double[] getCoordinatesDoubleArray() { + + double[] coordinates = new double[2]; + + coordinates[0] = 10; + coordinates[1] = 12.5; + + return coordinates; + } + + + static Number[] getCoordinatesNumberArray() { + + Number[] coordinates = new Number[2]; + + coordinates[0] = 10; //Integer + coordinates[1] = 12.5; //Double + + return coordinates; + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollections.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollections.java new file mode 100644 index 0000000000..ccd5a4b74e --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollections.java @@ -0,0 +1,30 @@ +package com.baeldung.methodmultiplereturnvalues; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class MultipleReturnValuesUsingCollections { + + static List getCoordinatesList() { + + List coordinates = new ArrayList<>(); + + coordinates.add(10); + coordinates.add(12.5); + + return coordinates; + } + + static Map getCoordinatesMap() { + + Map coordinates = new HashMap<>(); + + coordinates.put("longitude", 10); + coordinates.put("latitude", 12.5); + + return coordinates; + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainer.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainer.java new file mode 100644 index 0000000000..617f0df17c --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainer.java @@ -0,0 +1,14 @@ +package com.baeldung.methodmultiplereturnvalues; + +class MultipleReturnValuesUsingContainer { + + static Coordinates getCoordinates() { + + double longitude = 10; + double latitude = 12.5; + String placeName = "home"; + + return new Coordinates(longitude, latitude, placeName); + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuples.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuples.java new file mode 100644 index 0000000000..59984f777e --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuples.java @@ -0,0 +1,17 @@ +package com.baeldung.methodmultiplereturnvalues; + +import java.util.List; + +class MultipleReturnValuesUsingTuples { + + static Tuple2 getMostDistantPoint(List coordinatesList, + Coordinates target) { + + return coordinatesList.stream() + .map(coor -> new Tuple2<>(coor, coor.calculateDistance(target))) + .max((d1, d2) -> Double.compare(d1.getSecond(), d2.getSecond())) + .get(); + + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Tuple2.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Tuple2.java new file mode 100644 index 0000000000..57ef20d572 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Tuple2.java @@ -0,0 +1,31 @@ +package com.baeldung.methodmultiplereturnvalues; + +public class Tuple2 { + + private K first; + private V second; + + public Tuple2() {} + + public Tuple2(K first, V second) { + this.first = first; + this.second = second; + } + + public K getFirst() { + return first; + } + + public V getSecond() { + return second; + } + + public void setFirst(K first) { + this.first = first; + } + + public void setSecond(V second) { + this.second = second; + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java new file mode 100644 index 0000000000..a26b0a74b0 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java @@ -0,0 +1,84 @@ +package com.baeldung.comparelong; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +import org.junit.Test; + +import java.util.Objects; + +public class CompareLongUnitTest { + + @Test + public void givenLongValuesLessThan128_whenUsingReferenceComparater_thenSuccess() { + + Long l1 = 127L; + Long l2 = 127L; + + assertThat(l1 == l2).isTrue(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingReferenceComparater_thenFails() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(l1 == l2).isFalse(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingEquals_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(l1.equals(l2)).isTrue(); + } + + @Test + public void givenLongValuesLessThan128_whenUsingObjectsEquals_thenSuccess() { + + Long l1 = 127L; + Long l2 = 127L; + + assertThat(Objects.equals(l1, l2)).isTrue(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingObjectsEquals_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(Objects.equals(l1, l2)).isTrue(); + } + + @Test + public void givenNullReference_whenUsingObjectsEquals_thenNoException() { + + Long l1 = null; + Long l2 = 128L; + + assertThatCode(() -> Objects.equals(l1, l2)).doesNotThrowAnyException(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingComparisonOperator_andLongValue_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(l1.longValue() == l2.longValue()).isTrue(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingCasting_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat((long) l1 == (long) l2).isTrue(); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/exceptions/RootCauseFinder.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/exceptions/RootCauseFinder.java new file mode 100644 index 0000000000..e05dc7a6cd --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/exceptions/RootCauseFinder.java @@ -0,0 +1,95 @@ +package com.baeldung.exceptions; + +import java.time.LocalDate; +import java.time.Period; +import java.time.format.DateTimeParseException; +import java.util.Objects; + +/** + * Utility class to find root cause exceptions. + */ +public class RootCauseFinder { + + public static Throwable findCauseUsingPlainJava(Throwable throwable) { + Objects.requireNonNull(throwable); + Throwable rootCause = throwable; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + return rootCause; + } + + /** + * Calculates the age of a person from a given date. + */ + static class AgeCalculator { + + private AgeCalculator() { + } + + public static int calculateAge(String birthDate) throws CalculationException { + if (birthDate == null || birthDate.isEmpty()) { + throw new IllegalArgumentException(); + } + + try { + return Period + .between(parseDate(birthDate), LocalDate.now()) + .getYears(); + } catch (DateParseException ex) { + throw new CalculationException(ex); + } + } + + private static LocalDate parseDate(String birthDateAsString) throws DateParseException { + + LocalDate birthDate; + try { + birthDate = LocalDate.parse(birthDateAsString); + } catch (DateTimeParseException ex) { + throw new InvalidFormatException(birthDateAsString, ex); + } + + if (birthDate.isAfter(LocalDate.now())) { + throw new DateOutOfRangeException(birthDateAsString); + } + + return birthDate; + } + + } + + static class CalculationException extends Exception { + + CalculationException(DateParseException ex) { + super(ex); + } + } + + static class DateParseException extends Exception { + + DateParseException(String input) { + super(input); + } + + DateParseException(String input, Throwable thr) { + super(input, thr); + } + } + + static class InvalidFormatException extends DateParseException { + + InvalidFormatException(String input, Throwable thr) { + super("Invalid date format: " + input, thr); + } + } + + static class DateOutOfRangeException extends DateParseException { + + DateOutOfRangeException(String date) { + super("Date out of range: " + date); + } + + } + +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinallyUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinallyUnitTest.java new file mode 100644 index 0000000000..7e7a7241ec --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinallyUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.finallykeyword; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class PitfallsWhenUsingFinallyUnitTest { + + PitfallsWhenUsingFinally instance = new PitfallsWhenUsingFinally(); + + @Test + public void testIgnoresException() { + String result = instance.disregardsUnCaughtException(); + assertEquals("from finally", result); + } + + @Test + public void testIgnoresOtherReturns() { + String result = instance.ignoringOtherReturns(); + assertEquals("from finally", result); + } + + @Test(expected = RuntimeException.class) + public void testThrowsException() { + instance.throwsException(); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/headlessmode/HeadlessModeUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/headlessmode/HeadlessModeUnitTest.java new file mode 100644 index 0000000000..a17c1600f3 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/headlessmode/HeadlessModeUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.headlessmode; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +import java.awt.Canvas; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Frame; +import java.awt.GraphicsEnvironment; +import java.awt.HeadlessException; +import java.awt.image.BufferedImage; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import javax.imageio.ImageIO; + +import org.junit.Assume; +import org.junit.Before; +import org.junit.Test; + +public class HeadlessModeUnitTest { + + private static final String IN_FILE = "/product.png"; + private static final String OUT_FILE = System.getProperty("java.io.tmpdir") + "/product.jpg"; + private static final String FORMAT = "jpg"; + + @Before + public void setUpHeadlessMode() { + System.setProperty("java.awt.headless", "true"); + } + + @Test + public void whenJavaAwtHeadlessSetToTrue_thenIsHeadlessReturnsTrue() { + assertThat(GraphicsEnvironment.isHeadless()).isTrue(); + } + + @Test + public void whenHeadlessMode_thenFontsWork() { + GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); + + String fonts[] = ge.getAvailableFontFamilyNames(); + + assertThat(fonts).isNotEmpty(); + + Font font = new Font(fonts[0], Font.BOLD, 14); + + FontMetrics fm = (new Canvas()).getFontMetrics(font); + + assertThat(fm.getHeight()).isGreaterThan(0); + assertThat(fm.getAscent()).isGreaterThan(0); + assertThat(fm.getDescent()).isGreaterThan(0); + } + + @Test + public void whenHeadlessMode_thenImagesWork() throws IOException { + boolean result = false; + try (InputStream inStream = HeadlessModeUnitTest.class.getResourceAsStream(IN_FILE); FileOutputStream outStream = new FileOutputStream(OUT_FILE)) { + BufferedImage inputImage = ImageIO.read(inStream); + result = ImageIO.write(inputImage, FORMAT, outStream); + } + + assertThat(result).isTrue(); + } + + @Test + public void whenHeadlessmode_thenFrameThrowsHeadlessException() { + assertThatExceptionOfType(HeadlessException.class).isThrownBy(() -> { + Frame frame = new Frame(); + frame.setVisible(true); + frame.setSize(120, 120); + }); + } + + @Test + public void whenHeadless_thenFlexibleAppAdjustsItsBehavior() { + assertThat(FlexibleApp.iAmFlexible()).isEqualTo(FlexibleApp.HEADLESS); + } + + @Test + public void whenHeaded_thenFlexibleAppAdjustsItsBehavior() { + Assume.assumeFalse(GraphicsEnvironment.isHeadless()); + assertThat(FlexibleApp.iAmFlexible()).isEqualTo(FlexibleApp.HEADED); + } + +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsPairUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsPairUnitTest.java new file mode 100644 index 0000000000..ca5736fe50 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsPairUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.methodmultiplereturnvalues; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MultipleReturnValuesUsingApacheCommonsPairUnitTest { + + @Test + void whenUsingPair_thenMultipleFieldsAreReturned() { + + List coordinatesList = new ArrayList<>(); + coordinatesList.add(new Coordinates(1, 1, "home")); + coordinatesList.add(new Coordinates(2, 2, "school")); + coordinatesList.add(new Coordinates(3, 3, "hotel")); + + Coordinates target = new Coordinates(5, 5, "gym"); + + ImmutablePair mostDistantPoint = MultipleReturnValuesUsingApacheCommonsPair.getMostDistantPoint(coordinatesList, target); + + assertEquals(1, mostDistantPoint.getLeft().getLongitude()); + assertEquals(1, mostDistantPoint.getLeft().getLatitude()); + assertEquals("home", mostDistantPoint.getLeft().getPlaceName()); + assertEquals(5.66, BigDecimal.valueOf(mostDistantPoint.getRight()).setScale(2, RoundingMode.HALF_UP).doubleValue()); + + } + +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsTripleUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsTripleUnitTest.java new file mode 100644 index 0000000000..d23036f5e6 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingApacheCommonsTripleUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.methodmultiplereturnvalues; + +import org.apache.commons.lang3.tuple.ImmutableTriple; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MultipleReturnValuesUsingApacheCommonsTripleUnitTest { + + @Test + void whenUsingTriple_thenMultipleFieldsAreReturned() { + + List coordinatesList = new ArrayList<>(); + coordinatesList.add(new Coordinates(1, 1, "home")); + coordinatesList.add(new Coordinates(2, 2, "school")); + coordinatesList.add(new Coordinates(3, 3, "hotel")); + + Coordinates target = new Coordinates(5, 5, "gym"); + + ImmutableTriple minAvgMax = MultipleReturnValuesUsingApacheCommonsTriple.getMinAvgMaxTriple(coordinatesList, target); + + assertEquals(2.83, scaleDouble(minAvgMax.left)); //min + assertEquals(4.24, scaleDouble(minAvgMax.middle)); //avg + assertEquals(5.66, scaleDouble(minAvgMax.right)); //max + } + + private double scaleDouble(Double d) { + return BigDecimal.valueOf(d).setScale(2, RoundingMode.HALF_UP).doubleValue(); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArraysUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArraysUnitTest.java new file mode 100644 index 0000000000..0cf90a8879 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArraysUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingArraysUnitTest { + + @Test + void whenUsingArrayOfDoubles_thenMultipleDoubleFieldsAreReturned() { + + double[] coordinates = MultipleReturnValuesUsingArrays.getCoordinatesDoubleArray(); + assertEquals(10, coordinates[0]); + assertEquals(12.5, coordinates[1]); + } + + @Test + void whenUsingArrayOfNumbers_thenMultipleNumberFieldsAreReturned() { + + Number[] coordinates = MultipleReturnValuesUsingArrays.getCoordinatesNumberArray(); + assertEquals(10, coordinates[0]); + assertEquals(12.5, coordinates[1]); + + } + +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollectionsUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollectionsUnitTest.java new file mode 100644 index 0000000000..8038601986 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollectionsUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingCollectionsUnitTest { + + @Test + void whenUsingList_thenMultipleFieldsAreReturned() { + + List coordinates = MultipleReturnValuesUsingCollections.getCoordinatesList(); + assertEquals(Integer.valueOf(10), coordinates.get(0)); + assertEquals(Double.valueOf(12.5), coordinates.get(1)); + } + + @Test + void whenUsingMap_thenMultipleFieldsAreReturned() { + + Map coordinates = MultipleReturnValuesUsingCollections.getCoordinatesMap(); + assertEquals(Integer.valueOf(10), coordinates.get("longitude")); + assertEquals(Double.valueOf(12.5), coordinates.get("latitude")); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainerUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainerUnitTest.java new file mode 100644 index 0000000000..f7fd9bd108 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainerUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingContainerUnitTest { + + @Test + void whenUsingContainerClass_thenMultipleFieldsAreReturned() { + + Coordinates coordinates = MultipleReturnValuesUsingContainer.getCoordinates(); + + assertEquals(10, coordinates.getLongitude()); + assertEquals(12.5, coordinates.getLatitude()); + assertEquals("home", coordinates.getPlaceName()); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuplesUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuplesUnitTest.java new file mode 100644 index 0000000000..52f30286bc --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuplesUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingTuplesUnitTest { + + @Test + void whenUsingTuple_thenMultipleFieldsAreReturned() { + + List coordinatesList = new ArrayList<>(); + coordinatesList.add(new Coordinates(1, 1, "home")); + coordinatesList.add(new Coordinates(2, 2, "school")); + coordinatesList.add(new Coordinates(3, 3, "hotel")); + + Coordinates target = new Coordinates(5, 5, "gym"); + + Tuple2 mostDistantPoint = MultipleReturnValuesUsingTuples.getMostDistantPoint(coordinatesList, target); + + assertEquals(1, mostDistantPoint.getFirst().getLongitude()); + assertEquals(1, mostDistantPoint.getFirst().getLatitude()); + assertEquals("home", mostDistantPoint.getFirst().getPlaceName()); + assertEquals(5.66, BigDecimal.valueOf(mostDistantPoint.getSecond()).setScale(2, RoundingMode.HALF_UP).doubleValue()); + + } + +} diff --git a/core-java-modules/core-java-lang-2/src/test/resources/product.png b/core-java-modules/core-java-lang-2/src/test/resources/product.png new file mode 100644 index 0000000000..4edd01c0a1 Binary files /dev/null and b/core-java-modules/core-java-lang-2/src/test/resources/product.png differ diff --git a/core-java-modules/core-java-lang-math-2/.gitignore b/core-java-modules/core-java-lang-math-2/.gitignore new file mode 100644 index 0000000000..30b2b7442c --- /dev/null +++ b/core-java-modules/core-java-lang-math-2/.gitignore @@ -0,0 +1,4 @@ +/target/ +.settings/ +.classpath +.project \ No newline at end of file diff --git a/core-java-modules/core-java-lang-math-2/README.md b/core-java-modules/core-java-lang-math-2/README.md new file mode 100644 index 0000000000..09039f6ed0 --- /dev/null +++ b/core-java-modules/core-java-lang-math-2/README.md @@ -0,0 +1,16 @@ +========= + +## Core Java 8 Cookbooks and Examples - Part 2 + +### Relevant articles: + +- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial) +- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm) +- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap) +- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points) +- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines) +- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred) +- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude) +- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging) +- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication) +- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math) diff --git a/core-java-modules/core-java-lang-math-2/pom.xml b/core-java-modules/core-java-lang-math-2/pom.xml new file mode 100644 index 0000000000..92ebcc6a94 --- /dev/null +++ b/core-java-modules/core-java-lang-math-2/pom.xml @@ -0,0 +1,90 @@ + + + 4.0.0 + core-java-lang-math-2 + 0.0.1-SNAPSHOT + core-java-lang-math-2 + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.ejml + ejml-all + ${ejml.version} + + + org.nd4j + nd4j-native + ${nd4j.version} + + + org.la4j + la4j + ${la4j.version} + + + colt + colt + ${colt.version} + + + com.google.guava + guava + ${guava.version} + + + org.assertj + assertj-core + ${org.assertj.core.version} + test + + + com.github.dpaukov + combinatoricslib3 + ${combinatoricslib3.version} + + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + + + + + 3.6.1 + 3.9.0 + 27.0.1-jre + 3.3.0 + 0.38 + 1.0.0-beta4 + 1.2.0 + 0.6.0 + 1.19 + + + \ No newline at end of file diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/factorial/Factorial.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/factorial/Factorial.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/factorial/Factorial.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/factorial/Factorial.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/mercator/Mercator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/Mercator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/mercator/Mercator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/Mercator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/roundedup/RoundUpToHundred.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/roundedup/RoundUpToHundred.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/roundedup/RoundUpToHundred.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/roundedup/RoundUpToHundred.java diff --git a/java-math/src/main/java/com/baeldung/matrices/HomemadeMatrix.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/HomemadeMatrix.java similarity index 100% rename from java-math/src/main/java/com/baeldung/matrices/HomemadeMatrix.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/HomemadeMatrix.java diff --git a/java-math/src/main/java/com/baeldung/matrices/benchmark/BigMatrixMultiplicationBenchmarking.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/BigMatrixMultiplicationBenchmarking.java similarity index 100% rename from java-math/src/main/java/com/baeldung/matrices/benchmark/BigMatrixMultiplicationBenchmarking.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/BigMatrixMultiplicationBenchmarking.java diff --git a/java-math/src/main/java/com/baeldung/matrices/benchmark/BigMatrixProvider.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/BigMatrixProvider.java similarity index 100% rename from java-math/src/main/java/com/baeldung/matrices/benchmark/BigMatrixProvider.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/BigMatrixProvider.java diff --git a/java-math/src/main/java/com/baeldung/matrices/benchmark/MatrixMultiplicationBenchmarking.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/MatrixMultiplicationBenchmarking.java similarity index 100% rename from java-math/src/main/java/com/baeldung/matrices/benchmark/MatrixMultiplicationBenchmarking.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/MatrixMultiplicationBenchmarking.java diff --git a/java-math/src/main/java/com/baeldung/matrices/benchmark/MatrixProvider.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/MatrixProvider.java similarity index 100% rename from java-math/src/main/java/com/baeldung/matrices/benchmark/MatrixProvider.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/MatrixProvider.java diff --git a/java-collections-maps/src/main/resources/logback.xml b/core-java-modules/core-java-lang-math-2/src/main/resources/logback.xml similarity index 100% rename from java-collections-maps/src/main/resources/logback.xml rename to core-java-modules/core-java-lang-math-2/src/main/resources/logback.xml diff --git a/java-math/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/roundedup/RoundUpToHundredUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/roundedup/RoundUpToHundredUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/roundedup/RoundUpToHundredUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/roundedup/RoundUpToHundredUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java diff --git a/core-java-modules/core-java-lang-math/README.md b/core-java-modules/core-java-lang-math/README.md index aec339574b..9295349f82 100644 --- a/core-java-modules/core-java-lang-math/README.md +++ b/core-java-modules/core-java-lang-math/README.md @@ -7,3 +7,10 @@ - [Java 8 Unsigned Arithmetic Support](https://www.baeldung.com/java-unsigned-arithmetic) - [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts) - [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp) +- [Basic Calculator in Java](https://www.baeldung.com/java-basic-calculator) +- [Overflow and Underflow in Java](https://www.baeldung.com/java-overflow-underflow) +- [Obtaining a Power Set of a Set in Java](https://www.baeldung.com/java-power-set-of-a-set) +- [Calculating Logarithms in Java](https://www.baeldung.com/java-logarithms) +- [Finding Greatest Common Divisor in Java](https://www.baeldung.com/java-greatest-common-divisor) +- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage) +- More articles: [[Next -->]](/core-java-modules/core-java-lang-math-2) diff --git a/core-java-modules/core-java-lang-math/pom.xml b/core-java-modules/core-java-lang-math/pom.xml index 671d5630d2..bcb5cf39d2 100644 --- a/core-java-modules/core-java-lang-math/pom.xml +++ b/core-java-modules/core-java-lang-math/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-lang-math 0.1.0-SNAPSHOT diff --git a/java-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java rename to core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/percentage/PercentageCalculator.java b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/PercentageCalculator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/percentage/PercentageCalculator.java rename to core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/PercentageCalculator.java diff --git a/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java new file mode 100644 index 0000000000..336276786a --- /dev/null +++ b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java @@ -0,0 +1,302 @@ +package com.baeldung.powerset; + +import javax.annotation.Nullable; +import java.util.AbstractSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +public class PowerSetUtility { + + private Map map = new HashMap<>(); + private List reverseMap = new ArrayList<>(); + + //Lazy Load PowerSet class + private static class PowerSet extends AbstractSet> { + private Map map = new HashMap<>(); + private List reverseMap = new ArrayList<>(); + private Set set; + + public PowerSet(Set set) { + this.set = set; + initializeMap(); + } + + abstract class ListIterator implements Iterator { + + protected int position = 0; + private int size; + + public ListIterator(int size) { + this.size = size; + } + + @Override + public boolean hasNext() { + return position < size; + } + } + + static class Subset extends AbstractSet { + private Map map; + private List reverseMap; + private int mask; + + public Subset(Map map, List reverseMap, int mask) { + this.map = map; + this.reverseMap = reverseMap; + this.mask = mask; + } + + @Override + public Iterator iterator() { + return new Iterator() { + int remainingSetBits = mask; + + @Override + public boolean hasNext() { + return remainingSetBits != 0; + } + + @Override + public E next() { + int index = Integer.numberOfTrailingZeros(remainingSetBits); + if (index == 32) { + throw new NoSuchElementException(); + } + remainingSetBits &= ~(1 << index); + return reverseMap.get(index); + } + }; + } + + @Override + public int size() { + return Integer.bitCount(mask); + } + + @Override + public boolean contains(@Nullable Object o) { + Integer index = map.get(o); + return index != null && (mask & (1 << index)) != 0; + } + } + + @Override + public Iterator> iterator() { + return new ListIterator>(this.size()) { + @Override + public Set next() { + return new Subset<>(map, reverseMap, position++); + } + }; + } + + @Override + public int size() { + return (1 << this.set.size()); + } + + @Override + public boolean contains(@Nullable Object obj) { + if (obj instanceof Set) { + Set set = (Set) obj; + return reverseMap.containsAll(set); + } + return false; + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof PowerSet) { + PowerSet that = (PowerSet) obj; + return set.equals(that.set);//Set equals check to have the same element regardless of the order of the items + } + return super.equals(obj); + } + + + private void initializeMap() { + int mapId = 0; + for (E c : this.set) { + map.put(c, mapId++); + reverseMap.add(c); + } + } + } + + public Set> lazyLoadPowerSet(Set set) { + return new PowerSet<>(set); + } + + public Set> recursivePowerSet(Set set) { + if (set.isEmpty()) { + Set> ret = new HashSet<>(); + ret.add(set); + return ret; + } + + T element = set.iterator().next(); + Set subSetWithoutElement = getSubSetWithoutElement(set, element); + Set> powerSetSubSetWithoutElement = recursivePowerSet(subSetWithoutElement); + + Set> powerSetSubSetWithElement = addElementToAll(powerSetSubSetWithoutElement, element); + + Set> powerSet = new HashSet<>(); + powerSet.addAll(powerSetSubSetWithoutElement); + powerSet.addAll(powerSetSubSetWithElement); + return powerSet; + } + + public Set> recursivePowerSetIndexRepresentation(Collection set) { + initializeMap(set); + Set> powerSetIndices = recursivePowerSetIndexRepresentation(0, set.size()); + return unMapIndex(powerSetIndices); + } + + private List> iterativePowerSetByLoopOverNumbers(int n) { + List> powerSet = new ArrayList<>(); + for (int i = 0; i < (1 << n); i++) { + List subset = new ArrayList<>(n); + for (int j = 0; j < n; j++) + subset.add(((1 << j) & i) > 0); + powerSet.add(subset); + } + return powerSet; + } + + private List> iterativePowerSetByLoopOverNumbersWithMinimalChange(int n) { + List> powerSet = new ArrayList<>(); + for (int i = 0; i < (1 << n); i++) { + List subset = new ArrayList<>(n); + for (int j = 0; j < n; j++) { + int grayEquivalent = i ^ (i >> 1); + subset.add(((1 << j) & grayEquivalent) > 0); + } + powerSet.add(subset); + } + return powerSet; + } + + public Set> recursivePowerSetBinaryRepresentation(Collection set) { + initializeMap(set); + Set> powerSetBoolean = recursivePowerSetBinaryRepresentation(0, set.size()); + return unMapBinary(powerSetBoolean); + } + + public List> iterativePowerSetByLoopOverNumbers(Set set) { + initializeMap(set); + List> sets = iterativePowerSetByLoopOverNumbers(set.size()); + return unMapListBinary(sets); + } + + public List> iterativePowerSetByLoopOverNumbersMinimalChange(Set set) { + initializeMap(set); + List> sets = iterativePowerSetByLoopOverNumbersWithMinimalChange(set.size()); + return unMapListBinary(sets); + } + + private Set> recursivePowerSetIndexRepresentation(int idx, int n) { + if (idx == n) { + Set> empty = new HashSet<>(); + empty.add(new HashSet<>()); + return empty; + } + Set> powerSetSubset = recursivePowerSetIndexRepresentation(idx + 1, n); + Set> powerSet = new HashSet<>(powerSetSubset); + for (Set s : powerSetSubset) { + HashSet subSetIdxInclusive = new HashSet<>(s); + subSetIdxInclusive.add(idx); + powerSet.add(subSetIdxInclusive); + } + return powerSet; + } + + private Set> recursivePowerSetBinaryRepresentation(int idx, int n) { + if (idx == n) { + Set> powerSetOfEmptySet = new HashSet<>(); + powerSetOfEmptySet.add(Arrays.asList(new Boolean[n])); + return powerSetOfEmptySet; + } + Set> powerSetSubset = recursivePowerSetBinaryRepresentation(idx + 1, n); + Set> powerSet = new HashSet<>(); + for (List s : powerSetSubset) { + List subSetIdxExclusive = new ArrayList<>(s); + subSetIdxExclusive.set(idx, false); + powerSet.add(subSetIdxExclusive); + List subSetIdxInclusive = new ArrayList<>(s); + subSetIdxInclusive.set(idx, true); + powerSet.add(subSetIdxInclusive); + } + return powerSet; + } + + private void initializeMap(Collection collection) { + int mapId = 0; + for (T c : collection) { + map.put(c, mapId++); + reverseMap.add(c); + } + } + + private Set> unMapIndex(Set> sets) { + Set> ret = new HashSet<>(); + for (Set s : sets) { + HashSet subset = new HashSet<>(); + for (Integer i : s) + subset.add(reverseMap.get(i)); + ret.add(subset); + } + return ret; + } + + private Set> unMapBinary(Collection> sets) { + Set> ret = new HashSet<>(); + for (List s : sets) { + HashSet subset = new HashSet<>(); + for (int i = 0; i < s.size(); i++) + if (s.get(i)) + subset.add(reverseMap.get(i)); + ret.add(subset); + } + return ret; + } + + private List> unMapListBinary(Collection> sets) { + List> ret = new ArrayList<>(); + for (List s : sets) { + List subset = new ArrayList<>(); + for (int i = 0; i < s.size(); i++) + if (s.get(i)) + subset.add(reverseMap.get(i)); + ret.add(subset); + } + return ret; + } + + private Set> addElementToAll(Set> powerSetSubSetWithoutElement, T element) { + Set> powerSetSubSetWithElement = new HashSet<>(); + for (Set subsetWithoutElement : powerSetSubSetWithoutElement) { + Set subsetWithElement = new HashSet<>(subsetWithoutElement); + subsetWithElement.add(element); + powerSetSubSetWithElement.add(subsetWithElement); + } + return powerSetSubSetWithElement; + } + + private Set getSubSetWithoutElement(Set set, T element) { + Set subsetWithoutElement = new HashSet<>(); + for (T s : set) { + if (!s.equals(element)) + subsetWithoutElement.add(s); + } + return subsetWithoutElement; + } +} diff --git a/java-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java rename to core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/logarithm/LogarithmUnitTest.java b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/logarithm/LogarithmUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/logarithm/LogarithmUnitTest.java rename to core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/logarithm/LogarithmUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/percentage/PercentageCalculatorUnitTest.java b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/percentage/PercentageCalculatorUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/percentage/PercentageCalculatorUnitTest.java rename to core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/percentage/PercentageCalculatorUnitTest.java diff --git a/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java new file mode 100644 index 0000000000..8b7c338479 --- /dev/null +++ b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java @@ -0,0 +1,189 @@ +package com.baeldung.powerset; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.hamcrest.collection.IsCollectionWithSize; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; + +public class PowerSetUtilityUnitTest { + + @Test + public void givenSet_WhenGuavaLibraryGeneratePowerSet_ThenItContainsAllSubsets() { + ImmutableSet set = ImmutableSet.of("APPLE", "ORANGE", "MANGO"); + Set> powerSet = Sets.powerSet(set); + Assertions.assertEquals((1 << set.size()), powerSet.size()); + MatcherAssert.assertThat(powerSet, Matchers.containsInAnyOrder( + ImmutableSet.of(), + ImmutableSet.of("APPLE"), + ImmutableSet.of("ORANGE"), + ImmutableSet.of("APPLE", "ORANGE"), + ImmutableSet.of("MANGO"), + ImmutableSet.of("APPLE", "MANGO"), + ImmutableSet.of("ORANGE", "MANGO"), + ImmutableSet.of("APPLE", "ORANGE", "MANGO") + )); + } + + @Test + public void givenSet_WhenPowerSetIsLazyLoadGenerated_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + Set> powerSet = new PowerSetUtility().lazyLoadPowerSet(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculated_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + Set> powerSet = new PowerSetUtility().recursivePowerSet(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedRecursiveByIndexRepresentation_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + Set> powerSet = new PowerSetUtility().recursivePowerSetIndexRepresentation(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedRecursiveByBinaryRepresentation_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + Set> powerSet = new PowerSetUtility().recursivePowerSetBinaryRepresentation(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbers_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + List> powerSet = new PowerSetUtility().iterativePowerSetByLoopOverNumbers(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (List subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + //To make sure that one subset is not generated twice + Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size()); + //To make sure that each element in each subset is occurred once + for (List subset : powerSet) { + Assertions.assertEquals(subset.size(), new HashSet<>(subset).size()); + } + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbersWithMinimalChange_ThenItContainsAllSubsets() { + + Set set = RandomSetOfStringGenerator.generateRandomSet(); + List> powerSet = new PowerSetUtility().iterativePowerSetByLoopOverNumbersMinimalChange(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (List subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + //To make sure that one subset is not generated twice + Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size()); + //To make sure that each element in each subset is occurred once + for (List subset : powerSet) { + Assertions.assertEquals(subset.size(), new HashSet<>(subset).size()); + } + //To make sure that difference of consecutive subsets is exactly 1 + for(int i=1; i fruits = Arrays.asList("Apples", "Avocados", "Banana", "Blueberry", "Cherry", "Clementine", "Cucumber", "Date", "Fig", + "Grapefruit"/*, "Grape", "Kiwi", "Lemon", "Mango", "Mulberry", "Melon", "Nectarine", "Olive", "Orange"*/); + + static Set generateRandomSet() { + Set set = new HashSet<>(); + Random random = new Random(); + int size = random.nextInt(fruits.size()); + while (set.size() != size) { + set.add(fruits.get(random.nextInt(fruits.size()))); + } + return set; + } + } +} diff --git a/core-java-modules/core-java-lang-oop-2/.gitignore b/core-java-modules/core-java-lang-oop-2/.gitignore deleted file mode 100644 index 36aba1c242..0000000000 --- a/core-java-modules/core-java-lang-oop-2/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target/ -.idea/ -bin/ -*.iml \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-2/README.md b/core-java-modules/core-java-lang-oop-2/README.md deleted file mode 100644 index 035d464c50..0000000000 --- a/core-java-modules/core-java-lang-oop-2/README.md +++ /dev/null @@ -1,19 +0,0 @@ -## Core Java Lang OOP (Part 2) - -This module contains articles about Object-oriented programming (OOP) in Java - -### Relevant Articles: -- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors) -- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error) -- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes) -- [Raw Types in Java](https://www.baeldung.com/raw-types-java) -- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces) -- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts) -- [Immutable Objects in Java](https://www.baeldung.com/java-immutable-object) -- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](https://www.baeldung.com/java-inheritance-composition) -- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors) -- [Composition, Aggregation, and Association in Java](https://www.baeldung.com/java-composition-aggregation-association) -- [Static and Default Methods in Interfaces in Java](https://www.baeldung.com/java-static-default-methods) -- [Java Copy Constructor](https://www.baeldung.com/java-copy-constructor) -- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class) -- [[<-- Prev]](/core-java-modules/core-java-lang-oop)[[More -->]](/core-java-modules/core-java-lang-oop-3) diff --git a/core-java-modules/core-java-lang-oop-2/pom.xml b/core-java-modules/core-java-lang-oop-2/pom.xml deleted file mode 100644 index 01bacab0b9..0000000000 --- a/core-java-modules/core-java-lang-oop-2/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - core-java-lang-oop-2 - 0.1.0-SNAPSHOT - core-java-lang-oop-2 - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - - org.assertj - assertj-core - ${assertj-core.version} - test - - - nl.jqno.equalsverifier - equalsverifier - ${equalsverifier.version} - test - - - - - core-java-lang-oop-2 - - - src/main/resources - true - - - - - - - 3.10.0 - 3.0.3 - - - diff --git a/core-java-modules/core-java-lang-oop-3/README.md b/core-java-modules/core-java-lang-oop-3/README.md deleted file mode 100644 index b1ca877ae0..0000000000 --- a/core-java-modules/core-java-lang-oop-3/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Core Java Lang OOP (Part 3) - -This module contains articles about Object-oriented programming (OOP) in Java - -### Relevant Articles: -- [Pass-By-Value as a Parameter Passing Mechanism in Java](https://www.baeldung.com/java-pass-by-value-or-pass-by-reference) -- [Access Modifiers in Java](https://www.baeldung.com/java-access-modifiers) -- [Guide to the super Java Keyword](https://www.baeldung.com/java-super) -- [Guide to the this Java Keyword](https://www.baeldung.com/java-this) -- [Java ‘public’ Access Modifier](https://www.baeldung.com/java-public-keyword) -- [Composition, Aggregation and Association in Java](https://www.baeldung.com/java-composition-aggregation-association) -- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes) -- [A Guide to Inner Interfaces in Java](https://www.baeldung.com/java-inner-interfaces) -- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects) -- [Java Interfaces](https://www.baeldung.com/java-interfaces) -- [[<-- Prev]](/core-java-modules/core-java-lang-oop-2)[[More -->]](/core-java-modules/core-java-lang-oop-4) \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-3/pom.xml b/core-java-modules/core-java-lang-oop-3/pom.xml deleted file mode 100644 index 70939c32c9..0000000000 --- a/core-java-modules/core-java-lang-oop-3/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - 4.0.0 - core-java-lang-oop-3 - 0.1.0-SNAPSHOT - core-java-lang-oop-3 - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - - log4j - log4j - ${log4j.version} - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - org.assertj - assertj-core - ${assertj-core.version} - test - - - com.h2database - h2 - ${h2.version} - test - - - - - core-java-lang-oop-3 - - - src/main/resources - true - - - - - - 3.10.0 - - - diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/publicmodifier/SpecialCharacters.java b/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/publicmodifier/SpecialCharacters.java deleted file mode 100644 index 5556e9aa57..0000000000 --- a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/publicmodifier/SpecialCharacters.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.accessmodifiers.publicmodifier; - -public class SpecialCharacters { - - public static final String SLASH = "/"; - -} diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/publicmodifier/Student.java b/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/publicmodifier/Student.java deleted file mode 100644 index 83a0dcb30f..0000000000 --- a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/publicmodifier/Student.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.accessmodifiers.publicmodifier; - -import java.math.BigDecimal; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.Date; - -public class Student { - - private StudentGrade grade; //new data representation -// private int grade; //old data representation - private String name; - private int age; - - public void setGrade(int grade) { - this.grade = new StudentGrade(grade); - } - - public int getGrade() { - return this.grade.getGrade().intValue(); //int is returned for backward compatibility - } - - public Connection getConnection() throws SQLException { - - final String URL = "jdbc:h2:~/test"; - return DriverManager.getConnection(URL, "sa", ""); - - } - - public void setAge(int age) { - if (age < 0 || age > 150) { - throw new IllegalArgumentException(); - } - - this.age = age; - } - - public int getAge() { - return age; - } - - @Override - public String toString() { - return this.name; - } - - private class StudentGrade { - private BigDecimal grade = BigDecimal.ZERO; - private Date updatedAt; - - public StudentGrade(int grade) { - this.grade = new BigDecimal(grade); - this.updatedAt = new Date(); - } - - public BigDecimal getGrade() { - return grade; - } - - public Date getDate() { - return updatedAt; - } - - } - -} diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/KeywordDemo.java b/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/KeywordDemo.java deleted file mode 100644 index fd608b424c..0000000000 --- a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/KeywordDemo.java +++ /dev/null @@ -1,16 +0,0 @@ -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-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java b/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java deleted file mode 100644 index 35fd7358af..0000000000 --- a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java +++ /dev/null @@ -1,49 +0,0 @@ -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-modules/core-java-lang-oop-3/src/test/java/com/baeldung/nestedclass/AnonymousInner.java b/core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/nestedclass/AnonymousInner.java deleted file mode 100644 index 9fa8ee9cd5..0000000000 --- a/core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/nestedclass/AnonymousInner.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.nestedclass; - -import org.junit.Test; - -abstract class SimpleAbstractClass { - abstract void run(); -} - -public class AnonymousInner { - - @Test - public void run() { - SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() { - void run() { - System.out.println("Running Anonymous Class..."); - } - }; - simpleAbstractClass.run(); - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-4/README.md b/core-java-modules/core-java-lang-oop-4/README.md deleted file mode 100644 index 51650dc1f6..0000000000 --- a/core-java-modules/core-java-lang-oop-4/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Core Java Lang OOP (Part 4) - -This module contains articles about Object-oriented programming (OOP) in Java - -### Relevant Articles: -- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding) -- [Methods in Java](https://www.baeldung.com/java-methods) -- [Java ‘private’ Access Modifier](https://www.baeldung.com/java-private-keyword) -- [[<-- Prev]](/core-java-modules/core-java-lang-oop-3) \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-4/pom.xml b/core-java-modules/core-java-lang-oop-4/pom.xml deleted file mode 100644 index 9e138afddf..0000000000 --- a/core-java-modules/core-java-lang-oop-4/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - 4.0.0 - core-java-lang-oop-4 - 0.1.0-SNAPSHOT - core-java-lang-oop-4 - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - - log4j - log4j - ${log4j.version} - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - org.assertj - assertj-core - ${assertj-core.version} - test - - - com.h2database - h2 - ${h2.version} - test - - - - - core-java-lang-oop-4 - - - src/main/resources - true - - - - - - 3.10.0 - - - diff --git a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/basicmethods/PersonName.java b/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/basicmethods/PersonName.java deleted file mode 100644 index 43bbf0dd62..0000000000 --- a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/basicmethods/PersonName.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.basicmethods; - -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; - -public class PersonName { - - public String getName(String firstName, String lastName) throws RuntimeException { - return firstName + " " + lastName; - } - - public String getName(String firstName, String middleName, String lastName) { - if (!middleName.equals("")) { - return firstName + " " + lastName; - } - return firstName + " " + middleName + " " + lastName; - } - - public void printFullName(String firstName, String lastName) { - System.out.println(firstName + " " + lastName); - } - - public void writeName(String name) throws IOException { - PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt")); - out.println("Name: " + name); - out.close(); - } - - public static String getNameStatic(String firstName, String lastName) { - return firstName + " " + lastName; - } - - public static void callToStaticMethod() { - System.out.println("Name is: " + PersonName.getNameStatic("Alan", "Turing")); - } -} diff --git a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/binding/Cat.java b/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/binding/Cat.java deleted file mode 100644 index bbe740e412..0000000000 --- a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/binding/Cat.java +++ /dev/null @@ -1,18 +0,0 @@ -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-modules/core-java-lang-oop-4/src/main/java/com/baeldung/core/privatemodifier/Employee.java b/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/core/privatemodifier/Employee.java deleted file mode 100644 index 4598400e93..0000000000 --- a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/core/privatemodifier/Employee.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.core.privatemodifier; - -public class Employee { - - private String privateId; - private String name; - private boolean manager; - - public Employee(String id, String name) { - setPrivateId(id); - setName(name); - } - - private Employee(String id, String name, boolean managerAttribute) { - this.privateId = id; - this.name = name; - this.privateId = id + "_ID-MANAGER"; - } - - public void setPrivateId(String customId) { - if (customId.endsWith("_ID")) { - this.privateId = customId; - } else { - this.privateId = customId + "_ID"; - } - } - - public String getPrivateId() { - return privateId; - } - - public boolean isManager() { - return manager; - } - - public void elevateToManager() { - if ("Carl".equals(this.name)) { - setManager(true); - } - } - - private void setManager(boolean manager) { - this.manager = manager; - } - - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public static Employee buildManager(String id, String name) { - return new Employee(id, name, true); - } - -} diff --git a/core-java-modules/core-java-lang-oop-4/src/test/java/com/baeldung/binding/CatUnitTest.java b/core-java-modules/core-java-lang-oop-4/src/test/java/com/baeldung/binding/CatUnitTest.java deleted file mode 100644 index 76ccfb7719..0000000000 --- a/core-java-modules/core-java-lang-oop-4/src/test/java/com/baeldung/binding/CatUnitTest.java +++ /dev/null @@ -1,62 +0,0 @@ -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-modules/core-java-lang-oop-constructors/README.md b/core-java-modules/core-java-lang-oop-constructors/README.md new file mode 100644 index 0000000000..0082969807 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-constructors/README.md @@ -0,0 +1,8 @@ +## Core Java Lang OOP - Constructors + +This module contains article about constructors in Java + +### Relevant Articles: +- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors) +- [Java Copy Constructor](https://www.baeldung.com/java-copy-constructor) +- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error) \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-constructors/pom.xml b/core-java-modules/core-java-lang-oop-constructors/pom.xml new file mode 100644 index 0000000000..76507103ea --- /dev/null +++ b/core-java-modules/core-java-lang-oop-constructors/pom.xml @@ -0,0 +1,28 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-lang-oop-constructors + core-java-lang-oop-constructors + jar + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + 3.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/constructors/BankAccount.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructors/BankAccount.java similarity index 99% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/constructors/BankAccount.java rename to core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructors/BankAccount.java index b78b5937e1..b198492129 100644 --- a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/constructors/BankAccount.java +++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructors/BankAccount.java @@ -6,7 +6,7 @@ class BankAccount { String name; LocalDateTime opened; double balance; - + @Override public String toString() { return String.format("%s, %s, %f", this.name, this.opened.toString(), this.balance); @@ -47,14 +47,13 @@ class BankAccountCopyConstructor extends BankAccount { this.opened = opened; this.balance = balance; } - + public BankAccountCopyConstructor(BankAccount other) { this.name = other.name; this.opened = LocalDateTime.now(); this.balance = 0.0f; } } - class BankAccountChainedConstructors extends BankAccount { public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) { this.name = name; @@ -65,4 +64,4 @@ class BankAccountChainedConstructors extends BankAccount { public BankAccountChainedConstructors(String name) { this(name, LocalDateTime.now(), 0.0f); } -} +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/constructors/Transaction.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructors/Transaction.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/constructors/Transaction.java rename to core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructors/Transaction.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/copyconstructor/Employee.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/copyconstructor/Employee.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/copyconstructor/Employee.java rename to core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/copyconstructor/Employee.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/copyconstructor/Manager.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/copyconstructor/Manager.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/copyconstructor/Manager.java rename to core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/copyconstructor/Manager.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/supertypecompilerexception/MyClass.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/supertypecompilerexception/MyClass.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/supertypecompilerexception/MyClass.java rename to core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/supertypecompilerexception/MyClass.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution1.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution1.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution1.java rename to core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution1.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution2.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution2.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution2.java rename to core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution2.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution3.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution3.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution3.java rename to core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/supertypecompilerexception/MyClassSolution3.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/supertypecompilerexception/MyException.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/supertypecompilerexception/MyException.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/supertypecompilerexception/MyException.java rename to core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/supertypecompilerexception/MyException.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java b/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java similarity index 88% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java rename to core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java index 274fe77764..e207afec57 100644 --- a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java +++ b/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java @@ -1,20 +1,19 @@ package com.baeldung.constructors; +import org.assertj.core.api.Assertions; import org.junit.Test; import java.time.LocalDateTime; import java.time.Month; -import java.util.logging.Logger; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; public class ConstructorUnitTest { - final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName()); - + @Test public void givenNoExplicitContructor_whenUsed_thenFails() { BankAccount account = new BankAccount(); - assertThatThrownBy(() -> { + Assertions.assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class); } @@ -22,7 +21,7 @@ public class ConstructorUnitTest { @Test public void givenNoArgumentConstructor_whenUsed_thenSucceeds() { BankAccountEmptyConstructor account = new BankAccountEmptyConstructor(); - assertThatCode(() -> { + Assertions.assertThatCode(() -> { account.toString(); }).doesNotThrowAnyException(); } @@ -33,7 +32,7 @@ public class ConstructorUnitTest { BankAccountParameterizedConstructor account = new BankAccountParameterizedConstructor("Tom", opened, 1000.0f); - assertThatCode(() -> { + Assertions.assertThatCode(() -> { account.toString(); }).doesNotThrowAnyException(); } diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/copyconstructor/EmployeeUnitTest.java b/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/copyconstructor/EmployeeUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/copyconstructor/EmployeeUnitTest.java rename to core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/copyconstructor/EmployeeUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/copyconstructor/ManagerUnitTest.java b/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/copyconstructor/ManagerUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/copyconstructor/ManagerUnitTest.java rename to core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/copyconstructor/ManagerUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-generics/README.md b/core-java-modules/core-java-lang-oop-generics/README.md new file mode 100644 index 0000000000..f0213c5659 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/README.md @@ -0,0 +1,8 @@ +## Core Java Lang OOP - Generics + +This module contains articles about generics in Java + +### Relevant Articles: +- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors) +- [Type Erasure in Java Explained](https://www.baeldung.com/java-type-erasure) +- [Raw Types in Java](https://www.baeldung.com/raw-types-java) diff --git a/core-java-modules/core-java-lang-oop-generics/pom.xml b/core-java-modules/core-java-lang-oop-generics/pom.xml new file mode 100644 index 0000000000..ae141ecda2 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/pom.xml @@ -0,0 +1,16 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-lang-oop-generics + core-java-lang-oop-generics + jar + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/generics/Entry.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/Entry.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/generics/Entry.java rename to core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/Entry.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/generics/GenericEntry.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/GenericEntry.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/generics/GenericEntry.java rename to core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/GenericEntry.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/generics/MapEntry.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/MapEntry.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/generics/MapEntry.java rename to core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/MapEntry.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/generics/Product.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/Product.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/generics/Product.java rename to core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/Product.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/generics/Rankable.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/Rankable.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/generics/Rankable.java rename to core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/Rankable.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/rawtype/RawTypeDemo.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/rawtype/RawTypeDemo.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/rawtype/RawTypeDemo.java rename to core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/rawtype/RawTypeDemo.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/ArrayContentPrintUtil.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/typeerasure/ArrayContentPrintUtil.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/ArrayContentPrintUtil.java rename to core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/typeerasure/ArrayContentPrintUtil.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/BoundStack.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/typeerasure/BoundStack.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/BoundStack.java rename to core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/typeerasure/BoundStack.java diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/typeerasure/Example.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/typeerasure/Example.java new file mode 100644 index 0000000000..f816fd6d16 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/typeerasure/Example.java @@ -0,0 +1,13 @@ +package com.baeldung.typeerasure; + +public class Example { + + public static boolean containsElement(E [] elements, E element){ + for (E e : elements){ + if(e.equals(element)){ + return true; + } + } + return false; + } +} diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/IntegerStack.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/typeerasure/IntegerStack.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/IntegerStack.java rename to core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/typeerasure/IntegerStack.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/Stack.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/typeerasure/Stack.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/Stack.java rename to core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/typeerasure/Stack.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/generics/GenericConstructorUnitTest.java b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/generics/GenericConstructorUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/generics/GenericConstructorUnitTest.java rename to core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/generics/GenericConstructorUnitTest.java diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/typeerasure/TypeErasureUnitTest.java b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/typeerasure/TypeErasureUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/typeerasure/TypeErasureUnitTest.java rename to core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/typeerasure/TypeErasureUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-inheritance/README.md b/core-java-modules/core-java-lang-oop-inheritance/README.md new file mode 100644 index 0000000000..c87bdf13d7 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/README.md @@ -0,0 +1,14 @@ +## Core Java Lang OOP - Inheritance + +This module contains articles about inheritance in Java + +### Relevant Articles: +- [Java Interfaces](https://www.baeldung.com/java-interfaces) +- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class) +- [A Guide to Inner Interfaces in Java](https://www.baeldung.com/java-inner-interfaces) +- [Guide to the super Java Keyword](https://www.baeldung.com/java-super) +- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes) +- [Polymorphism in Java](https://www.baeldung.com/java-polymorphism) +- [Guide to Inheritance in Java](https://www.baeldung.com/java-inheritance) +- [Object Type Casting in Java](https://www.baeldung.com/java-type-casting) +- [Variable and Method Hiding in Java](https://www.baeldung.com/java-variable-method-hiding) diff --git a/core-java-modules/core-java-lang-oop-inheritance/pom.xml b/core-java-modules/core-java-lang-oop-inheritance/pom.xml new file mode 100644 index 0000000000..a48b28a289 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/pom.xml @@ -0,0 +1,28 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-lang-oop-inheritance + core-java-lang-oop-inheritance + jar + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + 3.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/abstractclasses/application/Application.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/application/Application.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/abstractclasses/application/Application.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/application/Application.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/abstractclasses/filereaders/BaseFileReader.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/filereaders/BaseFileReader.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/abstractclasses/filereaders/BaseFileReader.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/filereaders/BaseFileReader.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/abstractclasses/filereaders/LowercaseFileReader.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/filereaders/LowercaseFileReader.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/abstractclasses/filereaders/LowercaseFileReader.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/filereaders/LowercaseFileReader.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/abstractclasses/filereaders/UppercaseFileReader.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/filereaders/UppercaseFileReader.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/abstractclasses/filereaders/UppercaseFileReader.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/filereaders/UppercaseFileReader.java diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/overview/BoardGame.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/overview/BoardGame.java new file mode 100644 index 0000000000..e0395cec7e --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/overview/BoardGame.java @@ -0,0 +1,9 @@ +package com.baeldung.abstractclasses.overview; + +public abstract class BoardGame { + //... field declarations, constructors + + public abstract void play(); + + //... concrete methods +} diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/overview/Checkers.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/overview/Checkers.java new file mode 100644 index 0000000000..5c911649c8 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/abstractclasses/overview/Checkers.java @@ -0,0 +1,8 @@ +package com.baeldung.abstractclasses.overview; + +public class Checkers extends BoardGame { + @Override + public void play() { + //... implementation + } +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/anonymous/Book.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/anonymous/Book.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/anonymous/Book.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/anonymous/Book.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/anonymous/Main.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/anonymous/Main.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/anonymous/Main.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/anonymous/Main.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/Animal.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/Animal.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/Animal.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/Animal.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/AnimalFeeder.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/AnimalFeeder.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/AnimalFeeder.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/AnimalFeeder.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/Cat.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/Cat.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/Cat.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/Cat.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/Dog.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/Dog.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/Dog.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/Dog.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/Mew.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/Mew.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/casting/Mew.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/casting/Mew.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/ArmoredCar.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/ArmoredCar.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/ArmoredCar.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/ArmoredCar.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/BMW.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/BMW.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/BMW.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/BMW.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Car.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/Car.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Car.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/Car.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Employee.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/Employee.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Employee.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/Employee.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Floatable.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/Floatable.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Floatable.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/Floatable.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Flyable.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/Flyable.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Flyable.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/Flyable.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/SpaceCar.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/SpaceCar.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/SpaceCar.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/SpaceCar.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/SpaceTraveller.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/SpaceTraveller.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/inheritance/SpaceTraveller.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/inheritance/SpaceTraveller.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/innerinterfaces/CommaSeparatedCustomers.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/innerinterfaces/CommaSeparatedCustomers.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/innerinterfaces/CommaSeparatedCustomers.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/innerinterfaces/CommaSeparatedCustomers.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/innerinterfaces/Customer.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/innerinterfaces/Customer.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/innerinterfaces/Customer.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/innerinterfaces/Customer.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/Box.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/Box.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/Box.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/Box.java diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/Computer.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/Computer.java new file mode 100644 index 0000000000..94d39e2448 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/Computer.java @@ -0,0 +1,9 @@ +package com.baeldung.interfaces; + +public class Computer implements Electronic { + + @Override + public int getElectricityUse() { + return 1000; + } +} diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/Electronic.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/Electronic.java new file mode 100644 index 0000000000..fcaf67dc3a --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/Electronic.java @@ -0,0 +1,22 @@ +package com.baeldung.interfaces; + +public interface Electronic { + // Constant variable + String LED = "LED"; + + // Abstract method + int getElectricityUse(); + + // Static method + static boolean isEnergyEfficient(String electtronicType) { + if (electtronicType.equals(LED)) { + return true; + } + return false; + } + + //Default method + default void printDescription() { + System.out.println("Electronic Description"); + } +} diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/Employee.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/Employee.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/Employee.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/Employee.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/EmployeeSalaryComparator.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/EmployeeSalaryComparator.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/EmployeeSalaryComparator.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/EmployeeSalaryComparator.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/HasColor.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/HasColor.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/HasColor.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/HasColor.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/multiinheritance/Car.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/multiinheritance/Car.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/multiinheritance/Car.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/multiinheritance/Car.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/polymorphysim/MainTestClass.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/polymorphysim/MainTestClass.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/polymorphysim/MainTestClass.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/polymorphysim/MainTestClass.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/FileManager.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/polymorphism/FileManager.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/FileManager.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/polymorphism/FileManager.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/GenericFile.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/polymorphism/GenericFile.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/GenericFile.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/polymorphism/GenericFile.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/ImageFile.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/polymorphism/ImageFile.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/ImageFile.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/polymorphism/ImageFile.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/TextFile.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/polymorphism/TextFile.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/TextFile.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/polymorphism/TextFile.java diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/superkeyword/KeywordDemo.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/superkeyword/KeywordDemo.java new file mode 100644 index 0000000000..0e5bd489bb --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/superkeyword/KeywordDemo.java @@ -0,0 +1,11 @@ +package com.baeldung.superkeyword; + +/** + * Created by Gebruiker on 5/14/2018. + */ +public class KeywordDemo { + + public static void main(String[] args) { + SuperSub child = new SuperSub("message from the child class"); + } +} diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/superkeyword/SuperBase.java similarity index 87% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/superkeyword/SuperBase.java index a5304fcef9..ec6a90cb06 100644 --- a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/superkeyword/SuperBase.java @@ -1,4 +1,4 @@ -package com.baeldung.keyword.superkeyword; +package com.baeldung.superkeyword; /** * Created by Gebruiker on 5/14/2018. diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/superkeyword/SuperSub.java similarity index 91% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/superkeyword/SuperSub.java index 83bc04ad0f..ada52e4ff2 100644 --- a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/superkeyword/SuperSub.java @@ -1,4 +1,4 @@ -package com.baeldung.keyword.superkeyword; +package com.baeldung.superkeyword; /** * Created by Gebruiker on 5/15/2018. diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/method/BaseMethodClass.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/method/BaseMethodClass.java new file mode 100644 index 0000000000..7e6b08c000 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/method/BaseMethodClass.java @@ -0,0 +1,9 @@ +package com.baeldung.variableandmethodhiding.method; + + +public class BaseMethodClass { + + public static void printMessage() { + System.out.println("base static method"); + } +} diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/method/ChildMethodClass.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/method/ChildMethodClass.java new file mode 100644 index 0000000000..30db54cd84 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/method/ChildMethodClass.java @@ -0,0 +1,9 @@ +package com.baeldung.variableandmethodhiding.method; + + +public class ChildMethodClass extends BaseMethodClass { + + public static void printMessage() { + System.out.println("child static method"); + } +} diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/method/MethodHidingDemo.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/method/MethodHidingDemo.java new file mode 100644 index 0000000000..ce1feac665 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/method/MethodHidingDemo.java @@ -0,0 +1,8 @@ +package com.baeldung.variableandmethodhiding.method; + +public class MethodHidingDemo { + + public static void main(String[] args) { + ChildMethodClass.printMessage(); + } +} diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/ChildVariable.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/ChildVariable.java similarity index 81% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/ChildVariable.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/ChildVariable.java index 5730e5e282..83434f7dd3 100644 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/ChildVariable.java +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/ChildVariable.java @@ -1,4 +1,4 @@ -package com.baeldung.scope.variable; +package com.baeldung.variableandmethodhiding.variable; /** * Created by Gebruiker on 5/7/2018. diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/HideVariable.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/HideVariable.java similarity index 89% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/HideVariable.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/HideVariable.java index 8243fdb249..98a29573b8 100644 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/HideVariable.java +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/HideVariable.java @@ -1,4 +1,4 @@ -package com.baeldung.scope.variable; +package com.baeldung.variableandmethodhiding.variable; /** * Created by Gebruiker on 5/6/2018. diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/ParentVariable.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/ParentVariable.java similarity index 80% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/ParentVariable.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/ParentVariable.java index 7f116b955e..ef17305746 100644 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/ParentVariable.java +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/ParentVariable.java @@ -1,4 +1,4 @@ -package com.baeldung.scope.variable; +package com.baeldung.variableandmethodhiding.variable; /** * Created by Gebruiker on 5/7/2018. diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/VariableHidingDemo.java similarity index 89% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java rename to core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/VariableHidingDemo.java index 1ad71bd966..0fd83ad55e 100644 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/VariableHidingDemo.java @@ -1,4 +1,4 @@ -package com.baeldung.scope.variable; +package com.baeldung.variableandmethodhiding.variable; /** * Created by Gebruiker on 5/6/2018. diff --git a/core-java-modules/core-java-lang-oop-2/src/main/resources/files/test.txt b/core-java-modules/core-java-lang-oop-inheritance/src/main/resources/files/test.txt similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/resources/files/test.txt rename to core-java-modules/core-java-lang-oop-inheritance/src/main/resources/files/test.txt diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/abstractclasses/test/LowercaseFileReaderUnitTest.java b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/abstractclasses/LowercaseFileReaderUnitTest.java similarity index 94% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/abstractclasses/test/LowercaseFileReaderUnitTest.java rename to core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/abstractclasses/LowercaseFileReaderUnitTest.java index 45e16f0d25..8e970fc0c7 100644 --- a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/abstractclasses/test/LowercaseFileReaderUnitTest.java +++ b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/abstractclasses/LowercaseFileReaderUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.abstractclasses.test; +package com.baeldung.abstractclasses; import com.baeldung.abstractclasses.filereaders.BaseFileReader; import com.baeldung.abstractclasses.filereaders.LowercaseFileReader; diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/abstractclasses/test/UppercaseFileReaderUnitTest.java b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/abstractclasses/UppercaseFileReaderUnitTest.java similarity index 94% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/abstractclasses/test/UppercaseFileReaderUnitTest.java rename to core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/abstractclasses/UppercaseFileReaderUnitTest.java index dc4df900e4..e7b83a97e6 100644 --- a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/abstractclasses/test/UppercaseFileReaderUnitTest.java +++ b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/abstractclasses/UppercaseFileReaderUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.abstractclasses.test; +package com.baeldung.abstractclasses; import com.baeldung.abstractclasses.filereaders.BaseFileReader; import com.baeldung.abstractclasses.filereaders.UppercaseFileReader; diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/casting/CastingUnitTest.java b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/casting/CastingUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/casting/CastingUnitTest.java rename to core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/casting/CastingUnitTest.java diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/inheritance/AppUnitTest.java b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/inheritance/AppUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/inheritance/AppUnitTest.java rename to core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/inheritance/AppUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/innerinterfaces/InnerInterfaceUnitTest.java b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/innerinterfaces/InnerInterfaceUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/innerinterfaces/InnerInterfaceUnitTest.java rename to core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/innerinterfaces/InnerInterfaceUnitTest.java diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java rename to core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-methods/README.md b/core-java-modules/core-java-lang-oop-methods/README.md new file mode 100644 index 0000000000..fa474c9795 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/README.md @@ -0,0 +1,9 @@ +## Core Java Lang OOP - Methods + +This module contains articles about methods in Java + +### Relevant Articles: +- [Methods in Java](https://www.baeldung.com/java-methods) +- [Method Overloading and Overriding in Java](https://www.baeldung.com/java-method-overload-override) +- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts) +- [Guide to hashCode() in Java](https://www.baeldung.com/java-hashcode) diff --git a/core-java-modules/core-java-lang-oop-methods/pom.xml b/core-java-modules/core-java-lang-oop-methods/pom.xml new file mode 100644 index 0000000000..3590b85454 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/pom.xml @@ -0,0 +1,49 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-lang-oop-methods + core-java-lang-oop-methods + jar + + + + org.projectlombok + lombok + ${lombok.version} + + + commons-lang + commons-lang + ${commons-lang.version} + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + nl.jqno.equalsverifier + equalsverifier + ${equalsverifier.version} + test + + + + + 1.18.12 + 2.6 + + 3.10.0 + 3.0.3 + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/Money.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/Money.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/Money.java rename to core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/Money.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/Team.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/Team.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/Team.java rename to core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/Team.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/Voucher.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/Voucher.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/Voucher.java rename to core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/Voucher.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/WrongTeam.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/WrongTeam.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/WrongTeam.java rename to core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/WrongTeam.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java rename to core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/apachecommons/User.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/apachecommons/User.java new file mode 100644 index 0000000000..4be082019a --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/apachecommons/User.java @@ -0,0 +1,42 @@ +package com.baeldung.hashcode.apachecommons; + +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class User { + + private final Logger logger = LoggerFactory.getLogger(User.class); + private long id; + private String name; + private String email; + + public User(long id, String name, String email) { + this.id = id; + this.name = name; + this.email = email; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null) + return false; + if (this.getClass() != o.getClass()) + return false; + User user = (User) o; + return id == user.id && (name.equals(user.name) && email.equals(user.email)); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(17, 37). + append(id). + append(name). + append(email). + toHashCode(); + } + // getters and setters here + +} diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/eclipse/User.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/eclipse/User.java new file mode 100644 index 0000000000..e852eef96e --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/eclipse/User.java @@ -0,0 +1,42 @@ +package com.baeldung.hashcode.eclipse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class User { + + private final Logger logger = LoggerFactory.getLogger(User.class); + private long id; + private String name; + private String email; + + public User(long id, String name, String email) { + this.id = id; + this.name = name; + this.email = email; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null) + return false; + if (this.getClass() != o.getClass()) + return false; + User user = (User) o; + return id == user.id && (name.equals(user.name) && email.equals(user.email)); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.hashCode()); + result = prime * result + (int) (id ^ (id >>> 32)); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + // getters and setters here + +} diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/improved/User.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/improved/User.java new file mode 100644 index 0000000000..773a2c7e45 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/improved/User.java @@ -0,0 +1,37 @@ +package com.baeldung.hashcode.improved; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class User { + + private final Logger logger = LoggerFactory.getLogger(User.class); + private long id; + private String name; + private String email; + + public User(long id, String name, String email) { + this.id = id; + this.name = name; + this.email = email; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null) + return false; + if (this.getClass() != o.getClass()) + return false; + User user = (User) o; + return id == user.id && (name.equals(user.name) && email.equals(user.email)); + } + + @Override + public int hashCode() { + return (int) id * name.hashCode() * email.hashCode(); + } + // getters and setters here + +} diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/intellij/User.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/intellij/User.java new file mode 100644 index 0000000000..f7bf1ab735 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/intellij/User.java @@ -0,0 +1,40 @@ +package com.baeldung.hashcode.intellij; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class User { + + private final Logger logger = LoggerFactory.getLogger(User.class); + private long id; + private String name; + private String email; + + public User(long id, String name, String email) { + this.id = id; + this.name = name; + this.email = email; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null) + return false; + if (this.getClass() != o.getClass()) + return false; + User user = (User) o; + return id == user.id && (name.equals(user.name) && email.equals(user.email)); + } + + @Override + public int hashCode() { + int result = (int) (id ^ (id >>> 32)); + result = 31 * result + name.hashCode(); + result = 31 * result + email.hashCode(); + return result; + } + // getters and setters here + +} diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/lombok/User.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/lombok/User.java new file mode 100644 index 0000000000..e34246ce24 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/lombok/User.java @@ -0,0 +1,22 @@ +package com.baeldung.hashcode.lombok; + +import lombok.EqualsAndHashCode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@EqualsAndHashCode +public class User { + + private final Logger logger = LoggerFactory.getLogger(User.class); + private long id; + private String name; + private String email; + + public User(long id, String name, String email) { + this.id = id; + this.name = name; + this.email = email; + } + // getters and setters here + +} diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/naive/User.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/naive/User.java new file mode 100644 index 0000000000..b0a33ad3e9 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/naive/User.java @@ -0,0 +1,37 @@ +package com.baeldung.hashcode.naive; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class User { + + private final Logger logger = LoggerFactory.getLogger(User.class); + private long id; + private String name; + private String email; + + public User(long id, String name, String email) { + this.id = id; + this.name = name; + this.email = email; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null) + return false; + if (this.getClass() != o.getClass()) + return false; + User user = (User) o; + return id == user.id && (name.equals(user.name) && email.equals(user.email)); + } + + @Override + public int hashCode() { + return 1; + } + // getters and setters here + +} diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/standard/User.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/standard/User.java new file mode 100644 index 0000000000..f8fd5cedbd --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/hashcode/standard/User.java @@ -0,0 +1,41 @@ +package com.baeldung.hashcode.standard; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class User { + + private final Logger logger = LoggerFactory.getLogger(User.class); + private long id; + private String name; + private String email; + + public User(long id, String name, String email) { + this.id = id; + this.name = name; + this.email = email; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null) + return false; + if (this.getClass() != o.getClass()) + return false; + User user = (User) o; + return id == user.id && (name.equals(user.name) && email.equals(user.email)); + } + + @Override + public int hashCode() { + int hash = 7; + hash = 31 * hash + (int) id; + hash = 31 * hash + (name == null ? 0 : name.hashCode()); + hash = 31 * hash + (email == null ? 0 : email.hashCode()); + return hash; + } + // getters and setters here + +} diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/application/Application.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methodoverloadingoverriding/application/Application.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/application/Application.java rename to core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methodoverloadingoverriding/application/Application.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/model/Car.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methodoverloadingoverriding/model/Car.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/model/Car.java rename to core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methodoverloadingoverriding/model/Car.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/model/Vehicle.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methodoverloadingoverriding/model/Vehicle.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/model/Vehicle.java rename to core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methodoverloadingoverriding/model/Vehicle.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/util/Multiplier.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methodoverloadingoverriding/util/Multiplier.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/util/Multiplier.java rename to core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methodoverloadingoverriding/util/Multiplier.java diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/PersonName.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/PersonName.java new file mode 100644 index 0000000000..d1f3f58b8c --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/PersonName.java @@ -0,0 +1,37 @@ +package com.baeldung.methods; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; + +public class PersonName { + + public String getName(String firstName, String lastName) throws RuntimeException { + return firstName + " " + lastName; + } + + public String getName(String firstName, String middleName, String lastName) { + if (!middleName.equals("")) { + return firstName + " " + lastName; + } + return firstName + " " + middleName + " " + lastName; + } + + public void printFullName(String firstName, String lastName) { + System.out.println(firstName + " " + lastName); + } + + public void writeName(String name) throws IOException { + PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt")); + out.println("Name: " + name); + out.close(); + } + + public static String getNameStatic(String firstName, String lastName) { + return firstName + " " + lastName; + } + + public static void callToStaticMethod() { + System.out.println("Name is: " + PersonName.getNameStatic("Alan", "Turing")); + } +} diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java rename to core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java similarity index 96% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java rename to core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java index 7dfc6d47a3..308004452b 100644 --- a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java +++ b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java @@ -38,7 +38,7 @@ public class TeamUnitTest { } @Test - public void equalsContract() { + public void equalsHashCodeContracts() { EqualsVerifier.forClass(Team.class).verify(); } diff --git a/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/hashcode/UserUnitTest.java b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/hashcode/UserUnitTest.java new file mode 100644 index 0000000000..51475acabf --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/hashcode/UserUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.hashcode; + +import com.baeldung.hashcode.standard.User; +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-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java new file mode 100644 index 0000000000..18b2d4d570 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.hashcode.application; + +import com.baeldung.hashcode.standard.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-modules/core-java-lang-oop/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverloadingUnitTest.java b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methodoverloadingoverriding/MethodOverloadingUnitTest.java similarity index 95% rename from core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverloadingUnitTest.java rename to core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methodoverloadingoverriding/MethodOverloadingUnitTest.java index 081a30c34a..476e70618f 100644 --- a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverloadingUnitTest.java +++ b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methodoverloadingoverriding/MethodOverloadingUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.methodoverloadingoverriding.test; +package com.baeldung.methodoverloadingoverriding; import com.baeldung.methodoverloadingoverriding.util.Multiplier; import org.junit.BeforeClass; diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverridingUnitTest.java b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methodoverloadingoverriding/MethodOverridingUnitTest.java similarity index 97% rename from core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverridingUnitTest.java rename to core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methodoverloadingoverriding/MethodOverridingUnitTest.java index 554ac121bc..f4142d7382 100644 --- a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverridingUnitTest.java +++ b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methodoverloadingoverriding/MethodOverridingUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.methodoverloadingoverriding.test; +package com.baeldung.methodoverloadingoverriding; import com.baeldung.methodoverloadingoverriding.model.Car; import com.baeldung.methodoverloadingoverriding.model.Vehicle; diff --git a/core-java-modules/core-java-lang-oop-modifiers/README.md b/core-java-modules/core-java-lang-oop-modifiers/README.md new file mode 100644 index 0000000000..eef905fa0e --- /dev/null +++ b/core-java-modules/core-java-lang-oop-modifiers/README.md @@ -0,0 +1,12 @@ +## Core Java Lang OOP - Modifiers + +This module contains articles about modifiers in Java + +### Relevant Articles: +- [Access Modifiers in Java](https://www.baeldung.com/java-access-modifiers) +- [Java ‘public’ Access Modifier](https://www.baeldung.com/java-public-keyword) +- [Java ‘private’ Access Modifier](https://www.baeldung.com/java-private-keyword) +- [The “final” Keyword in Java](https://www.baeldung.com/java-final) +- [A Guide to the Static Keyword in Java](https://www.baeldung.com/java-static) +- [Static and Default Methods in Interfaces in Java](https://www.baeldung.com/java-static-default-methods) +- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp) \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-modifiers/pom.xml b/core-java-modules/core-java-lang-oop-modifiers/pom.xml new file mode 100644 index 0000000000..615e20690f --- /dev/null +++ b/core-java-modules/core-java-lang-oop-modifiers/pom.xml @@ -0,0 +1,34 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-lang-oop-modifiers + core-java-lang-oop-modifiers + jar + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + test + + + + + 3.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/Public.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/Public.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/Public.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/Public.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/SubClass.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/SubClass.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/SubClass.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/SubClass.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/application/Application.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/application/Application.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/application/Application.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/application/Application.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Alarm.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Alarm.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Alarm.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Alarm.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Car.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Car.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Car.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Car.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Motorbike.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Motorbike.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Motorbike.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Motorbike.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/MultiAlarmCar.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/MultiAlarmCar.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/MultiAlarmCar.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/MultiAlarmCar.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Vehicle.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Vehicle.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Vehicle.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Vehicle.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/BlackCat.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/finalkeyword/BlackCat.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/BlackCat.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/finalkeyword/BlackCat.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/BlackDog.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/finalkeyword/BlackDog.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/BlackDog.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/finalkeyword/BlackDog.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/Cat.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/finalkeyword/Cat.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/Cat.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/finalkeyword/Cat.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/Dog.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/finalkeyword/Dog.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/Dog.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/finalkeyword/Dog.java diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/privatemodifier/Employee.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/privatemodifier/Employee.java new file mode 100644 index 0000000000..a0f7829d51 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/privatemodifier/Employee.java @@ -0,0 +1,59 @@ +package com.baeldung.privatemodifier; + +public class Employee { + + private String privateId; + private String name; + private boolean manager; + + public Employee(String id, String name) { + setPrivateId(id); + setName(name); + } + + private Employee(String id, String name, boolean managerAttribute) { + this.privateId = id; + this.name = name; + this.privateId = id + "_ID-MANAGER"; + } + + public void setPrivateId(String customId) { + if (customId.endsWith("_ID")) { + this.privateId = customId; + } else { + this.privateId = customId + "_ID"; + } + } + + public String getPrivateId() { + return privateId; + } + + public boolean isManager() { + return manager; + } + + public void elevateToManager() { + if ("Carl".equals(this.name)) { + setManager(true); + } + } + + private void setManager(boolean manager) { + this.manager = manager; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public static Employee buildManager(String id, String name) { + return new Employee(id, name, true); + } + +} diff --git a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/core/privatemodifier/ExampleClass.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/privatemodifier/ExampleClass.java similarity index 84% rename from core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/core/privatemodifier/ExampleClass.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/privatemodifier/ExampleClass.java index 8659b4ad9c..c87980fbe8 100644 --- a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/core/privatemodifier/ExampleClass.java +++ b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/privatemodifier/ExampleClass.java @@ -1,4 +1,4 @@ -package com.baeldung.core.privatemodifier; +package com.baeldung.privatemodifier; public class ExampleClass { diff --git a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/core/privatemodifier/PublicOuterClass.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/privatemodifier/PublicOuterClass.java similarity index 90% rename from core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/core/privatemodifier/PublicOuterClass.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/privatemodifier/PublicOuterClass.java index 8a9e8a8eb3..082d08b034 100644 --- a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/core/privatemodifier/PublicOuterClass.java +++ b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/privatemodifier/PublicOuterClass.java @@ -1,4 +1,4 @@ -package com.baeldung.core.privatemodifier; +package com.baeldung.privatemodifier; public class PublicOuterClass { diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/publicmodifier/ListOfThree.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/publicmodifier/ListOfThree.java similarity index 92% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/publicmodifier/ListOfThree.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/publicmodifier/ListOfThree.java index 2ded0ba5d3..0e3449f451 100644 --- a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/accessmodifiers/publicmodifier/ListOfThree.java +++ b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/publicmodifier/ListOfThree.java @@ -1,4 +1,4 @@ -package com.baeldung.accessmodifiers.publicmodifier; +package com.baeldung.publicmodifier; import java.util.AbstractList; import java.util.Arrays; diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/publicmodifier/SpecialCharacters.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/publicmodifier/SpecialCharacters.java new file mode 100644 index 0000000000..633308e707 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/publicmodifier/SpecialCharacters.java @@ -0,0 +1,7 @@ +package com.baeldung.publicmodifier; + +public class SpecialCharacters { + + public static final String SLASH = "/"; + +} diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/publicmodifier/Student.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/publicmodifier/Student.java new file mode 100644 index 0000000000..5aa80286bf --- /dev/null +++ b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/publicmodifier/Student.java @@ -0,0 +1,67 @@ +package com.baeldung.publicmodifier; + +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Date; + +public class Student { + + private StudentGrade grade; //new data representation +// private int grade; //old data representation + private String name; + private int age; + + public void setGrade(int grade) { + this.grade = new StudentGrade(grade); + } + + public int getGrade() { + return this.grade.getGrade().intValue(); //int is returned for backward compatibility + } + + public Connection getConnection() throws SQLException { + + final String URL = "jdbc:h2:~/test"; + return DriverManager.getConnection(URL, "sa", ""); + + } + + public void setAge(int age) { + if (age < 0 || age > 150) { + throw new IllegalArgumentException(); + } + + this.age = age; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return this.name; + } + + private class StudentGrade { + private BigDecimal grade = BigDecimal.ZERO; + private Date updatedAt; + + public StudentGrade(int grade) { + this.grade = new BigDecimal(grade); + this.updatedAt = new Date(); + } + + public BigDecimal getGrade() { + return grade; + } + + public Date getDate() { + return updatedAt; + } + + } + +} diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Car.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Car.java new file mode 100644 index 0000000000..950f008dcd --- /dev/null +++ b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Car.java @@ -0,0 +1,48 @@ +package com.baeldung.staticmodifier; + +/** + * This class demonstrates the use of static fields and static methods + * the instance variables engine and displacement are distinct for + * each and every object whereas static/class variable numberOfCars + * is unique and is shared across all objects of this class. + * + * @author baeldung + * + */ +public class Car { + private String name; + private String engine; + + public static int numberOfCars; + + public Car(String name, String engine) { + this.name = name; + this.engine = engine; + numberOfCars++; + } + + //getters and setters + public static int getNumberOfCars() { + return numberOfCars; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEngine() { + return engine; + } + + public void setEngine(String engine) { + this.engine = engine; + } + + public static void setNumberOfCars(int numberOfCars) { + Car.numberOfCars = numberOfCars; + } +} diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/Singleton.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Singleton.java similarity index 88% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/Singleton.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Singleton.java index de75af9d9d..6e7dcf7c60 100644 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/Singleton.java +++ b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Singleton.java @@ -1,4 +1,4 @@ -package com.baeldung.staticdemo; +package com.baeldung.staticmodifier; public class Singleton { private Singleton() {} diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/StaticBlockDemo.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/StaticBlockDemo.java new file mode 100644 index 0000000000..637bb5e82a --- /dev/null +++ b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/StaticBlockDemo.java @@ -0,0 +1,28 @@ +package com.baeldung.staticmodifier; + +import java.util.LinkedList; +import java.util.List; + +public class StaticBlockDemo { + private static List ranks = new LinkedList<>(); + + static { + ranks.add("Lieutenant"); + ranks.add("Captain"); + ranks.add("Major"); + } + + static { + ranks.add("Colonel"); + ranks.add("General"); + } + + //getters and setters + public static List getRanks() { + return ranks; + } + + public static void setRanks(List ranks) { + StaticBlockDemo.ranks = ranks; + } +} diff --git a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/strictfpUsage/Circle.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/strictfpUsage/Circle.java similarity index 100% rename from core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/strictfpUsage/Circle.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/strictfpUsage/Circle.java diff --git a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/strictfpUsage/ScientificCalculator.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/strictfpUsage/ScientificCalculator.java similarity index 100% rename from core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/strictfpUsage/ScientificCalculator.java rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/strictfpUsage/ScientificCalculator.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/defaultistaticinterfacemethods/test/StaticDefaulInterfaceMethodUnitTest.java b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/defaultstaticinterfacemethods/StaticDefaulInterfaceMethodUnitTest.java similarity index 97% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/defaultistaticinterfacemethods/test/StaticDefaulInterfaceMethodUnitTest.java rename to core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/defaultstaticinterfacemethods/StaticDefaulInterfaceMethodUnitTest.java index 7d4b06908a..0dffe8f80e 100644 --- a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/defaultistaticinterfacemethods/test/StaticDefaulInterfaceMethodUnitTest.java +++ b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/defaultstaticinterfacemethods/StaticDefaulInterfaceMethodUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.defaultistaticinterfacemethods.test; +package com.baeldung.defaultstaticinterfacemethods; import com.baeldung.defaultstaticinterfacemethods.model.Car; import com.baeldung.defaultstaticinterfacemethods.model.Motorbike; diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/finalkeyword/FinalUnitTest.java b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/finalkeyword/FinalUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/finalkeyword/FinalUnitTest.java rename to core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/finalkeyword/FinalUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/accessmodifiers/PublicAccessModifierUnitTest.java b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/publicmodifier/PublicAccessModifierUnitTest.java similarity index 94% rename from core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/accessmodifiers/PublicAccessModifierUnitTest.java rename to core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/publicmodifier/PublicAccessModifierUnitTest.java index ed8fb4f45a..8c014e703b 100644 --- a/core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/accessmodifiers/PublicAccessModifierUnitTest.java +++ b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/publicmodifier/PublicAccessModifierUnitTest.java @@ -1,7 +1,5 @@ -package com.baeldung.accessmodifiers; +package com.baeldung.publicmodifier; -import com.baeldung.accessmodifiers.publicmodifier.ListOfThree; -import com.baeldung.accessmodifiers.publicmodifier.Student; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/CarUnitTest.java b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/CarUnitTest.java new file mode 100644 index 0000000000..f55955caa8 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/CarUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.staticmodifier; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class CarUnitTest { + @Test + public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() { + new Car("Jaguar", "V8"); + new Car("Bugatti", "W16"); + assertEquals(2, Car.numberOfCars); + } +} diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/SingletonUnitTest.java b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/SingletonUnitTest.java new file mode 100644 index 0000000000..6371fd4961 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/SingletonUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.staticmodifier; + +import org.junit.Assert; +import org.junit.Test; + +public class SingletonUnitTest { + + @Test + public void givenStaticInnerClass_whenMultipleTimesInstanceCalled_thenOnlyOneTimeInitialized() { + Singleton object1 = Singleton.getInstance(); + Singleton object2 = Singleton.getInstance(); + + Assert.assertSame(object1, object2); + } +} diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/StaticBlockDemoUnitTest.java b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/StaticBlockDemoUnitTest.java new file mode 100644 index 0000000000..f31a8e8895 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/StaticBlockDemoUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.staticmodifier; + +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.junit.Test; + +public class StaticBlockDemoUnitTest { + + @Test + public void whenAddedListElementsThroughStaticBlock_thenEnsureCorrectOrder() { + List actualList = StaticBlockDemo.getRanks(); + assertThat(actualList, contains("Lieutenant", "Captain", "Major", "Colonel", "General")); + } +} diff --git a/core-java-modules/core-java-lang-oop-4/src/test/java/com/baeldung/strictfpUsage/ScientificCalculatorUnitTest.java b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/strictfpUsage/ScientificCalculatorUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-4/src/test/java/com/baeldung/strictfpUsage/ScientificCalculatorUnitTest.java rename to core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/strictfpUsage/ScientificCalculatorUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-others/README.md b/core-java-modules/core-java-lang-oop-others/README.md new file mode 100644 index 0000000000..d3909c0014 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/README.md @@ -0,0 +1,8 @@ +## Core Java Lang OOP - Others + +This module contains articles about Object Oriented Programming (OOP) in Java + +### Relevant Articles: +- [Object-Oriented-Programming Concepts in Java](https://www.baeldung.com/java-oop) +- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding) +- [Pass-By-Value as a Parameter Passing Mechanism in Java](https://www.baeldung.com/java-pass-by-value-or-pass-by-reference) diff --git a/core-java-modules/core-java-lang-oop-others/pom.xml b/core-java-modules/core-java-lang-oop-others/pom.xml new file mode 100644 index 0000000000..8eab301748 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/pom.xml @@ -0,0 +1,16 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-lang-oop-others + core-java-lang-oop-others + jar + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/binding/Animal.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/binding/Animal.java similarity index 100% rename from core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/binding/Animal.java rename to core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/binding/Animal.java diff --git a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/binding/AnimalActivity.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/binding/AnimalActivity.java similarity index 90% rename from core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/binding/AnimalActivity.java rename to core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/binding/AnimalActivity.java index 1bd36123e3..a30c3acd00 100644 --- a/core-java-modules/core-java-lang-oop-4/src/main/java/com/baeldung/binding/AnimalActivity.java +++ b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/binding/AnimalActivity.java @@ -15,7 +15,7 @@ public class AnimalActivity { logger.info("Animal is sleeping"); } - public static void sleep(Cat cat) { + public static void sleep(Dog dog) { logger.info("Cat is sleeping"); } @@ -30,7 +30,7 @@ public class AnimalActivity { //assigning a dog object to reference of type Animal - Animal catAnimal = new Cat(); + Animal catAnimal = new Dog(); catAnimal.makeNoise(); diff --git a/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/binding/Dog.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/binding/Dog.java new file mode 100644 index 0000000000..b6924569d0 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/binding/Dog.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 Dog extends Animal { + + final static Logger logger = LoggerFactory.getLogger(Dog.class); + + public void makeNoise() { + + logger.info("meow"); + } + +} diff --git a/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/ArmoredCar.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/ArmoredCar.java new file mode 100644 index 0000000000..29cba3702a --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/ArmoredCar.java @@ -0,0 +1,13 @@ +package com.baeldung.oop; + +public class ArmoredCar extends Car { + private int bulletProofWindows; + + public ArmoredCar(String type, String model, String color) { + super(type, model, color); + } + + public void remoteStartCar() { + // this vehicle can be started by using a remote control + } +} diff --git a/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/Car.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/Car.java new file mode 100644 index 0000000000..8ea4d779b6 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/Car.java @@ -0,0 +1,58 @@ +package com.baeldung.oop; + +public class Car extends Vehicle { + + private String type; + private String color; + private int speed; + private int numberOfGears; + + public Car(String type, String model, String color) { + super(4, model); + this.type = type; + this.color = color; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public int getSpeed() { + return speed; + } + + public void setSpeed(int speed) { + this.speed = speed; + } + + public int increaseSpeed(int increment) { + if (increment > 0) { + this.speed += increment; + } else { + System.out.println("Increment can't be negative."); + } + return this.speed; + } + + public int decreaseSpeed(int decrement) { + if (decrement > 0 && decrement <= this.speed) { + this.speed -= decrement; + } else { + System.out.println("Decrement can't be negative or greater than current speed."); + } + return this.speed; + } + + public void openDoors() { + // process to open the doors + } + + @Override + public void honk() { + // produces car-specific honk + } +} diff --git a/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/GenericFile.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/GenericFile.java new file mode 100644 index 0000000000..812a3f1d63 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/GenericFile.java @@ -0,0 +1,63 @@ +package com.baeldung.oop; + +import java.util.Date; + +public class GenericFile { + private String name; + private String extension; + private Date dateCreated; + private String version; + private byte[] content; + + public GenericFile() { + this.setDateCreated(new Date()); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public Date getDateCreated() { + return dateCreated; + } + + public void setDateCreated(Date dateCreated) { + this.dateCreated = dateCreated; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public byte[] getContent() { + return content; + } + + public void setContent(byte[] content) { + this.content = content; + } + + public String getFileInfo() { + return "Generic File Impl"; + } + + public Object read() { + return content; + } +} diff --git a/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/ImageFile.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/ImageFile.java new file mode 100644 index 0000000000..2e2b9b4129 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/ImageFile.java @@ -0,0 +1,41 @@ +package com.baeldung.oop; + +public class ImageFile extends GenericFile { + private int height; + private int width; + + public ImageFile(String name, int height, int width, byte[] content, String version) { + this.setHeight(height); + this.setWidth(width); + this.setContent(content); + this.setName(name); + this.setVersion(version); + this.setExtension(".jpg"); + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + + public String getFileInfo() { + return "Image File Impl"; + } + + public String read() { + return this.getContent() + .toString(); + } + +} diff --git a/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/TextFile.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/TextFile.java new file mode 100644 index 0000000000..0d7b8e4192 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/TextFile.java @@ -0,0 +1,44 @@ +package com.baeldung.oop; + +public class TextFile extends GenericFile { + private int wordCount; + + public TextFile(String name, String content, String version) { + String[] words = content.split(" "); + this.setWordCount(words.length > 0 ? words.length : 1); + this.setContent(content.getBytes()); + this.setName(name); + this.setVersion(version); + this.setExtension(".txt"); + } + + public int getWordCount() { + return wordCount; + } + + public void setWordCount(int wordCount) { + this.wordCount = wordCount; + } + + public String getFileInfo() { + return "Text File Impl"; + } + + public String read() { + return this.getContent() + .toString(); + } + + public String read(int limit) { + return this.getContent() + .toString() + .substring(0, limit); + } + + public String read(int start, int stop) { + return this.getContent() + .toString() + .substring(start, stop); + } + +} diff --git a/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/Vehicle.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/Vehicle.java new file mode 100644 index 0000000000..d5ef05bc31 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/oop/Vehicle.java @@ -0,0 +1,23 @@ +package com.baeldung.oop; + +public class Vehicle { + private int wheels; + private String model; + + public Vehicle(int wheels, String model) { + this.wheels = wheels; + this.model = model; + } + + public void start() { + // the process of starting the vehicle + } + + public void stop() { + // process to stop the vehicle + } + + public void honk() { + // produces a default honk + } +} diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java rename to core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/parameterpassing/Primitives.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/parameterpassing/Primitives.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/parameterpassing/Primitives.java rename to core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/parameterpassing/Primitives.java diff --git a/core-java-modules/core-java-lang-oop-4/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java b/core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java similarity index 96% rename from core-java-modules/core-java-lang-oop-4/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java rename to core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java index 41c67ff389..6ef9b51818 100644 --- a/core-java-modules/core-java-lang-oop-4/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java +++ b/core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java @@ -62,9 +62,9 @@ public class AnimalActivityUnitTest { @Test public void givenDogReference__whenRefersCatObject_shouldCallFunctionWithAnimalParam() { - Cat cat = new Cat(); + Dog dog = new Dog(); - AnimalActivity.sleep(cat); + AnimalActivity.sleep(dog); verify(mockAppender).doAppend(captorLoggingEvent.capture()); @@ -79,7 +79,7 @@ public class AnimalActivityUnitTest { @Test public void givenAnimaReference__whenRefersDogObject_shouldCallFunctionWithAnimalParam() { - Animal cat = new Cat(); + Animal cat = new Dog(); AnimalActivity.sleep(cat); diff --git a/core-java-modules/core-java-lang-oop-4/src/test/java/com/baeldung/binding/AnimalUnitTest.java b/core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/binding/AnimalUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-4/src/test/java/com/baeldung/binding/AnimalUnitTest.java rename to core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/binding/AnimalUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/binding/DogUnitTest.java b/core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/binding/DogUnitTest.java new file mode 100644 index 0000000000..977c5d65e6 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/binding/DogUnitTest.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 DogUnitTest { + + @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() { + + Dog dog = new Dog(); + + dog.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-modules/core-java-lang-oop-3/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java b/core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java rename to core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java b/core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java rename to core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-patterns/README.md b/core-java-modules/core-java-lang-oop-patterns/README.md new file mode 100644 index 0000000000..178a556a96 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/README.md @@ -0,0 +1,9 @@ +## Core Java Lang OOP - Patterns + +This module contains articles about Object-oriented programming (OOP) patterns in Java + +### Relevant Articles: +- [Composition, Aggregation, and Association in Java](https://www.baeldung.com/java-composition-aggregation-association) +- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](https://www.baeldung.com/java-inheritance-composition) +- [Immutable Objects in Java](https://www.baeldung.com/java-immutable-object) +- [How to Make a Deep Copy of an Object in Java](https://www.baeldung.com/java-deep-copy) diff --git a/core-java-modules/core-java-lang-oop-patterns/pom.xml b/core-java-modules/core-java-lang-oop-patterns/pom.xml new file mode 100644 index 0000000000..0102ef2653 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/pom.xml @@ -0,0 +1,45 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-lang-oop-patterns + core-java-lang-oop-patterns + jar + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.google.code.gson + gson + ${gson.version} + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + 2.8.2 + 3.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/deepcopy/Address.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/deepcopy/Address.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/deepcopy/Address.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/deepcopy/Address.java diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/deepcopy/User.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/deepcopy/User.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/deepcopy/User.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/deepcopy/User.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/immutableobjects/Currency.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/immutableobjects/Currency.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/immutableobjects/Currency.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/immutableobjects/Currency.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/immutableobjects/Money.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/immutableobjects/Money.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/immutableobjects/Money.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/immutableobjects/Money.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/application/Application.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/application/Application.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/application/Application.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/application/Application.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Actress.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Actress.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Actress.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Actress.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Computer.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Computer.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Computer.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Computer.java diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/ComputerBuilder.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/ComputerBuilder.java new file mode 100644 index 0000000000..4d8574e93f --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/ComputerBuilder.java @@ -0,0 +1,13 @@ +package com.baeldung.inheritancecomposition.model; + +public abstract class ComputerBuilder { + + public final void buildComputer() { + addProcessor(); + addMemory(); + } + + public abstract void addProcessor(); + + public abstract void addMemory(); +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Memory.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Memory.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Memory.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Memory.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Person.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Person.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Person.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Person.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Processor.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Processor.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Processor.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Processor.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/SoundCard.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/SoundCard.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/SoundCard.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/SoundCard.java diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/StandardComputerBuilder.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/StandardComputerBuilder.java new file mode 100644 index 0000000000..76c4732ace --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/StandardComputerBuilder.java @@ -0,0 +1,13 @@ +package com.baeldung.inheritancecomposition.model; + +public class StandardComputerBuilder extends ComputerBuilder { + @Override + public void addProcessor() { + // method implementation + } + + @Override + public void addMemory() { + // method implementation + } +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/StandardMemory.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/StandardMemory.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/StandardMemory.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/StandardMemory.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/StandardProcessor.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/StandardProcessor.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/StandardProcessor.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/StandardProcessor.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/StandardSoundCard.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/StandardSoundCard.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/StandardSoundCard.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/StandardSoundCard.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Waitress.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Waitress.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/inheritancecomposition/model/Waitress.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/inheritancecomposition/model/Waitress.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/aggregation/Car.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/aggregation/Car.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/aggregation/Car.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/aggregation/Car.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/aggregation/Wheel.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/aggregation/Wheel.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/aggregation/Wheel.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/aggregation/Wheel.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/association/Child.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/association/Child.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/association/Child.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/association/Child.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/association/Mother.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/association/Mother.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/association/Mother.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/association/Mother.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/composition/Building.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/composition/Building.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/composition/Building.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/composition/Building.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/university/Department.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/university/Department.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/university/Department.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/university/Department.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/university/Professor.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/university/Professor.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/university/Professor.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/university/Professor.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/university/University.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/university/University.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/relationships/university/University.java rename to core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/relationships/university/University.java diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/deepcopy/DeepCopyUnitTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/deepcopy/DeepCopyUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/deepcopy/DeepCopyUnitTest.java rename to core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/deepcopy/DeepCopyUnitTest.java diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/deepcopy/ShallowCopyUnitTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/deepcopy/ShallowCopyUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/deepcopy/ShallowCopyUnitTest.java rename to core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/deepcopy/ShallowCopyUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java rename to core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/inheritancecomposition/ActressUnitTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/inheritancecomposition/ActressUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/inheritancecomposition/ActressUnitTest.java rename to core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/inheritancecomposition/ActressUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/inheritancecomposition/CompositionUnitTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/inheritancecomposition/CompositionUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/inheritancecomposition/CompositionUnitTest.java rename to core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/inheritancecomposition/CompositionUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/inheritancecomposition/InheritanceUnitTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/inheritancecomposition/InheritanceUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/inheritancecomposition/InheritanceUnitTest.java rename to core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/inheritancecomposition/InheritanceUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/inheritancecomposition/PersonUnitTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/inheritancecomposition/PersonUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/inheritancecomposition/PersonUnitTest.java rename to core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/inheritancecomposition/PersonUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/inheritancecomposition/WaitressUnitTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/inheritancecomposition/WaitressUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/inheritancecomposition/WaitressUnitTest.java rename to core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/inheritancecomposition/WaitressUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-types/README.md b/core-java-modules/core-java-lang-oop-types/README.md new file mode 100644 index 0000000000..80344c70fa --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types/README.md @@ -0,0 +1,9 @@ +## Core Java Lang OOP - Types + +This module contains articles about types in Java + +### Relevant Articles: +- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects) +- [Guide to the this Java Keyword](https://www.baeldung.com/java-this) +- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes) +- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces) diff --git a/core-java-modules/core-java-lang-oop-types/pom.xml b/core-java-modules/core-java-lang-oop-types/pom.xml new file mode 100644 index 0000000000..f73434a9ff --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types/pom.xml @@ -0,0 +1,15 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-lang-oop-types + core-java-lang-oop-types + jar + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/markerinterface/DeletableShape.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/markerinterface/DeletableShape.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/markerinterface/DeletableShape.java rename to core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/markerinterface/DeletableShape.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/markerinterface/Rectangle.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/markerinterface/Rectangle.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/markerinterface/Rectangle.java rename to core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/markerinterface/Rectangle.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/markerinterface/Shape.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/markerinterface/Shape.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/markerinterface/Shape.java rename to core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/markerinterface/Shape.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/markerinterface/ShapeDao.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/markerinterface/ShapeDao.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/markerinterface/ShapeDao.java rename to core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/markerinterface/ShapeDao.java diff --git a/core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/objects/Car.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/objects/Car.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/main/java/com/baeldung/objects/Car.java rename to core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/objects/Car.java diff --git a/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/thiskeyword/Keyword.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/thiskeyword/Keyword.java new file mode 100644 index 0000000000..a09a1ac8e1 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/thiskeyword/Keyword.java @@ -0,0 +1,49 @@ +package com.baeldung.thiskeyword; + +public class Keyword { + + private String name; + private int age; + + public Keyword() { + this("John", 27); + this.printMessage(); + printInstance(this); + } + + public Keyword(String name, int age) { + this.name = name; + this.age = age; + } + + public void printMessage() { + System.out.println("invoked by this"); + } + + public void printInstance(Keyword thisKeyword) { + System.out.println(thisKeyword); + } + + public Keyword getCurrentInstance() { + return this; + } + + class ThisInnerClass { + + boolean isInnerClass = true; + + public ThisInnerClass() { + Keyword thisKeyword = Keyword.this; + String outerString = Keyword.this.name; + System.out.println(this.isInnerClass); + } + } + + @Override + public String toString() { + return "KeywordTest{" + + "name='" + name + '\'' + + ", age=" + age + + '}'; + } +} diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/markerinterface/MarkerInterfaceUnitTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/markerinterface/MarkerInterfaceUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/markerinterface/MarkerInterfaceUnitTest.java rename to core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/markerinterface/MarkerInterfaceUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/nestedclass/AnonymousInnerUnitTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/nestedclass/AnonymousInnerUnitTest.java new file mode 100644 index 0000000000..98917b9e05 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/nestedclass/AnonymousInnerUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.nestedclass; + +import org.junit.Test; + +abstract class SimpleAbstractClass { + abstract void run(); +} + +public class AnonymousInnerUnitTest { + + @Test + public void run() { + SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() { + void run() { + System.out.println("Running Anonymous Class..."); + } + }; + simpleAbstractClass.run(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/nestedclass/Enclosing.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/nestedclass/Enclosing.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/nestedclass/Enclosing.java rename to core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/nestedclass/Enclosing.java diff --git a/core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/nestedclass/NewEnclosing.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/nestedclass/NewEnclosing.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/nestedclass/NewEnclosing.java rename to core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/nestedclass/NewEnclosing.java diff --git a/core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/nestedclass/NewOuter.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/nestedclass/NewOuter.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/nestedclass/NewOuter.java rename to core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/nestedclass/NewOuter.java diff --git a/core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/nestedclass/Outer.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/nestedclass/Outer.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/nestedclass/Outer.java rename to core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/nestedclass/Outer.java diff --git a/core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/objects/ObjectsUnitTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/objects/ObjectsUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-3/src/test/java/com/baeldung/objects/ObjectsUnitTest.java rename to core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/objects/ObjectsUnitTest.java diff --git a/core-java-modules/core-java-lang-oop/.gitignore b/core-java-modules/core-java-lang-oop/.gitignore deleted file mode 100644 index 3de4cc647e..0000000000 --- a/core-java-modules/core-java-lang-oop/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -*.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-modules/core-java-lang-oop/README.md b/core-java-modules/core-java-lang-oop/README.md deleted file mode 100644 index 0fb044138d..0000000000 --- a/core-java-modules/core-java-lang-oop/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Core Java Lang OOP - -This module contains articles about Object-oriented programming (OOP) in Java - -### Relevant Articles: -- [Guide to hashCode() in Java](https://www.baeldung.com/java-hashcode) -- [A Guide to the Static Keyword in Java](https://www.baeldung.com/java-static) -- [Polymorphism in Java](https://www.baeldung.com/java-polymorphism) -- [Method Overloading and Overriding in Java](https://www.baeldung.com/java-method-overload-override) -- [How to Make a Deep Copy of an Object in Java](https://www.baeldung.com/java-deep-copy) -- [Guide to Inheritance in Java](https://www.baeldung.com/java-inheritance) -- [Object Type Casting in Java](https://www.baeldung.com/java-type-casting) -- [The “final” Keyword in Java](https://www.baeldung.com/java-final) -- [Type Erasure in Java Explained](https://www.baeldung.com/java-type-erasure) -- [Variable and Method Hiding in Java](https://www.baeldung.com/java-variable-method-hiding) -- [[More -->]](/core-java-modules/core-java-lang-oop-2) diff --git a/core-java-modules/core-java-lang-oop/pom.xml b/core-java-modules/core-java-lang-oop/pom.xml deleted file mode 100644 index a628a4d6c2..0000000000 --- a/core-java-modules/core-java-lang-oop/pom.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - 4.0.0 - core-java-lang-oop - 0.1.0-SNAPSHOT - core-java-lang-oop - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.google.code.gson - gson - ${gson.version} - - - - org.assertj - assertj-core - ${assertj-core.version} - test - - - - - core-java-lang-oop - - - src/main/resources - true - - - - - - 2.8.2 - - 3.10.0 - - - diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/hashcode/entities/User.java deleted file mode 100644 index 524f176e6b..0000000000 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/hashcode/entities/User.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.hashcode.entities; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class User { - - private final Logger logger = LoggerFactory.getLogger(User.class); - private long id; - private String name; - private String email; - - public User(long id, String name, String email) { - this.id = id; - this.name = name; - this.email = email; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null) - return false; - if (this.getClass() != o.getClass()) - return false; - User user = (User) o; - return id == user.id && (name.equals(user.name) && email.equals(user.email)); - } - - @Override - public int hashCode() { - int hash = 7; - hash = 31 * hash + (int) id; - hash = 31 * hash + (name == null ? 0 : name.hashCode()); - hash = 31 * hash + (email == null ? 0 : email.hashCode()); - logger.info("hashCode() method called - Computed hash: " + hash); - return hash; - } - // getters and setters here - -} diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/initializationguide/User.java b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/initializationguide/User.java deleted file mode 100644 index 1d9a872d69..0000000000 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/initializationguide/User.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.initializationguide; - -import java.io.Serializable; - -public class User implements Serializable, Cloneable { - private static final long serialVersionUID = 1L; - static String forum; - private String name; - private int id; - - { - id = 0; - System.out.println("Instance Initializer"); - } - - static { - forum = "Java"; - System.out.println("Static Initializer"); - } - - public User(String name, int id) { - super(); - this.name = name; - this.id = id; - } - - public User() { - System.out.println("Constructor"); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - @Override - protected Object clone() throws CloneNotSupportedException { - return this; - } - -} - diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/method/BaseMethodClass.java b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/method/BaseMethodClass.java deleted file mode 100644 index 46ed5fd99f..0000000000 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/method/BaseMethodClass.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.scope.method; - - -public class BaseMethodClass { - - public static void printMessage() { - System.out.println("base static method"); - } -} diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/method/ChildMethodClass.java b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/method/ChildMethodClass.java deleted file mode 100644 index 1d0cff2d6b..0000000000 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/method/ChildMethodClass.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.scope.method; - - -public class ChildMethodClass extends BaseMethodClass { - - public static void printMessage() { - System.out.println("child static method"); - } -} diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java deleted file mode 100644 index 7e0b3ed146..0000000000 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.scope.method; - -public class MethodHidingDemo { - - public static void main(String[] args) { - ChildMethodClass.printMessage(); - } -} diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/Car.java b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/Car.java deleted file mode 100644 index cdb3806c35..0000000000 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/Car.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.staticdemo; - -/** - * This class demonstrates the use of static fields and static methods - * the instance variables engine and displacement are distinct for - * each and every object whereas static/class variable numberOfCars - * is unique and is shared across all objects of this class. - * - * @author baeldung - * - */ -public class Car { - private String name; - private String engine; - - public static int numberOfCars; - - public Car(String name, String engine) { - this.name = name; - this.engine = engine; - numberOfCars++; - } - - //getters and setters - public static int getNumberOfCars() { - return numberOfCars; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEngine() { - return engine; - } - - public void setEngine(String engine) { - this.engine = engine; - } - - public static void setNumberOfCars(int numberOfCars) { - Car.numberOfCars = numberOfCars; - } -} diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/StaticBlock.java b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/StaticBlock.java deleted file mode 100644 index fde7afb090..0000000000 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/StaticBlock.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.staticdemo; - -import java.util.LinkedList; -import java.util.List; - -public class StaticBlock { - private static List ranks = new LinkedList<>(); - - static { - ranks.add("Lieutenant"); - ranks.add("Captain"); - ranks.add("Major"); - } - - static { - ranks.add("Colonel"); - ranks.add("General"); - } - - //getters and setters - public static List getRanks() { - return ranks; - } - - public static void setRanks(List ranks) { - StaticBlock.ranks = ranks; - } -} diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java deleted file mode 100644 index 49857f355a..0000000000 --- a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.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 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-modules/core-java-lang-oop/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java deleted file mode 100644 index 44ea7efed1..0000000000 --- a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.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 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-modules/core-java-lang-oop/src/test/java/com/baeldung/initializationguide/UserUnitTest.java b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/initializationguide/UserUnitTest.java deleted file mode 100644 index a26b602609..0000000000 --- a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/initializationguide/UserUnitTest.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 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-modules/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/CarIntegrationTest.java b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/CarIntegrationTest.java deleted file mode 100644 index 3150627269..0000000000 --- a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/CarIntegrationTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.staticdemo; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class CarIntegrationTest { - @Test - public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() { - new Car("Jaguar", "V8"); - new Car("Bugatti", "W16"); - assertEquals(2, Car.numberOfCars); - } -} diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/SingletonIntegrationTest.java b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/SingletonIntegrationTest.java deleted file mode 100644 index 28d864073a..0000000000 --- a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/SingletonIntegrationTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.staticdemo; - -import org.junit.Assert; -import org.junit.Test; - -public class SingletonIntegrationTest { - - @Test - public void givenStaticInnerClass_whenMultipleTimesInstanceCalled_thenOnlyOneTimeInitialized() { - Singleton object1 = Singleton.getInstance(); - Singleton object2 = Singleton.getInstance(); - - Assert.assertSame(object1, object2); - } -} diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/StaticBlockIntegrationTest.java b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/StaticBlockIntegrationTest.java deleted file mode 100644 index f98e3e14db..0000000000 --- a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/StaticBlockIntegrationTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.staticdemo; - -import static org.hamcrest.collection.IsIterableContainingInOrder.contains; -import static org.junit.Assert.assertThat; - -import java.util.List; - -import org.junit.Test; - -public class StaticBlockIntegrationTest { - - @Test - public void whenAddedListElementsThroughStaticBlock_thenEnsureCorrectOrder() { - List actualList = StaticBlock.getRanks(); - assertThat(actualList, contains("Lieutenant", "Captain", "Major", "Colonel", "General")); - } -} diff --git a/core-java-modules/core-java-lang-operators/README.md b/core-java-modules/core-java-lang-operators/README.md index 1fe524948c..facbf40fc6 100644 --- a/core-java-modules/core-java-lang-operators/README.md +++ b/core-java-modules/core-java-lang-operators/README.md @@ -11,4 +11,4 @@ This module contains articles about Java operators - [Java Compound Operators](https://www.baeldung.com/java-compound-operators) - [The XOR Operator in Java](https://www.baeldung.com/java-xor-operator) - [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators) - +- [Bitwise & vs Logical && Operators](https://www.baeldung.com/java-bitwise-vs-logical-and) diff --git a/core-java-modules/core-java-lang-operators/pom.xml b/core-java-modules/core-java-lang-operators/pom.xml index 03720122cb..09fbce4b3c 100644 --- a/core-java-modules/core-java-lang-operators/pom.xml +++ b/core-java-modules/core-java-lang-operators/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 core-java-lang-operators 0.1.0-SNAPSHOT @@ -16,6 +17,12 @@ + + org.projectlombok + lombok + ${lombok.version} + provided + org.assertj diff --git a/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/objectclass/Borrower.java b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/objectclass/Borrower.java new file mode 100644 index 0000000000..62062aa7fc --- /dev/null +++ b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/objectclass/Borrower.java @@ -0,0 +1,23 @@ +package com.baeldung.objectclass; + +import lombok.Data; + +@Data +public class Borrower extends User { + + private double totalLoanAmount; + + public double requestLoan(double amount) { + totalLoanAmount = amount; + return totalLoanAmount; + } + + public double increaseLoan(double increaseBy) { + return totalLoanAmount + increaseBy; + } + + public double payLoan(double amount) { + return totalLoanAmount - amount; + } + +} diff --git a/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/objectclass/Lender.java b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/objectclass/Lender.java new file mode 100644 index 0000000000..b45272cbb1 --- /dev/null +++ b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/objectclass/Lender.java @@ -0,0 +1,20 @@ +package com.baeldung.objectclass; + +public class Lender extends User { + + private double totalInvestmentAmount; + + public double invest(double amount) { + totalInvestmentAmount = amount; + return totalInvestmentAmount; + } + + public double increaseInvestment(double increaseBy) { + return totalInvestmentAmount + increaseBy; + } + + public double collectDividends() { + return totalInvestmentAmount * 0.07; + } + +} diff --git a/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/objectclass/User.java b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/objectclass/User.java new file mode 100644 index 0000000000..b1f3887f2f --- /dev/null +++ b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/objectclass/User.java @@ -0,0 +1,12 @@ +package com.baeldung.objectclass; + +import lombok.Data; + +@Data +public class User { + + private String firstName; + private String lastName; + + +} diff --git a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/andoperators/BitwiseAndLogicalANDOperatorsUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/andoperators/BitwiseAndLogicalANDOperatorsUnitTest.java new file mode 100644 index 0000000000..6158c2870d --- /dev/null +++ b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/andoperators/BitwiseAndLogicalANDOperatorsUnitTest.java @@ -0,0 +1,71 @@ +package com.baeldung.andoperators; + +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.*; + +public class BitwiseAndLogicalANDOperatorsUnitTest { + + @Test + public void givenTwoTrueBooleans_whenBitwiseAndOperator_thenTrue() { + boolean trueBool = true; + boolean anotherTrueBool = true; + boolean trueANDTrue = trueBool & anotherTrueBool; + assertTrue(trueANDTrue); + } + + @Test + public void givenOneFalseAndOneTrueBooleans_whenBitwiseAndOperator_thenFalse() { + boolean trueBool = true; + boolean falseBool = false; + boolean trueANDFalse = trueBool & falseBool; + assertFalse(trueANDFalse); + } + + @Test + public void givenTwoFalseBooleans_whenBitwiseAndOperator_thenFalse() { + boolean falseBool = false; + boolean anotherFalseBool = false; + boolean falseANDFalse = falseBool & anotherFalseBool; + assertFalse(falseANDFalse); + } + + @Test + public void givenTwoIntegers_whenBitwiseAndOperator_thenNewDecimalNumber() { + int six = 6; + int five = 5; + int shouldBeFour = six & five; + assertEquals(4, shouldBeFour); + } + + @Test + public void givenTwoTrueBooleans_whenLogicalAndOperator_thenTrue() { + boolean trueBool = true; + boolean anotherTrueBool = true; + boolean trueANDTrue = trueBool && anotherTrueBool; + assertTrue(trueANDTrue); + } + + @Test + public void givenOneFalseAndOneTrueBooleans_whenLogicalAndOperator_thenFalse() { + boolean trueBool = true; + boolean falseBool = false; + boolean trueANDFalse = trueBool && falseBool; + assertFalse(trueANDFalse); + } + + @Test + public void givenTwoFalseBooleans_whenLogicalAndOperator_thenFalse() { + boolean falseBool = false; + boolean anotherFalseBool = false; + boolean falseANDFalse = falseBool && anotherFalseBool; + assertFalse(falseANDFalse); + } + + @Test + public void givenTwoFalseExpressions_whenLogicalAndOperator_thenShortCircuitFalse() { + boolean shortCircuitResult = (2<1) && (4<5); + assertFalse(shortCircuitResult); + } + +} diff --git a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/objectclass/CreditAppUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/objectclass/CreditAppUnitTest.java new file mode 100644 index 0000000000..bba30adcdb --- /dev/null +++ b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/objectclass/CreditAppUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.objectclass; + +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.Ignore; +import org.junit.Test; + +public class CreditAppUnitTest { + + @Test + public void givenLender_whenInstanceOf_thenReturnTrue() { + User lender = new Lender(); + assertTrue(lender instanceof Lender); + assertTrue(lender instanceof User); + } + + @Test + public void givenUser_whenInstanceOfLender_thenDowncast() { + User user = new Lender(); + Lender lender = null; + + if(user instanceof Lender) { + lender = (Lender) user; + } + + assertNotNull(lender); + } + + @Test + public void givenUser_whenIsInstanceOfLender_thenDowncast() { + User user = new Lender(); + Lender lender = null; + + if(Lender.class.isInstance(user)) { + lender = (Lender) user; + } + + assertNotNull(lender); + } + + @Ignore + @Test + public void givenBorrower_whenDoubleOrNotString_thenRequestLoan() { + Borrower borrower = new Borrower(); + double amount = 100.0; + + /*if(amount instanceof Double) { // Compilation error, no autoboxing + borrower.requestLoan(amount); + } + + if(!(amount instanceof String)) { // Compilation error, incompatible operands + borrower.requestLoan(amount); + }*/ + + } + + @Test + public void givenBorrower_whenLoanAmountIsDouble_thenRequestLoan() { + Borrower borrower = new Borrower(); + double amount = 100.0; + + if(Double.class.isInstance(amount)) { // No compilation error + borrower.requestLoan(amount); + } + assertEquals(100, borrower.getTotalLoanAmount()); + } + + @Test + public void givenBorrower_whenLoanAmountIsNotString_thenRequestLoan() { + Borrower borrower = new Borrower(); + Double amount = 100.0; + + if(!String.class.isInstance(amount)) { // No compilation error + borrower.requestLoan(amount); + } + assertEquals(100, borrower.getTotalLoanAmount()); + } + + @Test + public void givenLender_whenGetClass_thenEqualsLenderType() { + User lender = new Lender(); + assertEquals(Lender.class, lender.getClass()); + assertNotEquals(User.class, lender.getClass()); + } + +} diff --git a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java index 6b292ad8ab..728c83a107 100644 --- a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java +++ b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; public class TernaryOperatorUnitTest { @Test - public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() { + public void whenUsingTernaryOperator_thenConditionIsEvaluatedAndValueReturned() { int number = 10; String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10"; @@ -14,7 +14,7 @@ public class TernaryOperatorUnitTest { } @Test - public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() { + public void whenConditionIsTrue_thenOnlyFirstExpressionIsEvaluated() { int exp1 = 0, exp2 = 0; int result = 12 > 10 ? ++exp1 : ++exp2; @@ -24,7 +24,7 @@ public class TernaryOperatorUnitTest { } @Test - public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() { + public void whenConditionIsFalse_thenOnlySecondExpressionIsEvaluated() { int exp1 = 0, exp2 = 0; int result = 8 > 10 ? ++exp1 : ++exp2; diff --git a/core-java-modules/core-java-lang-syntax-2/README.md b/core-java-modules/core-java-lang-syntax-2/README.md index 1518d1ab35..940629c1dc 100644 --- a/core-java-modules/core-java-lang-syntax-2/README.md +++ b/core-java-modules/core-java-lang-syntax-2/README.md @@ -12,4 +12,5 @@ This module contains articles about Java syntax - [Variable Scope in Java](https://www.baeldung.com/java-variable-scope) - [Introduction to Basic Syntax in Java](https://www.baeldung.com/java-syntax) - [Java ‘protected’ Access Modifier](https://www.baeldung.com/java-protected-access-modifier) +- [Using the Not Operator in If Conditions in Java](https://www.baeldung.com/java-using-not-in-if-conditions) - [[<-- Prev]](/core-java-modules/core-java-lang-syntax) diff --git a/core-java-modules/core-java-lang-syntax-2/pom.xml b/core-java-modules/core-java-lang-syntax-2/pom.xml index 961cf022cb..b6da37b736 100644 --- a/core-java-modules/core-java-lang-syntax-2/pom.xml +++ b/core-java-modules/core-java-lang-syntax-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-lang-syntax-2 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/operators/notoperator/NotOperator.java b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/operators/notoperator/NotOperator.java new file mode 100644 index 0000000000..4e0cf98ff2 --- /dev/null +++ b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/operators/notoperator/NotOperator.java @@ -0,0 +1,99 @@ +package com.baeldung.core.operators.notoperator; + +/** + * Examples used in the article `Using the Not Operator in If Conditions in Java`. + */ +public class NotOperator { + + public static void ifElseStatementExample() { + boolean isValid = true; + + if (isValid) { + System.out.println("Valid"); + } else { + System.out.println("Invalid"); + } + } + + public static void checkIsValidIsFalseWithEmptyIfBlock() { + boolean isValid = true; + + if (isValid) { + + } else { + System.out.println("Invalid"); + } + } + + public static void checkIsValidIsFalseWithJustTheIfBlock() { + boolean isValid = true; + + if (isValid == false) { + System.out.println("Invalid"); + } + } + + public static void checkIsValidIsFalseWithTheNotOperator() { + boolean isValid = true; + + if (!isValid) { + System.out.println("Invalid"); + } + } + + public static void notOperatorWithBooleanValueAsOperand() { + System.out.println(!true); // prints false + System.out.println(!false); // prints true + System.out.println(!!false); // prints false + } + + public static void applyNotOperatorToAnExpression_example1() { + int count = 2; + + System.out.println(!(count > 2)); // prints true + System.out.println(!(count <= 2)); // prints false + } + + public static void applyNotOperatorToAnExpression_LogicalOperators() { + boolean x = true; + boolean y = false; + + System.out.println(!(x && y)); // prints true + System.out.println(!(x || y)); // prints false + } + + public static void precedence_example() { + boolean x = true; + boolean y = false; + + System.out.println(!x && y); // prints false + System.out.println(!(x && y)); // prints true + } + + public static void pitfalls_ComplexConditionsExample() { + int count = 9; + int total = 100; + + if (!(count >= 10 || total >= 1000)) { + System.out.println("Some more work to do"); + } + } + + public static void pitfalls_simplifyComplexConditionsByReversingLogicExample() { + int count = 9; + int total = 100; + + if (count < 10 && total < 1000) { + System.out.println("Some more work to do"); + } + } + + public static void exitEarlyExample() { + boolean isValid = false; + + if(!isValid) { + throw new IllegalArgumentException("Invalid input"); + } + // Code to execute when isValid == true goes here + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-syntax/README.md b/core-java-modules/core-java-lang-syntax/README.md index 25f5c63dbc..f74fa1b546 100644 --- a/core-java-modules/core-java-lang-syntax/README.md +++ b/core-java-modules/core-java-lang-syntax/README.md @@ -5,12 +5,12 @@ This module contains articles about Java syntax ### Relevant Articles: - [The Basics of Java Generics](https://www.baeldung.com/java-generics) - [Java Primitive Conversions](https://www.baeldung.com/java-primitive-conversions) -- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break) - [A Guide to Creating Objects in Java](https://www.baeldung.com/java-initialization) - [A Guide to Java Loops](https://www.baeldung.com/java-loops) - [Varargs in Java](https://www.baeldung.com/java-varargs) -- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums) -- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java) - [Java Switch Statement](https://www.baeldung.com/java-switch) - [Breaking Out of Nested Loops](https://www.baeldung.com/java-breaking-out-nested-loop) +- [Java Do-While Loop](https://www.baeldung.com/java-do-while-loop) +- [Java While Loop](https://www.baeldung.com/java-while-loop) +- [Java For Loop](https://www.baeldung.com/java-for-loop) - [[More -->]](/core-java-modules/core-java-lang-syntax-2) diff --git a/core-java-modules/core-java-lang-syntax/pom.xml b/core-java-modules/core-java-lang-syntax/pom.xml index c47a1011b7..106074bba6 100644 --- a/core-java-modules/core-java-lang-syntax/pom.xml +++ b/core-java-modules/core-java-lang-syntax/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-lang-syntax 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-lang/pom.xml b/core-java-modules/core-java-lang/pom.xml index 5b8fe4133b..44d7812c15 100644 --- a/core-java-modules/core-java-lang/pom.xml +++ b/core-java-modules/core-java-lang/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-lang 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java b/core-java-modules/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java rename to core-java-modules/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java b/core-java-modules/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java rename to core-java-modules/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java b/core-java-modules/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java rename to core-java-modules/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/entities/Shape.java b/core-java-modules/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Shape.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/entities/Shape.java rename to core-java-modules/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Shape.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/entities/Square.java b/core-java-modules/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Square.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/equalshashcode/entities/Square.java rename to core-java-modules/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Square.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/equalshashcode/entities/ComplexClassUnitTest.java b/core-java-modules/core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/ComplexClassUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/equalshashcode/entities/ComplexClassUnitTest.java rename to core-java-modules/core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/ComplexClassUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java b/core-java-modules/core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java rename to core-java-modules/core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/equalshashcode/entities/SquareClassUnitTest.java b/core-java-modules/core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/SquareClassUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/equalshashcode/entities/SquareClassUnitTest.java rename to core-java-modules/core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/SquareClassUnitTest.java diff --git a/core-java-modules/core-java-networking-2/README.md b/core-java-modules/core-java-networking-2/README.md index 120b111ff5..662d97252e 100644 --- a/core-java-modules/core-java-networking-2/README.md +++ b/core-java-modules/core-java-networking-2/README.md @@ -11,4 +11,5 @@ This module contains articles about networking in Java - [Sending Emails with Java](https://www.baeldung.com/java-email) - [Authentication with HttpUrlConnection](https://www.baeldung.com/java-http-url-connection) - [Download a File from an URL in Java](https://www.baeldung.com/java-download-file) +- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception) - [[<-- Prev]](/core-java-modules/core-java-networking) diff --git a/core-java-modules/core-java-networking-2/pom.xml b/core-java-modules/core-java-networking-2/pom.xml index 2e2eb51809..938635b8d4 100644 --- a/core-java-modules/core-java-networking-2/pom.xml +++ b/core-java-modules/core-java-networking-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-networking-2 core-java-networking-2 diff --git a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/connectexception/ConnectionChecker.java b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/connectexception/ConnectionChecker.java new file mode 100644 index 0000000000..360fb6ecaa --- /dev/null +++ b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/connectexception/ConnectionChecker.java @@ -0,0 +1,24 @@ +package com.baeldung.connectexception; + +import java.net.ConnectException; +import java.net.Socket; + +public class ConnectionChecker { + public static void main(String[] args) { + String host = "localhost"; + int port = 5000; + + try { + Socket clientSocket = new Socket(host, port); + + // successfully connected to host, do something with opened socket + + clientSocket.close(); + } catch (ConnectException e) { + // host and port combination not valid + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/core-java-modules/core-java-networking/pom.xml b/core-java-modules/core-java-networking/pom.xml index f5b39625f0..c22b62118d 100644 --- a/core-java-modules/core-java-networking/pom.xml +++ b/core-java-modules/core-java-networking/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-networking 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-nio-2/README.md b/core-java-modules/core-java-nio-2/README.md index 8b29c97385..ef73159f66 100644 --- a/core-java-modules/core-java-nio-2/README.md +++ b/core-java-modules/core-java-nio-2/README.md @@ -8,4 +8,5 @@ This module contains articles about core Java non-blocking input and output (IO) - [Create a Symbolic Link with Java](https://www.baeldung.com/java-symlink) - [Introduction to the Java NIO Selector](https://www.baeldung.com/java-nio-selector) - [Using Java MappedByteBuffer](https://www.baeldung.com/java-mapped-byte-buffer) -- [[<-- Prev]](/core-java-modules/core-java-nio) \ No newline at end of file +- [How to Lock a File in Java](https://www.baeldung.com/java-lock-files) +- [[<-- Prev]](/core-java-modules/core-java-nio) diff --git a/core-java-modules/core-java-nio-2/hard_link.txt b/core-java-modules/core-java-nio-2/hard_link.txt deleted file mode 100644 index 931a810b8d..0000000000 --- a/core-java-modules/core-java-nio-2/hard_link.txt +++ /dev/null @@ -1,10000 +0,0 @@ -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98 -99 -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110 -111 -112 -113 -114 -115 -116 -117 -118 -119 -120 -121 -122 -123 -124 -125 -126 -127 -128 -129 -130 -131 -132 -133 -134 -135 -136 -137 -138 -139 -140 -141 -142 -143 -144 -145 -146 -147 -148 -149 -150 -151 -152 -153 -154 -155 -156 -157 -158 -159 -160 -161 -162 -163 -164 -165 -166 -167 -168 -169 -170 -171 -172 -173 -174 -175 -176 -177 -178 -179 -180 -181 -182 -183 -184 -185 -186 -187 -188 -189 -190 -191 -192 -193 -194 -195 -196 -197 -198 -199 -200 -201 -202 -203 -204 -205 -206 -207 -208 -209 -210 -211 -212 -213 -214 -215 -216 -217 -218 -219 -220 -221 -222 -223 -224 -225 -226 -227 -228 -229 -230 -231 -232 -233 -234 -235 -236 -237 -238 -239 -240 -241 -242 -243 -244 -245 -246 -247 -248 -249 -250 -251 -252 -253 -254 -255 -256 -257 -258 -259 -260 -261 -262 -263 -264 -265 -266 -267 -268 -269 -270 -271 -272 -273 -274 -275 -276 -277 -278 -279 -280 -281 -282 -283 -284 -285 -286 -287 -288 -289 -290 -291 -292 -293 -294 -295 -296 -297 -298 -299 -300 -301 -302 -303 -304 -305 -306 -307 -308 -309 -310 -311 -312 -313 -314 -315 -316 -317 -318 -319 -320 -321 -322 -323 -324 -325 -326 -327 -328 -329 -330 -331 -332 -333 -334 -335 -336 -337 -338 -339 -340 -341 -342 -343 -344 -345 -346 -347 -348 -349 -350 -351 -352 -353 -354 -355 -356 -357 -358 -359 -360 -361 -362 -363 -364 -365 -366 -367 -368 -369 -370 -371 -372 -373 -374 -375 -376 -377 -378 -379 -380 -381 -382 -383 -384 -385 -386 -387 -388 -389 -390 -391 -392 -393 -394 -395 -396 -397 -398 -399 -400 -401 -402 -403 -404 -405 -406 -407 -408 -409 -410 -411 -412 -413 -414 -415 -416 -417 -418 -419 -420 -421 -422 -423 -424 -425 -426 -427 -428 -429 -430 -431 -432 -433 -434 -435 -436 -437 -438 -439 -440 -441 -442 -443 -444 -445 -446 -447 -448 -449 -450 -451 -452 -453 -454 -455 -456 -457 -458 -459 -460 -461 -462 -463 -464 -465 -466 -467 -468 -469 -470 -471 -472 -473 -474 -475 -476 -477 -478 -479 -480 -481 -482 -483 -484 -485 -486 -487 -488 -489 -490 -491 -492 -493 -494 -495 -496 -497 -498 -499 -500 -501 -502 -503 -504 -505 -506 -507 -508 -509 -510 -511 -512 -513 -514 -515 -516 -517 -518 -519 -520 -521 -522 -523 -524 -525 -526 -527 -528 -529 -530 -531 -532 -533 -534 -535 -536 -537 -538 -539 -540 -541 -542 -543 -544 -545 -546 -547 -548 -549 -550 -551 -552 -553 -554 -555 -556 -557 -558 -559 -560 -561 -562 -563 -564 -565 -566 -567 -568 -569 -570 -571 -572 -573 -574 -575 -576 -577 -578 -579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598 -599 -600 -601 -602 -603 -604 -605 -606 -607 -608 -609 -610 -611 -612 -613 -614 -615 -616 -617 -618 -619 -620 -621 -622 -623 -624 -625 -626 -627 -628 -629 -630 -631 -632 -633 -634 -635 -636 -637 -638 -639 -640 -641 -642 -643 -644 -645 -646 -647 -648 -649 -650 -651 -652 -653 -654 -655 -656 -657 -658 -659 -660 -661 -662 -663 -664 -665 -666 -667 -668 -669 -670 -671 -672 -673 -674 -675 -676 -677 -678 -679 -680 -681 -682 -683 -684 -685 -686 -687 -688 -689 -690 -691 -692 -693 -694 -695 -696 -697 -698 -699 -700 -701 -702 -703 -704 -705 -706 -707 -708 -709 -710 -711 -712 -713 -714 -715 -716 -717 -718 -719 -720 -721 -722 -723 -724 -725 -726 -727 -728 -729 -730 -731 -732 -733 -734 -735 -736 -737 -738 -739 -740 -741 -742 -743 -744 -745 -746 -747 -748 -749 -750 -751 -752 -753 -754 -755 -756 -757 -758 -759 -760 -761 -762 -763 -764 -765 -766 -767 -768 -769 -770 -771 -772 -773 -774 -775 -776 -777 -778 -779 -780 -781 -782 -783 -784 -785 -786 -787 -788 -789 -790 -791 -792 -793 -794 -795 -796 -797 -798 -799 -800 -801 -802 -803 -804 -805 -806 -807 -808 -809 -810 -811 -812 -813 -814 -815 -816 -817 -818 -819 -820 -821 -822 -823 -824 -825 -826 -827 -828 -829 -830 -831 -832 -833 -834 -835 -836 -837 -838 -839 -840 -841 -842 -843 -844 -845 -846 -847 -848 -849 -850 -851 -852 -853 -854 -855 -856 -857 -858 -859 -860 -861 -862 -863 -864 -865 -866 -867 -868 -869 -870 -871 -872 -873 -874 -875 -876 -877 -878 -879 -880 -881 -882 -883 -884 -885 -886 -887 -888 -889 -890 -891 -892 -893 -894 -895 -896 -897 -898 -899 -900 -901 -902 -903 -904 -905 -906 -907 -908 -909 -910 -911 -912 -913 -914 -915 -916 -917 -918 -919 -920 -921 -922 -923 -924 -925 -926 -927 -928 -929 -930 -931 -932 -933 -934 -935 -936 -937 -938 -939 -940 -941 -942 -943 -944 -945 -946 -947 -948 -949 -950 -951 -952 -953 -954 -955 -956 -957 -958 -959 -960 -961 -962 -963 -964 -965 -966 -967 -968 -969 -970 -971 -972 -973 -974 -975 -976 -977 -978 -979 -980 -981 -982 -983 -984 -985 -986 -987 -988 -989 -990 -991 -992 -993 -994 -995 -996 -997 -998 -999 -1000 -1001 -1002 -1003 -1004 -1005 -1006 -1007 -1008 -1009 -1010 -1011 -1012 -1013 -1014 -1015 -1016 -1017 -1018 -1019 -1020 -1021 -1022 -1023 -1024 -1025 -1026 -1027 -1028 -1029 -1030 -1031 -1032 -1033 -1034 -1035 -1036 -1037 -1038 -1039 -1040 -1041 -1042 -1043 -1044 -1045 -1046 -1047 -1048 -1049 -1050 -1051 -1052 -1053 -1054 -1055 -1056 -1057 -1058 -1059 -1060 -1061 -1062 -1063 -1064 -1065 -1066 -1067 -1068 -1069 -1070 -1071 -1072 -1073 -1074 -1075 -1076 -1077 -1078 -1079 -1080 -1081 -1082 -1083 -1084 -1085 -1086 -1087 -1088 -1089 -1090 -1091 -1092 -1093 -1094 -1095 -1096 -1097 -1098 -1099 -1100 -1101 -1102 -1103 -1104 -1105 -1106 -1107 -1108 -1109 -1110 -1111 -1112 -1113 -1114 -1115 -1116 -1117 -1118 -1119 -1120 -1121 -1122 -1123 -1124 -1125 -1126 -1127 -1128 -1129 -1130 -1131 -1132 -1133 -1134 -1135 -1136 -1137 -1138 -1139 -1140 -1141 -1142 -1143 -1144 -1145 -1146 -1147 -1148 -1149 -1150 -1151 -1152 -1153 -1154 -1155 -1156 -1157 -1158 -1159 -1160 -1161 -1162 -1163 -1164 -1165 -1166 -1167 -1168 -1169 -1170 -1171 -1172 -1173 -1174 -1175 -1176 -1177 -1178 -1179 -1180 -1181 -1182 -1183 -1184 -1185 -1186 -1187 -1188 -1189 -1190 -1191 -1192 -1193 -1194 -1195 -1196 -1197 -1198 -1199 -1200 -1201 -1202 -1203 -1204 -1205 -1206 -1207 -1208 -1209 -1210 -1211 -1212 -1213 -1214 -1215 -1216 -1217 -1218 -1219 -1220 -1221 -1222 -1223 -1224 -1225 -1226 -1227 -1228 -1229 -1230 -1231 -1232 -1233 -1234 -1235 -1236 -1237 -1238 -1239 -1240 -1241 -1242 -1243 -1244 -1245 -1246 -1247 -1248 -1249 -1250 -1251 -1252 -1253 -1254 -1255 -1256 -1257 -1258 -1259 -1260 -1261 -1262 -1263 -1264 -1265 -1266 -1267 -1268 -1269 -1270 -1271 -1272 -1273 -1274 -1275 -1276 -1277 -1278 -1279 -1280 -1281 -1282 -1283 -1284 -1285 -1286 -1287 -1288 -1289 -1290 -1291 -1292 -1293 -1294 -1295 -1296 -1297 -1298 -1299 -1300 -1301 -1302 -1303 -1304 -1305 -1306 -1307 -1308 -1309 -1310 -1311 -1312 -1313 -1314 -1315 -1316 -1317 -1318 -1319 -1320 -1321 -1322 -1323 -1324 -1325 -1326 -1327 -1328 -1329 -1330 -1331 -1332 -1333 -1334 -1335 -1336 -1337 -1338 -1339 -1340 -1341 -1342 -1343 -1344 -1345 -1346 -1347 -1348 -1349 -1350 -1351 -1352 -1353 -1354 -1355 -1356 -1357 -1358 -1359 -1360 -1361 -1362 -1363 -1364 -1365 -1366 -1367 -1368 -1369 -1370 -1371 -1372 -1373 -1374 -1375 -1376 -1377 -1378 -1379 -1380 -1381 -1382 -1383 -1384 -1385 -1386 -1387 -1388 -1389 -1390 -1391 -1392 -1393 -1394 -1395 -1396 -1397 -1398 -1399 -1400 -1401 -1402 -1403 -1404 -1405 -1406 -1407 -1408 -1409 -1410 -1411 -1412 -1413 -1414 -1415 -1416 -1417 -1418 -1419 -1420 -1421 -1422 -1423 -1424 -1425 -1426 -1427 -1428 -1429 -1430 -1431 -1432 -1433 -1434 -1435 -1436 -1437 -1438 -1439 -1440 -1441 -1442 -1443 -1444 -1445 -1446 -1447 -1448 -1449 -1450 -1451 -1452 -1453 -1454 -1455 -1456 -1457 -1458 -1459 -1460 -1461 -1462 -1463 -1464 -1465 -1466 -1467 -1468 -1469 -1470 -1471 -1472 -1473 -1474 -1475 -1476 -1477 -1478 -1479 -1480 -1481 -1482 -1483 -1484 -1485 -1486 -1487 -1488 -1489 -1490 -1491 -1492 -1493 -1494 -1495 -1496 -1497 -1498 -1499 -1500 -1501 -1502 -1503 -1504 -1505 -1506 -1507 -1508 -1509 -1510 -1511 -1512 -1513 -1514 -1515 -1516 -1517 -1518 -1519 -1520 -1521 -1522 -1523 -1524 -1525 -1526 -1527 -1528 -1529 -1530 -1531 -1532 -1533 -1534 -1535 -1536 -1537 -1538 -1539 -1540 -1541 -1542 -1543 -1544 -1545 -1546 -1547 -1548 -1549 -1550 -1551 -1552 -1553 -1554 -1555 -1556 -1557 -1558 -1559 -1560 -1561 -1562 -1563 -1564 -1565 -1566 -1567 -1568 -1569 -1570 -1571 -1572 -1573 -1574 -1575 -1576 -1577 -1578 -1579 -1580 -1581 -1582 -1583 -1584 -1585 -1586 -1587 -1588 -1589 -1590 -1591 -1592 -1593 -1594 -1595 -1596 -1597 -1598 -1599 -1600 -1601 -1602 -1603 -1604 -1605 -1606 -1607 -1608 -1609 -1610 -1611 -1612 -1613 -1614 -1615 -1616 -1617 -1618 -1619 -1620 -1621 -1622 -1623 -1624 -1625 -1626 -1627 -1628 -1629 -1630 -1631 -1632 -1633 -1634 -1635 -1636 -1637 -1638 -1639 -1640 -1641 -1642 -1643 -1644 -1645 -1646 -1647 -1648 -1649 -1650 -1651 -1652 -1653 -1654 -1655 -1656 -1657 -1658 -1659 -1660 -1661 -1662 -1663 -1664 -1665 -1666 -1667 -1668 -1669 -1670 -1671 -1672 -1673 -1674 -1675 -1676 -1677 -1678 -1679 -1680 -1681 -1682 -1683 -1684 -1685 -1686 -1687 -1688 -1689 -1690 -1691 -1692 -1693 -1694 -1695 -1696 -1697 -1698 -1699 -1700 -1701 -1702 -1703 -1704 -1705 -1706 -1707 -1708 -1709 -1710 -1711 -1712 -1713 -1714 -1715 -1716 -1717 -1718 -1719 -1720 -1721 -1722 -1723 -1724 -1725 -1726 -1727 -1728 -1729 -1730 -1731 -1732 -1733 -1734 -1735 -1736 -1737 -1738 -1739 -1740 -1741 -1742 -1743 -1744 -1745 -1746 -1747 -1748 -1749 -1750 -1751 -1752 -1753 -1754 -1755 -1756 -1757 -1758 -1759 -1760 -1761 -1762 -1763 -1764 -1765 -1766 -1767 -1768 -1769 -1770 -1771 -1772 -1773 -1774 -1775 -1776 -1777 -1778 -1779 -1780 -1781 -1782 -1783 -1784 -1785 -1786 -1787 -1788 -1789 -1790 -1791 -1792 -1793 -1794 -1795 -1796 -1797 -1798 -1799 -1800 -1801 -1802 -1803 -1804 -1805 -1806 -1807 -1808 -1809 -1810 -1811 -1812 -1813 -1814 -1815 -1816 -1817 -1818 -1819 -1820 -1821 -1822 -1823 -1824 -1825 -1826 -1827 -1828 -1829 -1830 -1831 -1832 -1833 -1834 -1835 -1836 -1837 -1838 -1839 -1840 -1841 -1842 -1843 -1844 -1845 -1846 -1847 -1848 -1849 -1850 -1851 -1852 -1853 -1854 -1855 -1856 -1857 -1858 -1859 -1860 -1861 -1862 -1863 -1864 -1865 -1866 -1867 -1868 -1869 -1870 -1871 -1872 -1873 -1874 -1875 -1876 -1877 -1878 -1879 -1880 -1881 -1882 -1883 -1884 -1885 -1886 -1887 -1888 -1889 -1890 -1891 -1892 -1893 -1894 -1895 -1896 -1897 -1898 -1899 -1900 -1901 -1902 -1903 -1904 -1905 -1906 -1907 -1908 -1909 -1910 -1911 -1912 -1913 -1914 -1915 -1916 -1917 -1918 -1919 -1920 -1921 -1922 -1923 -1924 -1925 -1926 -1927 -1928 -1929 -1930 -1931 -1932 -1933 -1934 -1935 -1936 -1937 -1938 -1939 -1940 -1941 -1942 -1943 -1944 -1945 -1946 -1947 -1948 -1949 -1950 -1951 -1952 -1953 -1954 -1955 -1956 -1957 -1958 -1959 -1960 -1961 -1962 -1963 -1964 -1965 -1966 -1967 -1968 -1969 -1970 -1971 -1972 -1973 -1974 -1975 -1976 -1977 -1978 -1979 -1980 -1981 -1982 -1983 -1984 -1985 -1986 -1987 -1988 -1989 -1990 -1991 -1992 -1993 -1994 -1995 -1996 -1997 -1998 -1999 -2000 -2001 -2002 -2003 -2004 -2005 -2006 -2007 -2008 -2009 -2010 -2011 -2012 -2013 -2014 -2015 -2016 -2017 -2018 -2019 -2020 -2021 -2022 -2023 -2024 -2025 -2026 -2027 -2028 -2029 -2030 -2031 -2032 -2033 -2034 -2035 -2036 -2037 -2038 -2039 -2040 -2041 -2042 -2043 -2044 -2045 -2046 -2047 -2048 -2049 -2050 -2051 -2052 -2053 -2054 -2055 -2056 -2057 -2058 -2059 -2060 -2061 -2062 -2063 -2064 -2065 -2066 -2067 -2068 -2069 -2070 -2071 -2072 -2073 -2074 -2075 -2076 -2077 -2078 -2079 -2080 -2081 -2082 -2083 -2084 -2085 -2086 -2087 -2088 -2089 -2090 -2091 -2092 -2093 -2094 -2095 -2096 -2097 -2098 -2099 -2100 -2101 -2102 -2103 -2104 -2105 -2106 -2107 -2108 -2109 -2110 -2111 -2112 -2113 -2114 -2115 -2116 -2117 -2118 -2119 -2120 -2121 -2122 -2123 -2124 -2125 -2126 -2127 -2128 -2129 -2130 -2131 -2132 -2133 -2134 -2135 -2136 -2137 -2138 -2139 -2140 -2141 -2142 -2143 -2144 -2145 -2146 -2147 -2148 -2149 -2150 -2151 -2152 -2153 -2154 -2155 -2156 -2157 -2158 -2159 -2160 -2161 -2162 -2163 -2164 -2165 -2166 -2167 -2168 -2169 -2170 -2171 -2172 -2173 -2174 -2175 -2176 -2177 -2178 -2179 -2180 -2181 -2182 -2183 -2184 -2185 -2186 -2187 -2188 -2189 -2190 -2191 -2192 -2193 -2194 -2195 -2196 -2197 -2198 -2199 -2200 -2201 -2202 -2203 -2204 -2205 -2206 -2207 -2208 -2209 -2210 -2211 -2212 -2213 -2214 -2215 -2216 -2217 -2218 -2219 -2220 -2221 -2222 -2223 -2224 -2225 -2226 -2227 -2228 -2229 -2230 -2231 -2232 -2233 -2234 -2235 -2236 -2237 -2238 -2239 -2240 -2241 -2242 -2243 -2244 -2245 -2246 -2247 -2248 -2249 -2250 -2251 -2252 -2253 -2254 -2255 -2256 -2257 -2258 -2259 -2260 -2261 -2262 -2263 -2264 -2265 -2266 -2267 -2268 -2269 -2270 -2271 -2272 -2273 -2274 -2275 -2276 -2277 -2278 -2279 -2280 -2281 -2282 -2283 -2284 -2285 -2286 -2287 -2288 -2289 -2290 -2291 -2292 -2293 -2294 -2295 -2296 -2297 -2298 -2299 -2300 -2301 -2302 -2303 -2304 -2305 -2306 -2307 -2308 -2309 -2310 -2311 -2312 -2313 -2314 -2315 -2316 -2317 -2318 -2319 -2320 -2321 -2322 -2323 -2324 -2325 -2326 -2327 -2328 -2329 -2330 -2331 -2332 -2333 -2334 -2335 -2336 -2337 -2338 -2339 -2340 -2341 -2342 -2343 -2344 -2345 -2346 -2347 -2348 -2349 -2350 -2351 -2352 -2353 -2354 -2355 -2356 -2357 -2358 -2359 -2360 -2361 -2362 -2363 -2364 -2365 -2366 -2367 -2368 -2369 -2370 -2371 -2372 -2373 -2374 -2375 -2376 -2377 -2378 -2379 -2380 -2381 -2382 -2383 -2384 -2385 -2386 -2387 -2388 -2389 -2390 -2391 -2392 -2393 -2394 -2395 -2396 -2397 -2398 -2399 -2400 -2401 -2402 -2403 -2404 -2405 -2406 -2407 -2408 -2409 -2410 -2411 -2412 -2413 -2414 -2415 -2416 -2417 -2418 -2419 -2420 -2421 -2422 -2423 -2424 -2425 -2426 -2427 -2428 -2429 -2430 -2431 -2432 -2433 -2434 -2435 -2436 -2437 -2438 -2439 -2440 -2441 -2442 -2443 -2444 -2445 -2446 -2447 -2448 -2449 -2450 -2451 -2452 -2453 -2454 -2455 -2456 -2457 -2458 -2459 -2460 -2461 -2462 -2463 -2464 -2465 -2466 -2467 -2468 -2469 -2470 -2471 -2472 -2473 -2474 -2475 -2476 -2477 -2478 -2479 -2480 -2481 -2482 -2483 -2484 -2485 -2486 -2487 -2488 -2489 -2490 -2491 -2492 -2493 -2494 -2495 -2496 -2497 -2498 -2499 -2500 -2501 -2502 -2503 -2504 -2505 -2506 -2507 -2508 -2509 -2510 -2511 -2512 -2513 -2514 -2515 -2516 -2517 -2518 -2519 -2520 -2521 -2522 -2523 -2524 -2525 -2526 -2527 -2528 -2529 -2530 -2531 -2532 -2533 -2534 -2535 -2536 -2537 -2538 -2539 -2540 -2541 -2542 -2543 -2544 -2545 -2546 -2547 -2548 -2549 -2550 -2551 -2552 -2553 -2554 -2555 -2556 -2557 -2558 -2559 -2560 -2561 -2562 -2563 -2564 -2565 -2566 -2567 -2568 -2569 -2570 -2571 -2572 -2573 -2574 -2575 -2576 -2577 -2578 -2579 -2580 -2581 -2582 -2583 -2584 -2585 -2586 -2587 -2588 -2589 -2590 -2591 -2592 -2593 -2594 -2595 -2596 -2597 -2598 -2599 -2600 -2601 -2602 -2603 -2604 -2605 -2606 -2607 -2608 -2609 -2610 -2611 -2612 -2613 -2614 -2615 -2616 -2617 -2618 -2619 -2620 -2621 -2622 -2623 -2624 -2625 -2626 -2627 -2628 -2629 -2630 -2631 -2632 -2633 -2634 -2635 -2636 -2637 -2638 -2639 -2640 -2641 -2642 -2643 -2644 -2645 -2646 -2647 -2648 -2649 -2650 -2651 -2652 -2653 -2654 -2655 -2656 -2657 -2658 -2659 -2660 -2661 -2662 -2663 -2664 -2665 -2666 -2667 -2668 -2669 -2670 -2671 -2672 -2673 -2674 -2675 -2676 -2677 -2678 -2679 -2680 -2681 -2682 -2683 -2684 -2685 -2686 -2687 -2688 -2689 -2690 -2691 -2692 -2693 -2694 -2695 -2696 -2697 -2698 -2699 -2700 -2701 -2702 -2703 -2704 -2705 -2706 -2707 -2708 -2709 -2710 -2711 -2712 -2713 -2714 -2715 -2716 -2717 -2718 -2719 -2720 -2721 -2722 -2723 -2724 -2725 -2726 -2727 -2728 -2729 -2730 -2731 -2732 -2733 -2734 -2735 -2736 -2737 -2738 -2739 -2740 -2741 -2742 -2743 -2744 -2745 -2746 -2747 -2748 -2749 -2750 -2751 -2752 -2753 -2754 -2755 -2756 -2757 -2758 -2759 -2760 -2761 -2762 -2763 -2764 -2765 -2766 -2767 -2768 -2769 -2770 -2771 -2772 -2773 -2774 -2775 -2776 -2777 -2778 -2779 -2780 -2781 -2782 -2783 -2784 -2785 -2786 -2787 -2788 -2789 -2790 -2791 -2792 -2793 -2794 -2795 -2796 -2797 -2798 -2799 -2800 -2801 -2802 -2803 -2804 -2805 -2806 -2807 -2808 -2809 -2810 -2811 -2812 -2813 -2814 -2815 -2816 -2817 -2818 -2819 -2820 -2821 -2822 -2823 -2824 -2825 -2826 -2827 -2828 -2829 -2830 -2831 -2832 -2833 -2834 -2835 -2836 -2837 -2838 -2839 -2840 -2841 -2842 -2843 -2844 -2845 -2846 -2847 -2848 -2849 -2850 -2851 -2852 -2853 -2854 -2855 -2856 -2857 -2858 -2859 -2860 -2861 -2862 -2863 -2864 -2865 -2866 -2867 -2868 -2869 -2870 -2871 -2872 -2873 -2874 -2875 -2876 -2877 -2878 -2879 -2880 -2881 -2882 -2883 -2884 -2885 -2886 -2887 -2888 -2889 -2890 -2891 -2892 -2893 -2894 -2895 -2896 -2897 -2898 -2899 -2900 -2901 -2902 -2903 -2904 -2905 -2906 -2907 -2908 -2909 -2910 -2911 -2912 -2913 -2914 -2915 -2916 -2917 -2918 -2919 -2920 -2921 -2922 -2923 -2924 -2925 -2926 -2927 -2928 -2929 -2930 -2931 -2932 -2933 -2934 -2935 -2936 -2937 -2938 -2939 -2940 -2941 -2942 -2943 -2944 -2945 -2946 -2947 -2948 -2949 -2950 -2951 -2952 -2953 -2954 -2955 -2956 -2957 -2958 -2959 -2960 -2961 -2962 -2963 -2964 -2965 -2966 -2967 -2968 -2969 -2970 -2971 -2972 -2973 -2974 -2975 -2976 -2977 -2978 -2979 -2980 -2981 -2982 -2983 -2984 -2985 -2986 -2987 -2988 -2989 -2990 -2991 -2992 -2993 -2994 -2995 -2996 -2997 -2998 -2999 -3000 -3001 -3002 -3003 -3004 -3005 -3006 -3007 -3008 -3009 -3010 -3011 -3012 -3013 -3014 -3015 -3016 -3017 -3018 -3019 -3020 -3021 -3022 -3023 -3024 -3025 -3026 -3027 -3028 -3029 -3030 -3031 -3032 -3033 -3034 -3035 -3036 -3037 -3038 -3039 -3040 -3041 -3042 -3043 -3044 -3045 -3046 -3047 -3048 -3049 -3050 -3051 -3052 -3053 -3054 -3055 -3056 -3057 -3058 -3059 -3060 -3061 -3062 -3063 -3064 -3065 -3066 -3067 -3068 -3069 -3070 -3071 -3072 -3073 -3074 -3075 -3076 -3077 -3078 -3079 -3080 -3081 -3082 -3083 -3084 -3085 -3086 -3087 -3088 -3089 -3090 -3091 -3092 -3093 -3094 -3095 -3096 -3097 -3098 -3099 -3100 -3101 -3102 -3103 -3104 -3105 -3106 -3107 -3108 -3109 -3110 -3111 -3112 -3113 -3114 -3115 -3116 -3117 -3118 -3119 -3120 -3121 -3122 -3123 -3124 -3125 -3126 -3127 -3128 -3129 -3130 -3131 -3132 -3133 -3134 -3135 -3136 -3137 -3138 -3139 -3140 -3141 -3142 -3143 -3144 -3145 -3146 -3147 -3148 -3149 -3150 -3151 -3152 -3153 -3154 -3155 -3156 -3157 -3158 -3159 -3160 -3161 -3162 -3163 -3164 -3165 -3166 -3167 -3168 -3169 -3170 -3171 -3172 -3173 -3174 -3175 -3176 -3177 -3178 -3179 -3180 -3181 -3182 -3183 -3184 -3185 -3186 -3187 -3188 -3189 -3190 -3191 -3192 -3193 -3194 -3195 -3196 -3197 -3198 -3199 -3200 -3201 -3202 -3203 -3204 -3205 -3206 -3207 -3208 -3209 -3210 -3211 -3212 -3213 -3214 -3215 -3216 -3217 -3218 -3219 -3220 -3221 -3222 -3223 -3224 -3225 -3226 -3227 -3228 -3229 -3230 -3231 -3232 -3233 -3234 -3235 -3236 -3237 -3238 -3239 -3240 -3241 -3242 -3243 -3244 -3245 -3246 -3247 -3248 -3249 -3250 -3251 -3252 -3253 -3254 -3255 -3256 -3257 -3258 -3259 -3260 -3261 -3262 -3263 -3264 -3265 -3266 -3267 -3268 -3269 -3270 -3271 -3272 -3273 -3274 -3275 -3276 -3277 -3278 -3279 -3280 -3281 -3282 -3283 -3284 -3285 -3286 -3287 -3288 -3289 -3290 -3291 -3292 -3293 -3294 -3295 -3296 -3297 -3298 -3299 -3300 -3301 -3302 -3303 -3304 -3305 -3306 -3307 -3308 -3309 -3310 -3311 -3312 -3313 -3314 -3315 -3316 -3317 -3318 -3319 -3320 -3321 -3322 -3323 -3324 -3325 -3326 -3327 -3328 -3329 -3330 -3331 -3332 -3333 -3334 -3335 -3336 -3337 -3338 -3339 -3340 -3341 -3342 -3343 -3344 -3345 -3346 -3347 -3348 -3349 -3350 -3351 -3352 -3353 -3354 -3355 -3356 -3357 -3358 -3359 -3360 -3361 -3362 -3363 -3364 -3365 -3366 -3367 -3368 -3369 -3370 -3371 -3372 -3373 -3374 -3375 -3376 -3377 -3378 -3379 -3380 -3381 -3382 -3383 -3384 -3385 -3386 -3387 -3388 -3389 -3390 -3391 -3392 -3393 -3394 -3395 -3396 -3397 -3398 -3399 -3400 -3401 -3402 -3403 -3404 -3405 -3406 -3407 -3408 -3409 -3410 -3411 -3412 -3413 -3414 -3415 -3416 -3417 -3418 -3419 -3420 -3421 -3422 -3423 -3424 -3425 -3426 -3427 -3428 -3429 -3430 -3431 -3432 -3433 -3434 -3435 -3436 -3437 -3438 -3439 -3440 -3441 -3442 -3443 -3444 -3445 -3446 -3447 -3448 -3449 -3450 -3451 -3452 -3453 -3454 -3455 -3456 -3457 -3458 -3459 -3460 -3461 -3462 -3463 -3464 -3465 -3466 -3467 -3468 -3469 -3470 -3471 -3472 -3473 -3474 -3475 -3476 -3477 -3478 -3479 -3480 -3481 -3482 -3483 -3484 -3485 -3486 -3487 -3488 -3489 -3490 -3491 -3492 -3493 -3494 -3495 -3496 -3497 -3498 -3499 -3500 -3501 -3502 -3503 -3504 -3505 -3506 -3507 -3508 -3509 -3510 -3511 -3512 -3513 -3514 -3515 -3516 -3517 -3518 -3519 -3520 -3521 -3522 -3523 -3524 -3525 -3526 -3527 -3528 -3529 -3530 -3531 -3532 -3533 -3534 -3535 -3536 -3537 -3538 -3539 -3540 -3541 -3542 -3543 -3544 -3545 -3546 -3547 -3548 -3549 -3550 -3551 -3552 -3553 -3554 -3555 -3556 -3557 -3558 -3559 -3560 -3561 -3562 -3563 -3564 -3565 -3566 -3567 -3568 -3569 -3570 -3571 -3572 -3573 -3574 -3575 -3576 -3577 -3578 -3579 -3580 -3581 -3582 -3583 -3584 -3585 -3586 -3587 -3588 -3589 -3590 -3591 -3592 -3593 -3594 -3595 -3596 -3597 -3598 -3599 -3600 -3601 -3602 -3603 -3604 -3605 -3606 -3607 -3608 -3609 -3610 -3611 -3612 -3613 -3614 -3615 -3616 -3617 -3618 -3619 -3620 -3621 -3622 -3623 -3624 -3625 -3626 -3627 -3628 -3629 -3630 -3631 -3632 -3633 -3634 -3635 -3636 -3637 -3638 -3639 -3640 -3641 -3642 -3643 -3644 -3645 -3646 -3647 -3648 -3649 -3650 -3651 -3652 -3653 -3654 -3655 -3656 -3657 -3658 -3659 -3660 -3661 -3662 -3663 -3664 -3665 -3666 -3667 -3668 -3669 -3670 -3671 -3672 -3673 -3674 -3675 -3676 -3677 -3678 -3679 -3680 -3681 -3682 -3683 -3684 -3685 -3686 -3687 -3688 -3689 -3690 -3691 -3692 -3693 -3694 -3695 -3696 -3697 -3698 -3699 -3700 -3701 -3702 -3703 -3704 -3705 -3706 -3707 -3708 -3709 -3710 -3711 -3712 -3713 -3714 -3715 -3716 -3717 -3718 -3719 -3720 -3721 -3722 -3723 -3724 -3725 -3726 -3727 -3728 -3729 -3730 -3731 -3732 -3733 -3734 -3735 -3736 -3737 -3738 -3739 -3740 -3741 -3742 -3743 -3744 -3745 -3746 -3747 -3748 -3749 -3750 -3751 -3752 -3753 -3754 -3755 -3756 -3757 -3758 -3759 -3760 -3761 -3762 -3763 -3764 -3765 -3766 -3767 -3768 -3769 -3770 -3771 -3772 -3773 -3774 -3775 -3776 -3777 -3778 -3779 -3780 -3781 -3782 -3783 -3784 -3785 -3786 -3787 -3788 -3789 -3790 -3791 -3792 -3793 -3794 -3795 -3796 -3797 -3798 -3799 -3800 -3801 -3802 -3803 -3804 -3805 -3806 -3807 -3808 -3809 -3810 -3811 -3812 -3813 -3814 -3815 -3816 -3817 -3818 -3819 -3820 -3821 -3822 -3823 -3824 -3825 -3826 -3827 -3828 -3829 -3830 -3831 -3832 -3833 -3834 -3835 -3836 -3837 -3838 -3839 -3840 -3841 -3842 -3843 -3844 -3845 -3846 -3847 -3848 -3849 -3850 -3851 -3852 -3853 -3854 -3855 -3856 -3857 -3858 -3859 -3860 -3861 -3862 -3863 -3864 -3865 -3866 -3867 -3868 -3869 -3870 -3871 -3872 -3873 -3874 -3875 -3876 -3877 -3878 -3879 -3880 -3881 -3882 -3883 -3884 -3885 -3886 -3887 -3888 -3889 -3890 -3891 -3892 -3893 -3894 -3895 -3896 -3897 -3898 -3899 -3900 -3901 -3902 -3903 -3904 -3905 -3906 -3907 -3908 -3909 -3910 -3911 -3912 -3913 -3914 -3915 -3916 -3917 -3918 -3919 -3920 -3921 -3922 -3923 -3924 -3925 -3926 -3927 -3928 -3929 -3930 -3931 -3932 -3933 -3934 -3935 -3936 -3937 -3938 -3939 -3940 -3941 -3942 -3943 -3944 -3945 -3946 -3947 -3948 -3949 -3950 -3951 -3952 -3953 -3954 -3955 -3956 -3957 -3958 -3959 -3960 -3961 -3962 -3963 -3964 -3965 -3966 -3967 -3968 -3969 -3970 -3971 -3972 -3973 -3974 -3975 -3976 -3977 -3978 -3979 -3980 -3981 -3982 -3983 -3984 -3985 -3986 -3987 -3988 -3989 -3990 -3991 -3992 -3993 -3994 -3995 -3996 -3997 -3998 -3999 -4000 -4001 -4002 -4003 -4004 -4005 -4006 -4007 -4008 -4009 -4010 -4011 -4012 -4013 -4014 -4015 -4016 -4017 -4018 -4019 -4020 -4021 -4022 -4023 -4024 -4025 -4026 -4027 -4028 -4029 -4030 -4031 -4032 -4033 -4034 -4035 -4036 -4037 -4038 -4039 -4040 -4041 -4042 -4043 -4044 -4045 -4046 -4047 -4048 -4049 -4050 -4051 -4052 -4053 -4054 -4055 -4056 -4057 -4058 -4059 -4060 -4061 -4062 -4063 -4064 -4065 -4066 -4067 -4068 -4069 -4070 -4071 -4072 -4073 -4074 -4075 -4076 -4077 -4078 -4079 -4080 -4081 -4082 -4083 -4084 -4085 -4086 -4087 -4088 -4089 -4090 -4091 -4092 -4093 -4094 -4095 -4096 -4097 -4098 -4099 -4100 -4101 -4102 -4103 -4104 -4105 -4106 -4107 -4108 -4109 -4110 -4111 -4112 -4113 -4114 -4115 -4116 -4117 -4118 -4119 -4120 -4121 -4122 -4123 -4124 -4125 -4126 -4127 -4128 -4129 -4130 -4131 -4132 -4133 -4134 -4135 -4136 -4137 -4138 -4139 -4140 -4141 -4142 -4143 -4144 -4145 -4146 -4147 -4148 -4149 -4150 -4151 -4152 -4153 -4154 -4155 -4156 -4157 -4158 -4159 -4160 -4161 -4162 -4163 -4164 -4165 -4166 -4167 -4168 -4169 -4170 -4171 -4172 -4173 -4174 -4175 -4176 -4177 -4178 -4179 -4180 -4181 -4182 -4183 -4184 -4185 -4186 -4187 -4188 -4189 -4190 -4191 -4192 -4193 -4194 -4195 -4196 -4197 -4198 -4199 -4200 -4201 -4202 -4203 -4204 -4205 -4206 -4207 -4208 -4209 -4210 -4211 -4212 -4213 -4214 -4215 -4216 -4217 -4218 -4219 -4220 -4221 -4222 -4223 -4224 -4225 -4226 -4227 -4228 -4229 -4230 -4231 -4232 -4233 -4234 -4235 -4236 -4237 -4238 -4239 -4240 -4241 -4242 -4243 -4244 -4245 -4246 -4247 -4248 -4249 -4250 -4251 -4252 -4253 -4254 -4255 -4256 -4257 -4258 -4259 -4260 -4261 -4262 -4263 -4264 -4265 -4266 -4267 -4268 -4269 -4270 -4271 -4272 -4273 -4274 -4275 -4276 -4277 -4278 -4279 -4280 -4281 -4282 -4283 -4284 -4285 -4286 -4287 -4288 -4289 -4290 -4291 -4292 -4293 -4294 -4295 -4296 -4297 -4298 -4299 -4300 -4301 -4302 -4303 -4304 -4305 -4306 -4307 -4308 -4309 -4310 -4311 -4312 -4313 -4314 -4315 -4316 -4317 -4318 -4319 -4320 -4321 -4322 -4323 -4324 -4325 -4326 -4327 -4328 -4329 -4330 -4331 -4332 -4333 -4334 -4335 -4336 -4337 -4338 -4339 -4340 -4341 -4342 -4343 -4344 -4345 -4346 -4347 -4348 -4349 -4350 -4351 -4352 -4353 -4354 -4355 -4356 -4357 -4358 -4359 -4360 -4361 -4362 -4363 -4364 -4365 -4366 -4367 -4368 -4369 -4370 -4371 -4372 -4373 -4374 -4375 -4376 -4377 -4378 -4379 -4380 -4381 -4382 -4383 -4384 -4385 -4386 -4387 -4388 -4389 -4390 -4391 -4392 -4393 -4394 -4395 -4396 -4397 -4398 -4399 -4400 -4401 -4402 -4403 -4404 -4405 -4406 -4407 -4408 -4409 -4410 -4411 -4412 -4413 -4414 -4415 -4416 -4417 -4418 -4419 -4420 -4421 -4422 -4423 -4424 -4425 -4426 -4427 -4428 -4429 -4430 -4431 -4432 -4433 -4434 -4435 -4436 -4437 -4438 -4439 -4440 -4441 -4442 -4443 -4444 -4445 -4446 -4447 -4448 -4449 -4450 -4451 -4452 -4453 -4454 -4455 -4456 -4457 -4458 -4459 -4460 -4461 -4462 -4463 -4464 -4465 -4466 -4467 -4468 -4469 -4470 -4471 -4472 -4473 -4474 -4475 -4476 -4477 -4478 -4479 -4480 -4481 -4482 -4483 -4484 -4485 -4486 -4487 -4488 -4489 -4490 -4491 -4492 -4493 -4494 -4495 -4496 -4497 -4498 -4499 -4500 -4501 -4502 -4503 -4504 -4505 -4506 -4507 -4508 -4509 -4510 -4511 -4512 -4513 -4514 -4515 -4516 -4517 -4518 -4519 -4520 -4521 -4522 -4523 -4524 -4525 -4526 -4527 -4528 -4529 -4530 -4531 -4532 -4533 -4534 -4535 -4536 -4537 -4538 -4539 -4540 -4541 -4542 -4543 -4544 -4545 -4546 -4547 -4548 -4549 -4550 -4551 -4552 -4553 -4554 -4555 -4556 -4557 -4558 -4559 -4560 -4561 -4562 -4563 -4564 -4565 -4566 -4567 -4568 -4569 -4570 -4571 -4572 -4573 -4574 -4575 -4576 -4577 -4578 -4579 -4580 -4581 -4582 -4583 -4584 -4585 -4586 -4587 -4588 -4589 -4590 -4591 -4592 -4593 -4594 -4595 -4596 -4597 -4598 -4599 -4600 -4601 -4602 -4603 -4604 -4605 -4606 -4607 -4608 -4609 -4610 -4611 -4612 -4613 -4614 -4615 -4616 -4617 -4618 -4619 -4620 -4621 -4622 -4623 -4624 -4625 -4626 -4627 -4628 -4629 -4630 -4631 -4632 -4633 -4634 -4635 -4636 -4637 -4638 -4639 -4640 -4641 -4642 -4643 -4644 -4645 -4646 -4647 -4648 -4649 -4650 -4651 -4652 -4653 -4654 -4655 -4656 -4657 -4658 -4659 -4660 -4661 -4662 -4663 -4664 -4665 -4666 -4667 -4668 -4669 -4670 -4671 -4672 -4673 -4674 -4675 -4676 -4677 -4678 -4679 -4680 -4681 -4682 -4683 -4684 -4685 -4686 -4687 -4688 -4689 -4690 -4691 -4692 -4693 -4694 -4695 -4696 -4697 -4698 -4699 -4700 -4701 -4702 -4703 -4704 -4705 -4706 -4707 -4708 -4709 -4710 -4711 -4712 -4713 -4714 -4715 -4716 -4717 -4718 -4719 -4720 -4721 -4722 -4723 -4724 -4725 -4726 -4727 -4728 -4729 -4730 -4731 -4732 -4733 -4734 -4735 -4736 -4737 -4738 -4739 -4740 -4741 -4742 -4743 -4744 -4745 -4746 -4747 -4748 -4749 -4750 -4751 -4752 -4753 -4754 -4755 -4756 -4757 -4758 -4759 -4760 -4761 -4762 -4763 -4764 -4765 -4766 -4767 -4768 -4769 -4770 -4771 -4772 -4773 -4774 -4775 -4776 -4777 -4778 -4779 -4780 -4781 -4782 -4783 -4784 -4785 -4786 -4787 -4788 -4789 -4790 -4791 -4792 -4793 -4794 -4795 -4796 -4797 -4798 -4799 -4800 -4801 -4802 -4803 -4804 -4805 -4806 -4807 -4808 -4809 -4810 -4811 -4812 -4813 -4814 -4815 -4816 -4817 -4818 -4819 -4820 -4821 -4822 -4823 -4824 -4825 -4826 -4827 -4828 -4829 -4830 -4831 -4832 -4833 -4834 -4835 -4836 -4837 -4838 -4839 -4840 -4841 -4842 -4843 -4844 -4845 -4846 -4847 -4848 -4849 -4850 -4851 -4852 -4853 -4854 -4855 -4856 -4857 -4858 -4859 -4860 -4861 -4862 -4863 -4864 -4865 -4866 -4867 -4868 -4869 -4870 -4871 -4872 -4873 -4874 -4875 -4876 -4877 -4878 -4879 -4880 -4881 -4882 -4883 -4884 -4885 -4886 -4887 -4888 -4889 -4890 -4891 -4892 -4893 -4894 -4895 -4896 -4897 -4898 -4899 -4900 -4901 -4902 -4903 -4904 -4905 -4906 -4907 -4908 -4909 -4910 -4911 -4912 -4913 -4914 -4915 -4916 -4917 -4918 -4919 -4920 -4921 -4922 -4923 -4924 -4925 -4926 -4927 -4928 -4929 -4930 -4931 -4932 -4933 -4934 -4935 -4936 -4937 -4938 -4939 -4940 -4941 -4942 -4943 -4944 -4945 -4946 -4947 -4948 -4949 -4950 -4951 -4952 -4953 -4954 -4955 -4956 -4957 -4958 -4959 -4960 -4961 -4962 -4963 -4964 -4965 -4966 -4967 -4968 -4969 -4970 -4971 -4972 -4973 -4974 -4975 -4976 -4977 -4978 -4979 -4980 -4981 -4982 -4983 -4984 -4985 -4986 -4987 -4988 -4989 -4990 -4991 -4992 -4993 -4994 -4995 -4996 -4997 -4998 -4999 -5000 -5001 -5002 -5003 -5004 -5005 -5006 -5007 -5008 -5009 -5010 -5011 -5012 -5013 -5014 -5015 -5016 -5017 -5018 -5019 -5020 -5021 -5022 -5023 -5024 -5025 -5026 -5027 -5028 -5029 -5030 -5031 -5032 -5033 -5034 -5035 -5036 -5037 -5038 -5039 -5040 -5041 -5042 -5043 -5044 -5045 -5046 -5047 -5048 -5049 -5050 -5051 -5052 -5053 -5054 -5055 -5056 -5057 -5058 -5059 -5060 -5061 -5062 -5063 -5064 -5065 -5066 -5067 -5068 -5069 -5070 -5071 -5072 -5073 -5074 -5075 -5076 -5077 -5078 -5079 -5080 -5081 -5082 -5083 -5084 -5085 -5086 -5087 -5088 -5089 -5090 -5091 -5092 -5093 -5094 -5095 -5096 -5097 -5098 -5099 -5100 -5101 -5102 -5103 -5104 -5105 -5106 -5107 -5108 -5109 -5110 -5111 -5112 -5113 -5114 -5115 -5116 -5117 -5118 -5119 -5120 -5121 -5122 -5123 -5124 -5125 -5126 -5127 -5128 -5129 -5130 -5131 -5132 -5133 -5134 -5135 -5136 -5137 -5138 -5139 -5140 -5141 -5142 -5143 -5144 -5145 -5146 -5147 -5148 -5149 -5150 -5151 -5152 -5153 -5154 -5155 -5156 -5157 -5158 -5159 -5160 -5161 -5162 -5163 -5164 -5165 -5166 -5167 -5168 -5169 -5170 -5171 -5172 -5173 -5174 -5175 -5176 -5177 -5178 -5179 -5180 -5181 -5182 -5183 -5184 -5185 -5186 -5187 -5188 -5189 -5190 -5191 -5192 -5193 -5194 -5195 -5196 -5197 -5198 -5199 -5200 -5201 -5202 -5203 -5204 -5205 -5206 -5207 -5208 -5209 -5210 -5211 -5212 -5213 -5214 -5215 -5216 -5217 -5218 -5219 -5220 -5221 -5222 -5223 -5224 -5225 -5226 -5227 -5228 -5229 -5230 -5231 -5232 -5233 -5234 -5235 -5236 -5237 -5238 -5239 -5240 -5241 -5242 -5243 -5244 -5245 -5246 -5247 -5248 -5249 -5250 -5251 -5252 -5253 -5254 -5255 -5256 -5257 -5258 -5259 -5260 -5261 -5262 -5263 -5264 -5265 -5266 -5267 -5268 -5269 -5270 -5271 -5272 -5273 -5274 -5275 -5276 -5277 -5278 -5279 -5280 -5281 -5282 -5283 -5284 -5285 -5286 -5287 -5288 -5289 -5290 -5291 -5292 -5293 -5294 -5295 -5296 -5297 -5298 -5299 -5300 -5301 -5302 -5303 -5304 -5305 -5306 -5307 -5308 -5309 -5310 -5311 -5312 -5313 -5314 -5315 -5316 -5317 -5318 -5319 -5320 -5321 -5322 -5323 -5324 -5325 -5326 -5327 -5328 -5329 -5330 -5331 -5332 -5333 -5334 -5335 -5336 -5337 -5338 -5339 -5340 -5341 -5342 -5343 -5344 -5345 -5346 -5347 -5348 -5349 -5350 -5351 -5352 -5353 -5354 -5355 -5356 -5357 -5358 -5359 -5360 -5361 -5362 -5363 -5364 -5365 -5366 -5367 -5368 -5369 -5370 -5371 -5372 -5373 -5374 -5375 -5376 -5377 -5378 -5379 -5380 -5381 -5382 -5383 -5384 -5385 -5386 -5387 -5388 -5389 -5390 -5391 -5392 -5393 -5394 -5395 -5396 -5397 -5398 -5399 -5400 -5401 -5402 -5403 -5404 -5405 -5406 -5407 -5408 -5409 -5410 -5411 -5412 -5413 -5414 -5415 -5416 -5417 -5418 -5419 -5420 -5421 -5422 -5423 -5424 -5425 -5426 -5427 -5428 -5429 -5430 -5431 -5432 -5433 -5434 -5435 -5436 -5437 -5438 -5439 -5440 -5441 -5442 -5443 -5444 -5445 -5446 -5447 -5448 -5449 -5450 -5451 -5452 -5453 -5454 -5455 -5456 -5457 -5458 -5459 -5460 -5461 -5462 -5463 -5464 -5465 -5466 -5467 -5468 -5469 -5470 -5471 -5472 -5473 -5474 -5475 -5476 -5477 -5478 -5479 -5480 -5481 -5482 -5483 -5484 -5485 -5486 -5487 -5488 -5489 -5490 -5491 -5492 -5493 -5494 -5495 -5496 -5497 -5498 -5499 -5500 -5501 -5502 -5503 -5504 -5505 -5506 -5507 -5508 -5509 -5510 -5511 -5512 -5513 -5514 -5515 -5516 -5517 -5518 -5519 -5520 -5521 -5522 -5523 -5524 -5525 -5526 -5527 -5528 -5529 -5530 -5531 -5532 -5533 -5534 -5535 -5536 -5537 -5538 -5539 -5540 -5541 -5542 -5543 -5544 -5545 -5546 -5547 -5548 -5549 -5550 -5551 -5552 -5553 -5554 -5555 -5556 -5557 -5558 -5559 -5560 -5561 -5562 -5563 -5564 -5565 -5566 -5567 -5568 -5569 -5570 -5571 -5572 -5573 -5574 -5575 -5576 -5577 -5578 -5579 -5580 -5581 -5582 -5583 -5584 -5585 -5586 -5587 -5588 -5589 -5590 -5591 -5592 -5593 -5594 -5595 -5596 -5597 -5598 -5599 -5600 -5601 -5602 -5603 -5604 -5605 -5606 -5607 -5608 -5609 -5610 -5611 -5612 -5613 -5614 -5615 -5616 -5617 -5618 -5619 -5620 -5621 -5622 -5623 -5624 -5625 -5626 -5627 -5628 -5629 -5630 -5631 -5632 -5633 -5634 -5635 -5636 -5637 -5638 -5639 -5640 -5641 -5642 -5643 -5644 -5645 -5646 -5647 -5648 -5649 -5650 -5651 -5652 -5653 -5654 -5655 -5656 -5657 -5658 -5659 -5660 -5661 -5662 -5663 -5664 -5665 -5666 -5667 -5668 -5669 -5670 -5671 -5672 -5673 -5674 -5675 -5676 -5677 -5678 -5679 -5680 -5681 -5682 -5683 -5684 -5685 -5686 -5687 -5688 -5689 -5690 -5691 -5692 -5693 -5694 -5695 -5696 -5697 -5698 -5699 -5700 -5701 -5702 -5703 -5704 -5705 -5706 -5707 -5708 -5709 -5710 -5711 -5712 -5713 -5714 -5715 -5716 -5717 -5718 -5719 -5720 -5721 -5722 -5723 -5724 -5725 -5726 -5727 -5728 -5729 -5730 -5731 -5732 -5733 -5734 -5735 -5736 -5737 -5738 -5739 -5740 -5741 -5742 -5743 -5744 -5745 -5746 -5747 -5748 -5749 -5750 -5751 -5752 -5753 -5754 -5755 -5756 -5757 -5758 -5759 -5760 -5761 -5762 -5763 -5764 -5765 -5766 -5767 -5768 -5769 -5770 -5771 -5772 -5773 -5774 -5775 -5776 -5777 -5778 -5779 -5780 -5781 -5782 -5783 -5784 -5785 -5786 -5787 -5788 -5789 -5790 -5791 -5792 -5793 -5794 -5795 -5796 -5797 -5798 -5799 -5800 -5801 -5802 -5803 -5804 -5805 -5806 -5807 -5808 -5809 -5810 -5811 -5812 -5813 -5814 -5815 -5816 -5817 -5818 -5819 -5820 -5821 -5822 -5823 -5824 -5825 -5826 -5827 -5828 -5829 -5830 -5831 -5832 -5833 -5834 -5835 -5836 -5837 -5838 -5839 -5840 -5841 -5842 -5843 -5844 -5845 -5846 -5847 -5848 -5849 -5850 -5851 -5852 -5853 -5854 -5855 -5856 -5857 -5858 -5859 -5860 -5861 -5862 -5863 -5864 -5865 -5866 -5867 -5868 -5869 -5870 -5871 -5872 -5873 -5874 -5875 -5876 -5877 -5878 -5879 -5880 -5881 -5882 -5883 -5884 -5885 -5886 -5887 -5888 -5889 -5890 -5891 -5892 -5893 -5894 -5895 -5896 -5897 -5898 -5899 -5900 -5901 -5902 -5903 -5904 -5905 -5906 -5907 -5908 -5909 -5910 -5911 -5912 -5913 -5914 -5915 -5916 -5917 -5918 -5919 -5920 -5921 -5922 -5923 -5924 -5925 -5926 -5927 -5928 -5929 -5930 -5931 -5932 -5933 -5934 -5935 -5936 -5937 -5938 -5939 -5940 -5941 -5942 -5943 -5944 -5945 -5946 -5947 -5948 -5949 -5950 -5951 -5952 -5953 -5954 -5955 -5956 -5957 -5958 -5959 -5960 -5961 -5962 -5963 -5964 -5965 -5966 -5967 -5968 -5969 -5970 -5971 -5972 -5973 -5974 -5975 -5976 -5977 -5978 -5979 -5980 -5981 -5982 -5983 -5984 -5985 -5986 -5987 -5988 -5989 -5990 -5991 -5992 -5993 -5994 -5995 -5996 -5997 -5998 -5999 -6000 -6001 -6002 -6003 -6004 -6005 -6006 -6007 -6008 -6009 -6010 -6011 -6012 -6013 -6014 -6015 -6016 -6017 -6018 -6019 -6020 -6021 -6022 -6023 -6024 -6025 -6026 -6027 -6028 -6029 -6030 -6031 -6032 -6033 -6034 -6035 -6036 -6037 -6038 -6039 -6040 -6041 -6042 -6043 -6044 -6045 -6046 -6047 -6048 -6049 -6050 -6051 -6052 -6053 -6054 -6055 -6056 -6057 -6058 -6059 -6060 -6061 -6062 -6063 -6064 -6065 -6066 -6067 -6068 -6069 -6070 -6071 -6072 -6073 -6074 -6075 -6076 -6077 -6078 -6079 -6080 -6081 -6082 -6083 -6084 -6085 -6086 -6087 -6088 -6089 -6090 -6091 -6092 -6093 -6094 -6095 -6096 -6097 -6098 -6099 -6100 -6101 -6102 -6103 -6104 -6105 -6106 -6107 -6108 -6109 -6110 -6111 -6112 -6113 -6114 -6115 -6116 -6117 -6118 -6119 -6120 -6121 -6122 -6123 -6124 -6125 -6126 -6127 -6128 -6129 -6130 -6131 -6132 -6133 -6134 -6135 -6136 -6137 -6138 -6139 -6140 -6141 -6142 -6143 -6144 -6145 -6146 -6147 -6148 -6149 -6150 -6151 -6152 -6153 -6154 -6155 -6156 -6157 -6158 -6159 -6160 -6161 -6162 -6163 -6164 -6165 -6166 -6167 -6168 -6169 -6170 -6171 -6172 -6173 -6174 -6175 -6176 -6177 -6178 -6179 -6180 -6181 -6182 -6183 -6184 -6185 -6186 -6187 -6188 -6189 -6190 -6191 -6192 -6193 -6194 -6195 -6196 -6197 -6198 -6199 -6200 -6201 -6202 -6203 -6204 -6205 -6206 -6207 -6208 -6209 -6210 -6211 -6212 -6213 -6214 -6215 -6216 -6217 -6218 -6219 -6220 -6221 -6222 -6223 -6224 -6225 -6226 -6227 -6228 -6229 -6230 -6231 -6232 -6233 -6234 -6235 -6236 -6237 -6238 -6239 -6240 -6241 -6242 -6243 -6244 -6245 -6246 -6247 -6248 -6249 -6250 -6251 -6252 -6253 -6254 -6255 -6256 -6257 -6258 -6259 -6260 -6261 -6262 -6263 -6264 -6265 -6266 -6267 -6268 -6269 -6270 -6271 -6272 -6273 -6274 -6275 -6276 -6277 -6278 -6279 -6280 -6281 -6282 -6283 -6284 -6285 -6286 -6287 -6288 -6289 -6290 -6291 -6292 -6293 -6294 -6295 -6296 -6297 -6298 -6299 -6300 -6301 -6302 -6303 -6304 -6305 -6306 -6307 -6308 -6309 -6310 -6311 -6312 -6313 -6314 -6315 -6316 -6317 -6318 -6319 -6320 -6321 -6322 -6323 -6324 -6325 -6326 -6327 -6328 -6329 -6330 -6331 -6332 -6333 -6334 -6335 -6336 -6337 -6338 -6339 -6340 -6341 -6342 -6343 -6344 -6345 -6346 -6347 -6348 -6349 -6350 -6351 -6352 -6353 -6354 -6355 -6356 -6357 -6358 -6359 -6360 -6361 -6362 -6363 -6364 -6365 -6366 -6367 -6368 -6369 -6370 -6371 -6372 -6373 -6374 -6375 -6376 -6377 -6378 -6379 -6380 -6381 -6382 -6383 -6384 -6385 -6386 -6387 -6388 -6389 -6390 -6391 -6392 -6393 -6394 -6395 -6396 -6397 -6398 -6399 -6400 -6401 -6402 -6403 -6404 -6405 -6406 -6407 -6408 -6409 -6410 -6411 -6412 -6413 -6414 -6415 -6416 -6417 -6418 -6419 -6420 -6421 -6422 -6423 -6424 -6425 -6426 -6427 -6428 -6429 -6430 -6431 -6432 -6433 -6434 -6435 -6436 -6437 -6438 -6439 -6440 -6441 -6442 -6443 -6444 -6445 -6446 -6447 -6448 -6449 -6450 -6451 -6452 -6453 -6454 -6455 -6456 -6457 -6458 -6459 -6460 -6461 -6462 -6463 -6464 -6465 -6466 -6467 -6468 -6469 -6470 -6471 -6472 -6473 -6474 -6475 -6476 -6477 -6478 -6479 -6480 -6481 -6482 -6483 -6484 -6485 -6486 -6487 -6488 -6489 -6490 -6491 -6492 -6493 -6494 -6495 -6496 -6497 -6498 -6499 -6500 -6501 -6502 -6503 -6504 -6505 -6506 -6507 -6508 -6509 -6510 -6511 -6512 -6513 -6514 -6515 -6516 -6517 -6518 -6519 -6520 -6521 -6522 -6523 -6524 -6525 -6526 -6527 -6528 -6529 -6530 -6531 -6532 -6533 -6534 -6535 -6536 -6537 -6538 -6539 -6540 -6541 -6542 -6543 -6544 -6545 -6546 -6547 -6548 -6549 -6550 -6551 -6552 -6553 -6554 -6555 -6556 -6557 -6558 -6559 -6560 -6561 -6562 -6563 -6564 -6565 -6566 -6567 -6568 -6569 -6570 -6571 -6572 -6573 -6574 -6575 -6576 -6577 -6578 -6579 -6580 -6581 -6582 -6583 -6584 -6585 -6586 -6587 -6588 -6589 -6590 -6591 -6592 -6593 -6594 -6595 -6596 -6597 -6598 -6599 -6600 -6601 -6602 -6603 -6604 -6605 -6606 -6607 -6608 -6609 -6610 -6611 -6612 -6613 -6614 -6615 -6616 -6617 -6618 -6619 -6620 -6621 -6622 -6623 -6624 -6625 -6626 -6627 -6628 -6629 -6630 -6631 -6632 -6633 -6634 -6635 -6636 -6637 -6638 -6639 -6640 -6641 -6642 -6643 -6644 -6645 -6646 -6647 -6648 -6649 -6650 -6651 -6652 -6653 -6654 -6655 -6656 -6657 -6658 -6659 -6660 -6661 -6662 -6663 -6664 -6665 -6666 -6667 -6668 -6669 -6670 -6671 -6672 -6673 -6674 -6675 -6676 -6677 -6678 -6679 -6680 -6681 -6682 -6683 -6684 -6685 -6686 -6687 -6688 -6689 -6690 -6691 -6692 -6693 -6694 -6695 -6696 -6697 -6698 -6699 -6700 -6701 -6702 -6703 -6704 -6705 -6706 -6707 -6708 -6709 -6710 -6711 -6712 -6713 -6714 -6715 -6716 -6717 -6718 -6719 -6720 -6721 -6722 -6723 -6724 -6725 -6726 -6727 -6728 -6729 -6730 -6731 -6732 -6733 -6734 -6735 -6736 -6737 -6738 -6739 -6740 -6741 -6742 -6743 -6744 -6745 -6746 -6747 -6748 -6749 -6750 -6751 -6752 -6753 -6754 -6755 -6756 -6757 -6758 -6759 -6760 -6761 -6762 -6763 -6764 -6765 -6766 -6767 -6768 -6769 -6770 -6771 -6772 -6773 -6774 -6775 -6776 -6777 -6778 -6779 -6780 -6781 -6782 -6783 -6784 -6785 -6786 -6787 -6788 -6789 -6790 -6791 -6792 -6793 -6794 -6795 -6796 -6797 -6798 -6799 -6800 -6801 -6802 -6803 -6804 -6805 -6806 -6807 -6808 -6809 -6810 -6811 -6812 -6813 -6814 -6815 -6816 -6817 -6818 -6819 -6820 -6821 -6822 -6823 -6824 -6825 -6826 -6827 -6828 -6829 -6830 -6831 -6832 -6833 -6834 -6835 -6836 -6837 -6838 -6839 -6840 -6841 -6842 -6843 -6844 -6845 -6846 -6847 -6848 -6849 -6850 -6851 -6852 -6853 -6854 -6855 -6856 -6857 -6858 -6859 -6860 -6861 -6862 -6863 -6864 -6865 -6866 -6867 -6868 -6869 -6870 -6871 -6872 -6873 -6874 -6875 -6876 -6877 -6878 -6879 -6880 -6881 -6882 -6883 -6884 -6885 -6886 -6887 -6888 -6889 -6890 -6891 -6892 -6893 -6894 -6895 -6896 -6897 -6898 -6899 -6900 -6901 -6902 -6903 -6904 -6905 -6906 -6907 -6908 -6909 -6910 -6911 -6912 -6913 -6914 -6915 -6916 -6917 -6918 -6919 -6920 -6921 -6922 -6923 -6924 -6925 -6926 -6927 -6928 -6929 -6930 -6931 -6932 -6933 -6934 -6935 -6936 -6937 -6938 -6939 -6940 -6941 -6942 -6943 -6944 -6945 -6946 -6947 -6948 -6949 -6950 -6951 -6952 -6953 -6954 -6955 -6956 -6957 -6958 -6959 -6960 -6961 -6962 -6963 -6964 -6965 -6966 -6967 -6968 -6969 -6970 -6971 -6972 -6973 -6974 -6975 -6976 -6977 -6978 -6979 -6980 -6981 -6982 -6983 -6984 -6985 -6986 -6987 -6988 -6989 -6990 -6991 -6992 -6993 -6994 -6995 -6996 -6997 -6998 -6999 -7000 -7001 -7002 -7003 -7004 -7005 -7006 -7007 -7008 -7009 -7010 -7011 -7012 -7013 -7014 -7015 -7016 -7017 -7018 -7019 -7020 -7021 -7022 -7023 -7024 -7025 -7026 -7027 -7028 -7029 -7030 -7031 -7032 -7033 -7034 -7035 -7036 -7037 -7038 -7039 -7040 -7041 -7042 -7043 -7044 -7045 -7046 -7047 -7048 -7049 -7050 -7051 -7052 -7053 -7054 -7055 -7056 -7057 -7058 -7059 -7060 -7061 -7062 -7063 -7064 -7065 -7066 -7067 -7068 -7069 -7070 -7071 -7072 -7073 -7074 -7075 -7076 -7077 -7078 -7079 -7080 -7081 -7082 -7083 -7084 -7085 -7086 -7087 -7088 -7089 -7090 -7091 -7092 -7093 -7094 -7095 -7096 -7097 -7098 -7099 -7100 -7101 -7102 -7103 -7104 -7105 -7106 -7107 -7108 -7109 -7110 -7111 -7112 -7113 -7114 -7115 -7116 -7117 -7118 -7119 -7120 -7121 -7122 -7123 -7124 -7125 -7126 -7127 -7128 -7129 -7130 -7131 -7132 -7133 -7134 -7135 -7136 -7137 -7138 -7139 -7140 -7141 -7142 -7143 -7144 -7145 -7146 -7147 -7148 -7149 -7150 -7151 -7152 -7153 -7154 -7155 -7156 -7157 -7158 -7159 -7160 -7161 -7162 -7163 -7164 -7165 -7166 -7167 -7168 -7169 -7170 -7171 -7172 -7173 -7174 -7175 -7176 -7177 -7178 -7179 -7180 -7181 -7182 -7183 -7184 -7185 -7186 -7187 -7188 -7189 -7190 -7191 -7192 -7193 -7194 -7195 -7196 -7197 -7198 -7199 -7200 -7201 -7202 -7203 -7204 -7205 -7206 -7207 -7208 -7209 -7210 -7211 -7212 -7213 -7214 -7215 -7216 -7217 -7218 -7219 -7220 -7221 -7222 -7223 -7224 -7225 -7226 -7227 -7228 -7229 -7230 -7231 -7232 -7233 -7234 -7235 -7236 -7237 -7238 -7239 -7240 -7241 -7242 -7243 -7244 -7245 -7246 -7247 -7248 -7249 -7250 -7251 -7252 -7253 -7254 -7255 -7256 -7257 -7258 -7259 -7260 -7261 -7262 -7263 -7264 -7265 -7266 -7267 -7268 -7269 -7270 -7271 -7272 -7273 -7274 -7275 -7276 -7277 -7278 -7279 -7280 -7281 -7282 -7283 -7284 -7285 -7286 -7287 -7288 -7289 -7290 -7291 -7292 -7293 -7294 -7295 -7296 -7297 -7298 -7299 -7300 -7301 -7302 -7303 -7304 -7305 -7306 -7307 -7308 -7309 -7310 -7311 -7312 -7313 -7314 -7315 -7316 -7317 -7318 -7319 -7320 -7321 -7322 -7323 -7324 -7325 -7326 -7327 -7328 -7329 -7330 -7331 -7332 -7333 -7334 -7335 -7336 -7337 -7338 -7339 -7340 -7341 -7342 -7343 -7344 -7345 -7346 -7347 -7348 -7349 -7350 -7351 -7352 -7353 -7354 -7355 -7356 -7357 -7358 -7359 -7360 -7361 -7362 -7363 -7364 -7365 -7366 -7367 -7368 -7369 -7370 -7371 -7372 -7373 -7374 -7375 -7376 -7377 -7378 -7379 -7380 -7381 -7382 -7383 -7384 -7385 -7386 -7387 -7388 -7389 -7390 -7391 -7392 -7393 -7394 -7395 -7396 -7397 -7398 -7399 -7400 -7401 -7402 -7403 -7404 -7405 -7406 -7407 -7408 -7409 -7410 -7411 -7412 -7413 -7414 -7415 -7416 -7417 -7418 -7419 -7420 -7421 -7422 -7423 -7424 -7425 -7426 -7427 -7428 -7429 -7430 -7431 -7432 -7433 -7434 -7435 -7436 -7437 -7438 -7439 -7440 -7441 -7442 -7443 -7444 -7445 -7446 -7447 -7448 -7449 -7450 -7451 -7452 -7453 -7454 -7455 -7456 -7457 -7458 -7459 -7460 -7461 -7462 -7463 -7464 -7465 -7466 -7467 -7468 -7469 -7470 -7471 -7472 -7473 -7474 -7475 -7476 -7477 -7478 -7479 -7480 -7481 -7482 -7483 -7484 -7485 -7486 -7487 -7488 -7489 -7490 -7491 -7492 -7493 -7494 -7495 -7496 -7497 -7498 -7499 -7500 -7501 -7502 -7503 -7504 -7505 -7506 -7507 -7508 -7509 -7510 -7511 -7512 -7513 -7514 -7515 -7516 -7517 -7518 -7519 -7520 -7521 -7522 -7523 -7524 -7525 -7526 -7527 -7528 -7529 -7530 -7531 -7532 -7533 -7534 -7535 -7536 -7537 -7538 -7539 -7540 -7541 -7542 -7543 -7544 -7545 -7546 -7547 -7548 -7549 -7550 -7551 -7552 -7553 -7554 -7555 -7556 -7557 -7558 -7559 -7560 -7561 -7562 -7563 -7564 -7565 -7566 -7567 -7568 -7569 -7570 -7571 -7572 -7573 -7574 -7575 -7576 -7577 -7578 -7579 -7580 -7581 -7582 -7583 -7584 -7585 -7586 -7587 -7588 -7589 -7590 -7591 -7592 -7593 -7594 -7595 -7596 -7597 -7598 -7599 -7600 -7601 -7602 -7603 -7604 -7605 -7606 -7607 -7608 -7609 -7610 -7611 -7612 -7613 -7614 -7615 -7616 -7617 -7618 -7619 -7620 -7621 -7622 -7623 -7624 -7625 -7626 -7627 -7628 -7629 -7630 -7631 -7632 -7633 -7634 -7635 -7636 -7637 -7638 -7639 -7640 -7641 -7642 -7643 -7644 -7645 -7646 -7647 -7648 -7649 -7650 -7651 -7652 -7653 -7654 -7655 -7656 -7657 -7658 -7659 -7660 -7661 -7662 -7663 -7664 -7665 -7666 -7667 -7668 -7669 -7670 -7671 -7672 -7673 -7674 -7675 -7676 -7677 -7678 -7679 -7680 -7681 -7682 -7683 -7684 -7685 -7686 -7687 -7688 -7689 -7690 -7691 -7692 -7693 -7694 -7695 -7696 -7697 -7698 -7699 -7700 -7701 -7702 -7703 -7704 -7705 -7706 -7707 -7708 -7709 -7710 -7711 -7712 -7713 -7714 -7715 -7716 -7717 -7718 -7719 -7720 -7721 -7722 -7723 -7724 -7725 -7726 -7727 -7728 -7729 -7730 -7731 -7732 -7733 -7734 -7735 -7736 -7737 -7738 -7739 -7740 -7741 -7742 -7743 -7744 -7745 -7746 -7747 -7748 -7749 -7750 -7751 -7752 -7753 -7754 -7755 -7756 -7757 -7758 -7759 -7760 -7761 -7762 -7763 -7764 -7765 -7766 -7767 -7768 -7769 -7770 -7771 -7772 -7773 -7774 -7775 -7776 -7777 -7778 -7779 -7780 -7781 -7782 -7783 -7784 -7785 -7786 -7787 -7788 -7789 -7790 -7791 -7792 -7793 -7794 -7795 -7796 -7797 -7798 -7799 -7800 -7801 -7802 -7803 -7804 -7805 -7806 -7807 -7808 -7809 -7810 -7811 -7812 -7813 -7814 -7815 -7816 -7817 -7818 -7819 -7820 -7821 -7822 -7823 -7824 -7825 -7826 -7827 -7828 -7829 -7830 -7831 -7832 -7833 -7834 -7835 -7836 -7837 -7838 -7839 -7840 -7841 -7842 -7843 -7844 -7845 -7846 -7847 -7848 -7849 -7850 -7851 -7852 -7853 -7854 -7855 -7856 -7857 -7858 -7859 -7860 -7861 -7862 -7863 -7864 -7865 -7866 -7867 -7868 -7869 -7870 -7871 -7872 -7873 -7874 -7875 -7876 -7877 -7878 -7879 -7880 -7881 -7882 -7883 -7884 -7885 -7886 -7887 -7888 -7889 -7890 -7891 -7892 -7893 -7894 -7895 -7896 -7897 -7898 -7899 -7900 -7901 -7902 -7903 -7904 -7905 -7906 -7907 -7908 -7909 -7910 -7911 -7912 -7913 -7914 -7915 -7916 -7917 -7918 -7919 -7920 -7921 -7922 -7923 -7924 -7925 -7926 -7927 -7928 -7929 -7930 -7931 -7932 -7933 -7934 -7935 -7936 -7937 -7938 -7939 -7940 -7941 -7942 -7943 -7944 -7945 -7946 -7947 -7948 -7949 -7950 -7951 -7952 -7953 -7954 -7955 -7956 -7957 -7958 -7959 -7960 -7961 -7962 -7963 -7964 -7965 -7966 -7967 -7968 -7969 -7970 -7971 -7972 -7973 -7974 -7975 -7976 -7977 -7978 -7979 -7980 -7981 -7982 -7983 -7984 -7985 -7986 -7987 -7988 -7989 -7990 -7991 -7992 -7993 -7994 -7995 -7996 -7997 -7998 -7999 -8000 -8001 -8002 -8003 -8004 -8005 -8006 -8007 -8008 -8009 -8010 -8011 -8012 -8013 -8014 -8015 -8016 -8017 -8018 -8019 -8020 -8021 -8022 -8023 -8024 -8025 -8026 -8027 -8028 -8029 -8030 -8031 -8032 -8033 -8034 -8035 -8036 -8037 -8038 -8039 -8040 -8041 -8042 -8043 -8044 -8045 -8046 -8047 -8048 -8049 -8050 -8051 -8052 -8053 -8054 -8055 -8056 -8057 -8058 -8059 -8060 -8061 -8062 -8063 -8064 -8065 -8066 -8067 -8068 -8069 -8070 -8071 -8072 -8073 -8074 -8075 -8076 -8077 -8078 -8079 -8080 -8081 -8082 -8083 -8084 -8085 -8086 -8087 -8088 -8089 -8090 -8091 -8092 -8093 -8094 -8095 -8096 -8097 -8098 -8099 -8100 -8101 -8102 -8103 -8104 -8105 -8106 -8107 -8108 -8109 -8110 -8111 -8112 -8113 -8114 -8115 -8116 -8117 -8118 -8119 -8120 -8121 -8122 -8123 -8124 -8125 -8126 -8127 -8128 -8129 -8130 -8131 -8132 -8133 -8134 -8135 -8136 -8137 -8138 -8139 -8140 -8141 -8142 -8143 -8144 -8145 -8146 -8147 -8148 -8149 -8150 -8151 -8152 -8153 -8154 -8155 -8156 -8157 -8158 -8159 -8160 -8161 -8162 -8163 -8164 -8165 -8166 -8167 -8168 -8169 -8170 -8171 -8172 -8173 -8174 -8175 -8176 -8177 -8178 -8179 -8180 -8181 -8182 -8183 -8184 -8185 -8186 -8187 -8188 -8189 -8190 -8191 -8192 -8193 -8194 -8195 -8196 -8197 -8198 -8199 -8200 -8201 -8202 -8203 -8204 -8205 -8206 -8207 -8208 -8209 -8210 -8211 -8212 -8213 -8214 -8215 -8216 -8217 -8218 -8219 -8220 -8221 -8222 -8223 -8224 -8225 -8226 -8227 -8228 -8229 -8230 -8231 -8232 -8233 -8234 -8235 -8236 -8237 -8238 -8239 -8240 -8241 -8242 -8243 -8244 -8245 -8246 -8247 -8248 -8249 -8250 -8251 -8252 -8253 -8254 -8255 -8256 -8257 -8258 -8259 -8260 -8261 -8262 -8263 -8264 -8265 -8266 -8267 -8268 -8269 -8270 -8271 -8272 -8273 -8274 -8275 -8276 -8277 -8278 -8279 -8280 -8281 -8282 -8283 -8284 -8285 -8286 -8287 -8288 -8289 -8290 -8291 -8292 -8293 -8294 -8295 -8296 -8297 -8298 -8299 -8300 -8301 -8302 -8303 -8304 -8305 -8306 -8307 -8308 -8309 -8310 -8311 -8312 -8313 -8314 -8315 -8316 -8317 -8318 -8319 -8320 -8321 -8322 -8323 -8324 -8325 -8326 -8327 -8328 -8329 -8330 -8331 -8332 -8333 -8334 -8335 -8336 -8337 -8338 -8339 -8340 -8341 -8342 -8343 -8344 -8345 -8346 -8347 -8348 -8349 -8350 -8351 -8352 -8353 -8354 -8355 -8356 -8357 -8358 -8359 -8360 -8361 -8362 -8363 -8364 -8365 -8366 -8367 -8368 -8369 -8370 -8371 -8372 -8373 -8374 -8375 -8376 -8377 -8378 -8379 -8380 -8381 -8382 -8383 -8384 -8385 -8386 -8387 -8388 -8389 -8390 -8391 -8392 -8393 -8394 -8395 -8396 -8397 -8398 -8399 -8400 -8401 -8402 -8403 -8404 -8405 -8406 -8407 -8408 -8409 -8410 -8411 -8412 -8413 -8414 -8415 -8416 -8417 -8418 -8419 -8420 -8421 -8422 -8423 -8424 -8425 -8426 -8427 -8428 -8429 -8430 -8431 -8432 -8433 -8434 -8435 -8436 -8437 -8438 -8439 -8440 -8441 -8442 -8443 -8444 -8445 -8446 -8447 -8448 -8449 -8450 -8451 -8452 -8453 -8454 -8455 -8456 -8457 -8458 -8459 -8460 -8461 -8462 -8463 -8464 -8465 -8466 -8467 -8468 -8469 -8470 -8471 -8472 -8473 -8474 -8475 -8476 -8477 -8478 -8479 -8480 -8481 -8482 -8483 -8484 -8485 -8486 -8487 -8488 -8489 -8490 -8491 -8492 -8493 -8494 -8495 -8496 -8497 -8498 -8499 -8500 -8501 -8502 -8503 -8504 -8505 -8506 -8507 -8508 -8509 -8510 -8511 -8512 -8513 -8514 -8515 -8516 -8517 -8518 -8519 -8520 -8521 -8522 -8523 -8524 -8525 -8526 -8527 -8528 -8529 -8530 -8531 -8532 -8533 -8534 -8535 -8536 -8537 -8538 -8539 -8540 -8541 -8542 -8543 -8544 -8545 -8546 -8547 -8548 -8549 -8550 -8551 -8552 -8553 -8554 -8555 -8556 -8557 -8558 -8559 -8560 -8561 -8562 -8563 -8564 -8565 -8566 -8567 -8568 -8569 -8570 -8571 -8572 -8573 -8574 -8575 -8576 -8577 -8578 -8579 -8580 -8581 -8582 -8583 -8584 -8585 -8586 -8587 -8588 -8589 -8590 -8591 -8592 -8593 -8594 -8595 -8596 -8597 -8598 -8599 -8600 -8601 -8602 -8603 -8604 -8605 -8606 -8607 -8608 -8609 -8610 -8611 -8612 -8613 -8614 -8615 -8616 -8617 -8618 -8619 -8620 -8621 -8622 -8623 -8624 -8625 -8626 -8627 -8628 -8629 -8630 -8631 -8632 -8633 -8634 -8635 -8636 -8637 -8638 -8639 -8640 -8641 -8642 -8643 -8644 -8645 -8646 -8647 -8648 -8649 -8650 -8651 -8652 -8653 -8654 -8655 -8656 -8657 -8658 -8659 -8660 -8661 -8662 -8663 -8664 -8665 -8666 -8667 -8668 -8669 -8670 -8671 -8672 -8673 -8674 -8675 -8676 -8677 -8678 -8679 -8680 -8681 -8682 -8683 -8684 -8685 -8686 -8687 -8688 -8689 -8690 -8691 -8692 -8693 -8694 -8695 -8696 -8697 -8698 -8699 -8700 -8701 -8702 -8703 -8704 -8705 -8706 -8707 -8708 -8709 -8710 -8711 -8712 -8713 -8714 -8715 -8716 -8717 -8718 -8719 -8720 -8721 -8722 -8723 -8724 -8725 -8726 -8727 -8728 -8729 -8730 -8731 -8732 -8733 -8734 -8735 -8736 -8737 -8738 -8739 -8740 -8741 -8742 -8743 -8744 -8745 -8746 -8747 -8748 -8749 -8750 -8751 -8752 -8753 -8754 -8755 -8756 -8757 -8758 -8759 -8760 -8761 -8762 -8763 -8764 -8765 -8766 -8767 -8768 -8769 -8770 -8771 -8772 -8773 -8774 -8775 -8776 -8777 -8778 -8779 -8780 -8781 -8782 -8783 -8784 -8785 -8786 -8787 -8788 -8789 -8790 -8791 -8792 -8793 -8794 -8795 -8796 -8797 -8798 -8799 -8800 -8801 -8802 -8803 -8804 -8805 -8806 -8807 -8808 -8809 -8810 -8811 -8812 -8813 -8814 -8815 -8816 -8817 -8818 -8819 -8820 -8821 -8822 -8823 -8824 -8825 -8826 -8827 -8828 -8829 -8830 -8831 -8832 -8833 -8834 -8835 -8836 -8837 -8838 -8839 -8840 -8841 -8842 -8843 -8844 -8845 -8846 -8847 -8848 -8849 -8850 -8851 -8852 -8853 -8854 -8855 -8856 -8857 -8858 -8859 -8860 -8861 -8862 -8863 -8864 -8865 -8866 -8867 -8868 -8869 -8870 -8871 -8872 -8873 -8874 -8875 -8876 -8877 -8878 -8879 -8880 -8881 -8882 -8883 -8884 -8885 -8886 -8887 -8888 -8889 -8890 -8891 -8892 -8893 -8894 -8895 -8896 -8897 -8898 -8899 -8900 -8901 -8902 -8903 -8904 -8905 -8906 -8907 -8908 -8909 -8910 -8911 -8912 -8913 -8914 -8915 -8916 -8917 -8918 -8919 -8920 -8921 -8922 -8923 -8924 -8925 -8926 -8927 -8928 -8929 -8930 -8931 -8932 -8933 -8934 -8935 -8936 -8937 -8938 -8939 -8940 -8941 -8942 -8943 -8944 -8945 -8946 -8947 -8948 -8949 -8950 -8951 -8952 -8953 -8954 -8955 -8956 -8957 -8958 -8959 -8960 -8961 -8962 -8963 -8964 -8965 -8966 -8967 -8968 -8969 -8970 -8971 -8972 -8973 -8974 -8975 -8976 -8977 -8978 -8979 -8980 -8981 -8982 -8983 -8984 -8985 -8986 -8987 -8988 -8989 -8990 -8991 -8992 -8993 -8994 -8995 -8996 -8997 -8998 -8999 -9000 -9001 -9002 -9003 -9004 -9005 -9006 -9007 -9008 -9009 -9010 -9011 -9012 -9013 -9014 -9015 -9016 -9017 -9018 -9019 -9020 -9021 -9022 -9023 -9024 -9025 -9026 -9027 -9028 -9029 -9030 -9031 -9032 -9033 -9034 -9035 -9036 -9037 -9038 -9039 -9040 -9041 -9042 -9043 -9044 -9045 -9046 -9047 -9048 -9049 -9050 -9051 -9052 -9053 -9054 -9055 -9056 -9057 -9058 -9059 -9060 -9061 -9062 -9063 -9064 -9065 -9066 -9067 -9068 -9069 -9070 -9071 -9072 -9073 -9074 -9075 -9076 -9077 -9078 -9079 -9080 -9081 -9082 -9083 -9084 -9085 -9086 -9087 -9088 -9089 -9090 -9091 -9092 -9093 -9094 -9095 -9096 -9097 -9098 -9099 -9100 -9101 -9102 -9103 -9104 -9105 -9106 -9107 -9108 -9109 -9110 -9111 -9112 -9113 -9114 -9115 -9116 -9117 -9118 -9119 -9120 -9121 -9122 -9123 -9124 -9125 -9126 -9127 -9128 -9129 -9130 -9131 -9132 -9133 -9134 -9135 -9136 -9137 -9138 -9139 -9140 -9141 -9142 -9143 -9144 -9145 -9146 -9147 -9148 -9149 -9150 -9151 -9152 -9153 -9154 -9155 -9156 -9157 -9158 -9159 -9160 -9161 -9162 -9163 -9164 -9165 -9166 -9167 -9168 -9169 -9170 -9171 -9172 -9173 -9174 -9175 -9176 -9177 -9178 -9179 -9180 -9181 -9182 -9183 -9184 -9185 -9186 -9187 -9188 -9189 -9190 -9191 -9192 -9193 -9194 -9195 -9196 -9197 -9198 -9199 -9200 -9201 -9202 -9203 -9204 -9205 -9206 -9207 -9208 -9209 -9210 -9211 -9212 -9213 -9214 -9215 -9216 -9217 -9218 -9219 -9220 -9221 -9222 -9223 -9224 -9225 -9226 -9227 -9228 -9229 -9230 -9231 -9232 -9233 -9234 -9235 -9236 -9237 -9238 -9239 -9240 -9241 -9242 -9243 -9244 -9245 -9246 -9247 -9248 -9249 -9250 -9251 -9252 -9253 -9254 -9255 -9256 -9257 -9258 -9259 -9260 -9261 -9262 -9263 -9264 -9265 -9266 -9267 -9268 -9269 -9270 -9271 -9272 -9273 -9274 -9275 -9276 -9277 -9278 -9279 -9280 -9281 -9282 -9283 -9284 -9285 -9286 -9287 -9288 -9289 -9290 -9291 -9292 -9293 -9294 -9295 -9296 -9297 -9298 -9299 -9300 -9301 -9302 -9303 -9304 -9305 -9306 -9307 -9308 -9309 -9310 -9311 -9312 -9313 -9314 -9315 -9316 -9317 -9318 -9319 -9320 -9321 -9322 -9323 -9324 -9325 -9326 -9327 -9328 -9329 -9330 -9331 -9332 -9333 -9334 -9335 -9336 -9337 -9338 -9339 -9340 -9341 -9342 -9343 -9344 -9345 -9346 -9347 -9348 -9349 -9350 -9351 -9352 -9353 -9354 -9355 -9356 -9357 -9358 -9359 -9360 -9361 -9362 -9363 -9364 -9365 -9366 -9367 -9368 -9369 -9370 -9371 -9372 -9373 -9374 -9375 -9376 -9377 -9378 -9379 -9380 -9381 -9382 -9383 -9384 -9385 -9386 -9387 -9388 -9389 -9390 -9391 -9392 -9393 -9394 -9395 -9396 -9397 -9398 -9399 -9400 -9401 -9402 -9403 -9404 -9405 -9406 -9407 -9408 -9409 -9410 -9411 -9412 -9413 -9414 -9415 -9416 -9417 -9418 -9419 -9420 -9421 -9422 -9423 -9424 -9425 -9426 -9427 -9428 -9429 -9430 -9431 -9432 -9433 -9434 -9435 -9436 -9437 -9438 -9439 -9440 -9441 -9442 -9443 -9444 -9445 -9446 -9447 -9448 -9449 -9450 -9451 -9452 -9453 -9454 -9455 -9456 -9457 -9458 -9459 -9460 -9461 -9462 -9463 -9464 -9465 -9466 -9467 -9468 -9469 -9470 -9471 -9472 -9473 -9474 -9475 -9476 -9477 -9478 -9479 -9480 -9481 -9482 -9483 -9484 -9485 -9486 -9487 -9488 -9489 -9490 -9491 -9492 -9493 -9494 -9495 -9496 -9497 -9498 -9499 -9500 -9501 -9502 -9503 -9504 -9505 -9506 -9507 -9508 -9509 -9510 -9511 -9512 -9513 -9514 -9515 -9516 -9517 -9518 -9519 -9520 -9521 -9522 -9523 -9524 -9525 -9526 -9527 -9528 -9529 -9530 -9531 -9532 -9533 -9534 -9535 -9536 -9537 -9538 -9539 -9540 -9541 -9542 -9543 -9544 -9545 -9546 -9547 -9548 -9549 -9550 -9551 -9552 -9553 -9554 -9555 -9556 -9557 -9558 -9559 -9560 -9561 -9562 -9563 -9564 -9565 -9566 -9567 -9568 -9569 -9570 -9571 -9572 -9573 -9574 -9575 -9576 -9577 -9578 -9579 -9580 -9581 -9582 -9583 -9584 -9585 -9586 -9587 -9588 -9589 -9590 -9591 -9592 -9593 -9594 -9595 -9596 -9597 -9598 -9599 -9600 -9601 -9602 -9603 -9604 -9605 -9606 -9607 -9608 -9609 -9610 -9611 -9612 -9613 -9614 -9615 -9616 -9617 -9618 -9619 -9620 -9621 -9622 -9623 -9624 -9625 -9626 -9627 -9628 -9629 -9630 -9631 -9632 -9633 -9634 -9635 -9636 -9637 -9638 -9639 -9640 -9641 -9642 -9643 -9644 -9645 -9646 -9647 -9648 -9649 -9650 -9651 -9652 -9653 -9654 -9655 -9656 -9657 -9658 -9659 -9660 -9661 -9662 -9663 -9664 -9665 -9666 -9667 -9668 -9669 -9670 -9671 -9672 -9673 -9674 -9675 -9676 -9677 -9678 -9679 -9680 -9681 -9682 -9683 -9684 -9685 -9686 -9687 -9688 -9689 -9690 -9691 -9692 -9693 -9694 -9695 -9696 -9697 -9698 -9699 -9700 -9701 -9702 -9703 -9704 -9705 -9706 -9707 -9708 -9709 -9710 -9711 -9712 -9713 -9714 -9715 -9716 -9717 -9718 -9719 -9720 -9721 -9722 -9723 -9724 -9725 -9726 -9727 -9728 -9729 -9730 -9731 -9732 -9733 -9734 -9735 -9736 -9737 -9738 -9739 -9740 -9741 -9742 -9743 -9744 -9745 -9746 -9747 -9748 -9749 -9750 -9751 -9752 -9753 -9754 -9755 -9756 -9757 -9758 -9759 -9760 -9761 -9762 -9763 -9764 -9765 -9766 -9767 -9768 -9769 -9770 -9771 -9772 -9773 -9774 -9775 -9776 -9777 -9778 -9779 -9780 -9781 -9782 -9783 -9784 -9785 -9786 -9787 -9788 -9789 -9790 -9791 -9792 -9793 -9794 -9795 -9796 -9797 -9798 -9799 -9800 -9801 -9802 -9803 -9804 -9805 -9806 -9807 -9808 -9809 -9810 -9811 -9812 -9813 -9814 -9815 -9816 -9817 -9818 -9819 -9820 -9821 -9822 -9823 -9824 -9825 -9826 -9827 -9828 -9829 -9830 -9831 -9832 -9833 -9834 -9835 -9836 -9837 -9838 -9839 -9840 -9841 -9842 -9843 -9844 -9845 -9846 -9847 -9848 -9849 -9850 -9851 -9852 -9853 -9854 -9855 -9856 -9857 -9858 -9859 -9860 -9861 -9862 -9863 -9864 -9865 -9866 -9867 -9868 -9869 -9870 -9871 -9872 -9873 -9874 -9875 -9876 -9877 -9878 -9879 -9880 -9881 -9882 -9883 -9884 -9885 -9886 -9887 -9888 -9889 -9890 -9891 -9892 -9893 -9894 -9895 -9896 -9897 -9898 -9899 -9900 -9901 -9902 -9903 -9904 -9905 -9906 -9907 -9908 -9909 -9910 -9911 -9912 -9913 -9914 -9915 -9916 -9917 -9918 -9919 -9920 -9921 -9922 -9923 -9924 -9925 -9926 -9927 -9928 -9929 -9930 -9931 -9932 -9933 -9934 -9935 -9936 -9937 -9938 -9939 -9940 -9941 -9942 -9943 -9944 -9945 -9946 -9947 -9948 -9949 -9950 -9951 -9952 -9953 -9954 -9955 -9956 -9957 -9958 -9959 -9960 -9961 -9962 -9963 -9964 -9965 -9966 -9967 -9968 -9969 -9970 -9971 -9972 -9973 -9974 -9975 -9976 -9977 -9978 -9979 -9980 -9981 -9982 -9983 -9984 -9985 -9986 -9987 -9988 -9989 -9990 -9991 -9992 -9993 -9994 -9995 -9996 -9997 -9998 -9999 diff --git a/core-java-modules/core-java-nio-2/pom.xml b/core-java-modules/core-java-nio-2/pom.xml index cd5c87d44e..2e67bff30a 100644 --- a/core-java-modules/core-java-nio-2/pom.xml +++ b/core-java-modules/core-java-nio-2/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 core-java-nio-2 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/lock/FileLocks.java b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/lock/FileLocks.java new file mode 100644 index 0000000000..4b65221708 --- /dev/null +++ b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/lock/FileLocks.java @@ -0,0 +1,148 @@ +package com.baeldung.lock; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.NonReadableChannelException; +import java.nio.channels.NonWritableChannelException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; + +public class FileLocks { + + private static final Logger LOG = LoggerFactory.getLogger(FileLocks.class); + + // Write locks + + /** + * Trying to get an exclusive lock on a read-only FileChannel won't work. + */ + static void getExclusiveLockFromInputStream() throws IOException { + Path path = Files.createTempFile("foo", "txt"); + try (FileInputStream fis = new FileInputStream(path.toFile()); + FileLock lock = fis.getChannel() + .lock()) { + LOG.debug("This won't happen"); + } catch (NonWritableChannelException e) { + LOG.error("The channel obtained through a FileInputStream isn't writable. You can't obtain an exclusive lock on it!"); + throw e; + } + } + + /** + * Gets an exclusive lock from a RandomAccessFile. Works because the file is writable. + * @param from beginning of the locked region + * @param size how many bytes to lock + * @return A lock object representing the newly-acquired lock + * @throws IOException if there is a problem creating the temporary file + */ + static FileLock getExclusiveLockFromRandomAccessFile(long from, long size) throws IOException { + Path path = Files.createTempFile("foo", "txt"); + try (RandomAccessFile file = new RandomAccessFile(path.toFile(), "rw"); + FileLock lock = file.getChannel() + .lock(from, size, false)) { + if (lock.isValid()) { + LOG.debug("This is a valid exclusive lock"); + return lock; + } + return null; + } catch (Exception e) { + LOG.error(e.getMessage()); + } + return null; + } + + /** + * Acquires an exclusive lock on a file region. + * @param from beginning of the locked region + * @param size how many bytes to lock + * @return A lock object representing the newly-acquired lock + * @throws IOException if there is a problem creating the temporary file + */ + static FileLock getExclusiveLockFromFileChannelOpen(long from, long size) throws IOException { + Path path = Files.createTempFile("foo", "txt"); + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.APPEND); FileLock lock = channel.lock(from, size, false)) { + String text = "Hello, world."; + ByteBuffer buffer = ByteBuffer.allocate(text.length() + System.lineSeparator() + .length()); + buffer.put((text + System.lineSeparator()).getBytes(StandardCharsets.UTF_8)); + buffer.flip(); + while (buffer.hasRemaining()) { + channel.write(buffer, channel.size()); + } + LOG.debug("This was written to the file"); + Files.lines(path) + .forEach(LOG::debug); + return lock; + } + } + + // Read locks + + /** + * Trying to get a shared lock on a write-only FileChannel won't work. + */ + static void getReadLockFromOutputStream() throws IOException { + Path path = Files.createTempFile("foo", "txt"); + try (FileOutputStream fis = new FileOutputStream(path.toFile()); + FileLock lock = fis.getChannel() + .lock(0, Long.MAX_VALUE, true)) { + LOG.debug("This won't happen"); + } catch (NonReadableChannelException e) { + LOG.error("The channel obtained through a FileOutputStream isn't readable. " + "You can't obtain an shared lock on it!"); + throw e; + } + } + + /** + * Gets a lock from an InputStream. + * @param from beginning of the locked region + * @param size how many bytes to lock + * @return A lock object representing the newly-acquired lock + * @throws IOException if there is a problem creating the temporary file + */ + static FileLock getReadLockFromInputStream(long from, long size) throws IOException { + Path path = Files.createTempFile("foo", "txt"); + try (FileInputStream fis = new FileInputStream(path.toFile()); + FileLock lock = fis.getChannel() + .lock(from, size, true)) { + if (lock.isValid()) { + LOG.debug("This is a valid shared lock"); + return lock; + } + return null; + } + } + + /** + * Gets an exclusive lock from a RandomAccessFile. Works because the file is readable. + * @param from beginning of the locked region + * @param size how many bytes to lock + * @return A lock object representing the newly-acquired lock + * @throws IOException if there is a problem creating the temporary file + */ + static FileLock getReadLockFromRandomAccessFile(long from, long size) throws IOException { + Path path = Files.createTempFile("foo", "txt"); + try (RandomAccessFile file = new RandomAccessFile(path.toFile(), "r"); // could also be "rw", but "r" is sufficient for reading + FileLock lock = file.getChannel() + .lock(from, size, true)) { + if (lock.isValid()) { + LOG.debug("This is a valid shared lock"); + return lock; + } + } catch (Exception e) { + LOG.error(e.getMessage()); + } + return null; + } + +} diff --git a/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/lock/FileLocksUnitTest.java b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/lock/FileLocksUnitTest.java new file mode 100644 index 0000000000..1de988a87b --- /dev/null +++ b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/lock/FileLocksUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.lock; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.channels.FileLock; +import java.nio.channels.NonReadableChannelException; +import java.nio.channels.NonWritableChannelException; + +import org.junit.jupiter.api.Test; + +class FileLocksUnitTest { + + @Test + void givenAnInputStream_whenGetWriteLock_thenThrowNonWritableChannelException() { + assertThrows(NonWritableChannelException.class, () -> FileLocks.getExclusiveLockFromInputStream()); + } + + @Test + void givenARandomAccessFileWithReadWriteAccess_whenGetWriteLock_thenLock() throws IOException { + FileLock lock = FileLocks.getExclusiveLockFromRandomAccessFile(0, 10); + assertNotNull(lock); + assertFalse(lock.isShared()); + } + + @Test + void givenAPath_whenGetExclusiveLock_thenLock() throws IOException { + FileLock lock = FileLocks.getExclusiveLockFromFileChannelOpen(0, 10); + assertNotNull(lock); + assertFalse(lock.isShared()); + } + + @Test + void givenAFileOutputStream_whenGetSharedLock_thenThrowNonReadableChannelException() { + assertThrows(NonReadableChannelException.class, FileLocks::getReadLockFromOutputStream); + } + + @Test + void givenAnInputStream_whenGetSharedLock_thenLock() throws IOException { + FileLock lock = FileLocks.getReadLockFromInputStream(0, 10); + assertNotNull(lock); + assertTrue(lock.isShared()); + } + + @Test + void givenARandomAccessFile_whenGetSharedLock_thenLock() throws IOException { + FileLock lock = FileLocks.getReadLockFromRandomAccessFile(0, 10); + assertNotNull(lock); + assertTrue(lock.isShared()); + } +} diff --git a/core-java-modules/core-java-nio/pom.xml b/core-java-modules/core-java-nio/pom.xml index bc7801c398..e7605763bb 100644 --- a/core-java-modules/core-java-nio/pom.xml +++ b/core-java-modules/core-java-nio/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 core-java-nio 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml index 9ab41d5a82..57e85109e6 100644 --- a/core-java-modules/core-java-optional/pom.xml +++ b/core-java-modules/core-java-optional/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-optional 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java index 47473c29ea..f9fbc5dc3a 100644 --- a/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java +++ b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java @@ -1,6 +1,8 @@ package com.baeldung.optional; +import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; public class Person { private String name; @@ -21,7 +23,7 @@ public class Person { } public Optional getAge() { - return Optional.ofNullable(age); + return Optional.of(age); } public void setAge(int age) { @@ -36,4 +38,37 @@ public class Person { return Optional.ofNullable(password); } + public static List search(List people, String name, Optional age) { + // Null checks for people and name + return people.stream() + .filter(p -> p.getName().equals(name)) + .filter(p -> p.getAge().get() >= age.orElse(0)) + .collect(Collectors.toList()); + } + + public static List search(List people, String name, Integer age) { + // Null checks for people and name + final Integer ageFilter = age != null ? age : 0; + + return people.stream() + .filter(p -> p.getName().equals(name)) + .filter(p -> p.getAge().get() >= ageFilter) + .collect(Collectors.toList()); + } + + public static List search(List people, String name) { + return doSearch(people, name, 0); + } + + public static List search(List people, String name, int age) { + return doSearch(people, name, age); + } + + private static List doSearch(List people, String name, int age) { + // Null checks for people and name + return people.stream() + .filter(p -> p.getName().equals(name)) + .filter(p -> p.getAge().get().intValue() >= age) + .collect(Collectors.toList()); + } } diff --git a/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java new file mode 100644 index 0000000000..480dc782e4 --- /dev/null +++ b/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java @@ -0,0 +1,21 @@ +package com.baeldung.orelseoptional; + +import java.util.Optional; + +public class ItemsProvider { + + Optional getEmptyItem() { + System.out.println("Returning an empty item"); + return Optional.empty(); + } + + Optional getNail() { + System.out.println("Returning a nail"); + return Optional.of("nail"); + } + + Optional getHammer() { + System.out.println("Returning a hammer"); + return Optional.of("hammer"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java b/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java index e5c4319bf7..de16e9b635 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java +++ b/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java @@ -86,6 +86,15 @@ public class OptionalUnitTest { Optional opt = Optional.ofNullable(null); String name = opt.get(); } + + @Test + public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() { + Optional opt = Optional.of("Baeldung"); + assertTrue(opt.isPresent()); + + opt = Optional.ofNullable(null); + assertFalse(opt.isPresent()); + } // Conditional Return With filter() @Test diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java b/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java index 91aebbeebd..e3bdedcd82 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java +++ b/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java @@ -1,10 +1,10 @@ package com.baeldung.orelseoptional; -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.util.Optional; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class OrElseOptionalUnitTest { @@ -25,6 +25,28 @@ public class OrElseOptionalUnitTest { assertEquals(fallbackOptionalString, OptionalUtils.or(optionalString, fallbackOptionalString)); } + @Test + public void givenTwoOptionalMethods_whenFirstEmpty_thenSecondEvaluated() { + ItemsProvider itemsProvider = new ItemsProvider(); + + Optional item = itemsProvider.getEmptyItem() + .map(Optional::of) + .orElseGet(itemsProvider::getNail); + + assertEquals(Optional.of("nail"), item); + } + + @Test + public void givenTwoOptionalMethods_whenFirstNonEmpty_thenSecondNotEvaluated() { + ItemsProvider itemsProvider = new ItemsProvider(); + + Optional item = itemsProvider.getNail() + .map(Optional::of) + .orElseGet(itemsProvider::getHammer); + + assertEquals(Optional.of("nail"), item); + } + // Uncomment code when code base is compatible with Java 9 // @Test // public void givenOptional_whenEmptyValue_thenCustomMessage() { diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml index b934701067..d8941cb494 100644 --- a/core-java-modules/core-java-os/pom.xml +++ b/core-java-modules/core-java-os/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-os 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-perf/README.md b/core-java-modules/core-java-perf/README.md index d1d646ac7f..d52fd2d733 100644 --- a/core-java-modules/core-java-perf/README.md +++ b/core-java-modules/core-java-perf/README.md @@ -9,3 +9,5 @@ This module contains articles about performance of Java applications - [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded) - [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions) - [Monitoring Java Applications with Flight Recorder](https://www.baeldung.com/java-flight-recorder-monitoring) +- [Branch Prediction in Java](https://www.baeldung.com/java-branch-prediction) +- [Capturing a Java Thread Dump](https://www.baeldung.com/java-thread-dump) diff --git a/core-java-modules/core-java-perf/pom.xml b/core-java-modules/core-java-perf/pom.xml index 18e05c9741..c1970346b5 100644 --- a/core-java-modules/core-java-perf/pom.xml +++ b/core-java-modules/core-java-perf/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-perf 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java index 21044f82c4..e2a60ac384 100644 --- a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java +++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java @@ -3,7 +3,12 @@ package com.baeldung.jmx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.management.*; +import javax.management.InstanceAlreadyExistsException; +import javax.management.MBeanRegistrationException; +import javax.management.MBeanServer; +import javax.management.MalformedObjectNameException; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; import java.lang.management.ManagementFactory; public class JMXTutorialMainlauncher { @@ -11,24 +16,21 @@ public class JMXTutorialMainlauncher { private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class); public static void main(String[] args) { - // TODO Auto-generated method stub LOG.debug("This is basic JMX tutorial"); - ObjectName objectName = null; + try { - objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); - } catch (MalformedObjectNameException e) { - e.printStackTrace(); - } - MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - Game gameObj = new Game(); - try { - server.registerMBean(gameObj, objectName); - } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { + ObjectName objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + server.registerMBean(new Game(), objectName); + } catch (MalformedObjectNameException | InstanceAlreadyExistsException | + MBeanRegistrationException | NotCompliantMBeanException e) { e.printStackTrace(); } + LOG.debug("Registration for Game mbean with the platform server is successfull"); LOG.debug("Please open jconsole to access Game mbean"); + while (true) { // to ensure application does not terminate } diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/threaddump/ThreadDump.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/threaddump/ThreadDump.java new file mode 100644 index 0000000000..17bc840b8d --- /dev/null +++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/threaddump/ThreadDump.java @@ -0,0 +1,28 @@ +package com.baeldung.threaddump; + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.lang.management.ThreadMXBean; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class ThreadDump { + + public static void main(String[] args) throws IOException { + threadDump(true, true); + } + + private static void threadDump(boolean lockedMonitors, boolean lockedSynchronizers) throws IOException { + Path threadDumpFile = Paths.get("ThreadDump.txt"); + + StringBuffer threadDump = new StringBuffer(System.lineSeparator()); + ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); + for(ThreadInfo threadInfo : threadMXBean.dumpAllThreads(lockedMonitors, lockedSynchronizers)) { + threadDump.append(threadInfo.toString()); + } + Files.write(threadDumpFile, threadDump.toString().getBytes()); + } + +} diff --git a/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/CombiningUnitTest.java b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/CombiningUnitTest.java new file mode 100644 index 0000000000..c98eef5ed1 --- /dev/null +++ b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/CombiningUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.branchprediction; + +import java.util.stream.LongStream; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CombiningUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(CombiningUnitTest.class); + + public static final int TOP = 10000000; + public static final double FRACTION = 0.1; + + @Test + public void combined() { + long[] first = LongStream.range(0, TOP) + .map(n -> Math.random() < FRACTION ? 0 : n) + .toArray(); + long[] second = LongStream.range(0, TOP) + .map(n -> Math.random() < FRACTION ? 0 : n) + .toArray(); + + long count = 0; + long start = System.currentTimeMillis(); + for (int i = 0; i < TOP; i++) { + if (first[i] * second[i] != 0) { + ++count; + } + } + long end = System.currentTimeMillis(); + + LOG.info("Counted {}/{} numbers using combined mode in {}ms", count, TOP, end - start); + + } + + @Test + public void separate() { + long[] first = LongStream.range(0, TOP) + .map(n -> Math.random() < FRACTION ? 0 : n) + .toArray(); + long[] second = LongStream.range(0, TOP) + .map(n -> Math.random() < FRACTION ? 0 : n) + .toArray(); + + long count = 0; + long start = System.currentTimeMillis(); + for (int i = 0; i < TOP; i++) { + if (first[i] != 0 && second[i] != 0) { + ++count; + } + } + long end = System.currentTimeMillis(); + + LOG.info("Counted {}/{} numbers using separate mode in {}ms", count, TOP, end - start); + } +} diff --git a/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/IfUnitTest.java b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/IfUnitTest.java new file mode 100644 index 0000000000..6f80624502 --- /dev/null +++ b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/IfUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.branchprediction; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.LongStream; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IfUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(IfUnitTest.class); + + public static final int TOP = 10000000; + + @Test + public void majorBranchSorted() { + test(TOP, 0.9, false); + } + + @Test + public void minorBranchSorted() { + test(TOP, 0.1, false); + } + + @Test + public void equalBranchSorted() { + test(TOP, 0.5, false); + } + + @Test + public void allBranchSorted() { + test(TOP, 1, false); + } + + @Test + public void noneBranchSorted() { + test(TOP, 0, false); + } + + @Test + public void majorBranchShuffled() { + test(TOP, 0.9, true); + } + + @Test + public void minorBranchShuffled() { + test(TOP, 0.1, true); + } + + @Test + public void equalBranchShuffled() { + test(TOP, 0.5, true); + } + + @Test + public void allBranchShuffled() { + test(TOP, 1, true); + } + + @Test + public void noneBranchShuffled() { + test(TOP, 0, true); + } + + private void test(long top, double cutoffPercentage, boolean shuffle) { + List numbers = LongStream.range(0, top) + .boxed() + .collect(Collectors.toList()); + if (shuffle) { + Collections.shuffle(numbers); + } + + long cutoff = (long)(top * cutoffPercentage); + long low = 0; + long high = 0; + + long start = System.currentTimeMillis(); + for (Long number : numbers) { + if (number < cutoff) { + ++low; + } else { + ++high; + } + } + long end = System.currentTimeMillis(); + + LOG.info("Counted {}/{} {} numbers in {}ms", low, high, shuffle ? "shuffled" : "sorted", end - start); + + } +} diff --git a/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/SortingUnitTest.java b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/SortingUnitTest.java new file mode 100644 index 0000000000..6af40bd57a --- /dev/null +++ b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/SortingUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.branchprediction; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.LongStream; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SortingUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(SortingUnitTest.class); + public static final int BIG = 10000000; + public static final int SMALL = 100000; + + @Test + public void sortedBig() { + test(BIG, false); + } + + @Test + public void shuffledBig() { + test(BIG, true); + } + + @Test + public void sortedSmall() { + test(SMALL, false); + } + + @Test + public void shuffledSmall() { + test(SMALL, true); + } + + private void test(long top, boolean shuffle) { + List numbers = LongStream.range(0, top) + .boxed() + .collect(Collectors.toList()); + + if (shuffle) { + Collections.shuffle(numbers); + } + + long cutoff = top / 2; + long count = 0; + + long start = System.currentTimeMillis(); + for (Long number : numbers) { + if (number < cutoff) { + ++count; + } + } + long end = System.currentTimeMillis(); + + LOG.info("Counted {}/{} {} numbers in {}ms", + count, top, shuffle ? "shuffled" : "sorted", end - start); + } +} diff --git a/core-java-modules/core-java-reflection/README.MD b/core-java-modules/core-java-reflection/README.MD index 840d488968..5aed62b378 100644 --- a/core-java-modules/core-java-reflection/README.MD +++ b/core-java-modules/core-java-reflection/README.MD @@ -6,4 +6,5 @@ - [Guide to Java Reflection](http://www.baeldung.com/java-reflection) - [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection) - [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params) -- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) \ No newline at end of file +- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) +- [What Causes java.lang.reflect.InvocationTargetException?](https://www.baeldung.com/java-lang-reflect-invocationtargetexception) diff --git a/core-java-modules/core-java-reflection/pom.xml b/core-java-modules/core-java-reflection/pom.xml index b3c3390df8..dca446b268 100644 --- a/core-java-modules/core-java-reflection/pom.xml +++ b/core-java-modules/core-java-reflection/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 core-java-reflection 0.1.0-SNAPSHOT @@ -37,8 +38,8 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} -parameters @@ -48,5 +49,7 @@ 3.8.0 3.10.0 + 1.8 + 1.8 \ No newline at end of file diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetExample.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetExample.java new file mode 100644 index 0000000000..a20ee527f8 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetExample.java @@ -0,0 +1,7 @@ +package com.baeldung.reflection.exception.invocationtarget; + +public class InvocationTargetExample { + public int divideByZeroExample() { + return 1 / 0; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetUnitTest.java new file mode 100644 index 0000000000..b4cabebcef --- /dev/null +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.reflection.exception.invocationtarget; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.jupiter.api.Test; + +public class InvocationTargetUnitTest { + + @Test + public void whenCallingMethodThrowsException_thenAssertCauseOfInvocationTargetException() throws Exception { + + InvocationTargetExample targetExample = new InvocationTargetExample(); + Method method = InvocationTargetExample.class.getMethod("divideByZeroExample"); + + Exception exception = assertThrows(InvocationTargetException.class, () -> method.invoke(targetExample)); + + assertEquals(ArithmeticException.class, exception.getCause().getClass()); + } +} diff --git a/core-java-modules/core-java-regex/README.md b/core-java-modules/core-java-regex/README.md new file mode 100644 index 0000000000..6fdea9f2ca --- /dev/null +++ b/core-java-modules/core-java-regex/README.md @@ -0,0 +1,12 @@ +========= + +## Core Java 8 Cookbooks and Examples + +### Relevant Articles: +- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance) +- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java) +- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char) +- [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile) +- [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches) +- [How to Use Regular Expressions to Replace Tokens in Strings](https://www.baeldung.com/java-regex-token-replacement) +- [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus) diff --git a/core-java-modules/core-java-regex/pom.xml b/core-java-modules/core-java-regex/pom.xml new file mode 100644 index 0000000000..df2382a732 --- /dev/null +++ b/core-java-modules/core-java-regex/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + core-java-regex + 0.1.0-SNAPSHOT + core-java-regex + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-core.version} + + + org.assertj + assertj-core + 3.15.0 + test + + + + + core-java-regex + + + src/main/resources + true + + + + + diff --git a/core-java-modules/core-java-regex/src/main/java/com/baeldung/patternreuse/PatternPerformanceComparison.java b/core-java-modules/core-java-regex/src/main/java/com/baeldung/patternreuse/PatternPerformanceComparison.java new file mode 100644 index 0000000000..01f8df9ec6 --- /dev/null +++ b/core-java-modules/core-java-regex/src/main/java/com/baeldung/patternreuse/PatternPerformanceComparison.java @@ -0,0 +1,92 @@ +package com.baeldung.patternreuse; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.openjdk.jmh.runner.RunnerException; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Fork(value = 1, warmups = 1) +@Warmup(iterations = 5) +@State(Scope.Benchmark) +public class PatternPerformanceComparison { + + private static final String PATTERN = "\\d*[02468]"; + private static List values; + + private static Matcher matcherFromPreCompiledPattern; + private static Pattern preCompiledPattern; + + public static void main(String[] args) throws IOException, RunnerException { + org.openjdk.jmh.Main.main(args); + } + + @Benchmark + public void matcherFromPreCompiledPatternResetMatches(Blackhole bh) { + //With pre-compiled pattern and reusing the matcher + // 1 Pattern object created + // 1 Matcher objects created + for (String value : values) { + bh.consume(matcherFromPreCompiledPattern.reset(value).matches()); + } + } + + @Benchmark + public void preCompiledPatternMatcherMatches(Blackhole bh) { + // With pre-compiled pattern + // 1 Pattern object created + // 5_000_000 Matcher objects created + for (String value : values) { + bh.consume(preCompiledPattern.matcher(value).matches()); + } + } + + @Benchmark + public void patternCompileMatcherMatches(Blackhole bh) { + // Above approach "Pattern.matches(PATTERN, value)" makes this internally + // 5_000_000 Pattern objects created + // 5_000_000 Matcher objects created + for (String value : values) { + bh.consume(Pattern.compile(PATTERN).matcher(value).matches()); + } + } + + @Benchmark + public void patternMatches(Blackhole bh) { + // Above approach "value.matches(PATTERN)" makes this internally + // 5_000_000 Pattern objects created + // 5_000_000 Matcher objects created + for (String value : values) { + bh.consume(Pattern.matches(PATTERN, value)); + } + } + + @Benchmark + public void stringMatchs(Blackhole bh) { + // 5_000_000 Pattern objects created + // 5_000_000 Matcher objects created + Instant start = Instant.now(); + for (String value : values) { + bh.consume(value.matches(PATTERN)); + } + } + + @Setup() + public void setUp() { + preCompiledPattern = Pattern.compile(PATTERN); + matcherFromPreCompiledPattern = preCompiledPattern.matcher(""); + + values = new ArrayList<>(); + for (int x = 1; x <= 5_000_000; x++) { + values.add(String.valueOf(x)); + } + } +} diff --git a/core-java-modules/core-java-regex/src/main/java/com/baeldung/replacetokens/ReplacingTokens.java b/core-java-modules/core-java-regex/src/main/java/com/baeldung/replacetokens/ReplacingTokens.java new file mode 100644 index 0000000000..a4774ad572 --- /dev/null +++ b/core-java-modules/core-java-regex/src/main/java/com/baeldung/replacetokens/ReplacingTokens.java @@ -0,0 +1,63 @@ +package com.baeldung.replacetokens; + +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ReplacingTokens { + public static final Pattern TITLE_CASE_PATTERN = Pattern.compile("(?<=^|[^A-Za-z])([A-Z][a-z]*)(?=[^A-Za-z]|$)"); + + /** + * Iterate over the title case tokens in the input and replace them with lowercase + * @param original the original string + * @return a string with words replaced with their lowercase equivalents + */ + public static String replaceTitleCaseWithLowerCase(String original) { + int lastIndex = 0; + StringBuilder output = new StringBuilder(); + Matcher matcher = TITLE_CASE_PATTERN.matcher(original); + while (matcher.find()) { + output.append(original, lastIndex, matcher.start()) + .append(convert(matcher.group(1))); + + lastIndex = matcher.end(); + } + if (lastIndex < original.length()) { + output.append(original, lastIndex, original.length()); + } + return output.toString(); + } + + /** + * Convert a token found into its desired lowercase + * @param token the token to convert + * @return the converted token + */ + private static String convert(String token) { + return token.toLowerCase(); + } + + /** + * Replace all the tokens in an input using the algorithm provided for each + * @param original original string + * @param tokenPattern the pattern to match with + * @param converter the conversion to apply + * @return the substituted string + */ + public static String replaceTokens(String original, Pattern tokenPattern, + Function converter) { + int lastIndex = 0; + StringBuilder output = new StringBuilder(); + Matcher matcher = tokenPattern.matcher(original); + while (matcher.find()) { + output.append(original, lastIndex, matcher.start()) + .append(converter.apply(matcher)); + + lastIndex = matcher.end(); + } + if (lastIndex < original.length()) { + output.append(original, lastIndex, original.length()); + } + return output.toString(); + } +} diff --git a/java-math-2/src/main/resources/logback.xml b/core-java-modules/core-java-regex/src/main/resources/logback.xml similarity index 100% rename from java-math-2/src/main/resources/logback.xml rename to core-java-modules/core-java-regex/src/main/resources/logback.xml diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/patternreuse/PatternUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/patternreuse/PatternUnitTest.java new file mode 100644 index 0000000000..c7331471ec --- /dev/null +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/patternreuse/PatternUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.patternreuse; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.*; + +public class PatternUnitTest { + + private static final Pattern FIRST_LAST_NAME_PRE_COMPILED_PATTERN = Pattern.compile("[a-zA-Z]{3,} [a-zA-Z]{3,}"); + private static final Pattern SPLIT_PRE_COMPILED_PATTERN = Pattern.compile("__"); + + @Test + public void givenPreCompiledPattern_whenCallMatcher_thenReturnAMatcherToMatches() { + Matcher matcherName1 = FIRST_LAST_NAME_PRE_COMPILED_PATTERN.matcher("Fabio Silva"); + Matcher matcherName2 = FIRST_LAST_NAME_PRE_COMPILED_PATTERN.matcher("Mr. Silva"); + + boolean matchesName1 = matcherName1.matches(); + boolean matchesName2 = matcherName2.matches(); + + assertTrue(matchesName1); + assertFalse(matchesName2); + } + + @Test + public void givenPreCompiledPattern_whenCallAsPredicate_thenReturnPredicateToFindPatternInTheList() { + List namesToValidate = Arrays.asList("Fabio Silva", "Mr. Silva"); + Predicate patternsAsPredicate = FIRST_LAST_NAME_PRE_COMPILED_PATTERN.asPredicate(); + + List validNames = namesToValidate.stream() + .filter(patternsAsPredicate) + .collect(Collectors.toList()); + + assertEquals(1, validNames.size()); + assertTrue(validNames.contains("Fabio Silva")); + } + + @Test + public void givenPreCompiledPattern_whenCallSplit_thenReturnArrayWithValuesSplitByThePattern() { + String[] textSplit = SPLIT_PRE_COMPILED_PATTERN.split("My_Name__is__Fabio_Silva"); + + assertEquals("My_Name", textSplit[0]); + assertEquals("is", textSplit[1]); + assertEquals("Fabio_Silva", textSplit[2]); + } + + @Test + public void givenPreCompiledPattern_whenCallSplitAsStream_thenReturnArraySplitByThePattern() { + Stream textSplitAsStream = SPLIT_PRE_COMPILED_PATTERN.splitAsStream("My_Name__is__Fabio_Silva"); + String[] textSplit = textSplitAsStream.toArray(String[]::new); + + assertEquals("My_Name", textSplit[0]); + assertEquals("is", textSplit[1]); + assertEquals("Fabio_Silva", textSplit[2]); + } +} diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/RegexUnitTest.java similarity index 99% rename from core-java-modules/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java rename to core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/RegexUnitTest.java index e4ea55aae3..77052b79ac 100644 --- a/core-java-modules/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/RegexUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.regex; +package com.baeldung.regex; import static org.junit.Assert.*; @@ -26,7 +26,6 @@ public class RegexUnitTest { while (matcher.find()) matches++; assertEquals(matches, 2); - } @Test @@ -452,7 +451,6 @@ public class RegexUnitTest { Matcher matcher = pattern.matcher("dogs are friendly"); assertTrue(matcher.lookingAt()); assertFalse(matcher.matches()); - } @Test @@ -460,7 +458,6 @@ public class RegexUnitTest { Pattern pattern = Pattern.compile("dog"); Matcher matcher = pattern.matcher("dog"); assertTrue(matcher.matches()); - } @Test @@ -469,7 +466,6 @@ public class RegexUnitTest { Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); String newStr = matcher.replaceFirst("cat"); assertEquals("cats are domestic animals, dogs are friendly", newStr); - } @Test @@ -478,7 +474,6 @@ public class RegexUnitTest { Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); String newStr = matcher.replaceAll("cat"); assertEquals("cats are domestic animals, cats are friendly", newStr); - } public synchronized static int runTest(String regex, String text) { diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java new file mode 100644 index 0000000000..304b9f2f1d --- /dev/null +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.regex.matcher; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.Test; + +public class MatcherUnitTest { + + @Test + public void whenFindFourDigitWorks_thenCorrect() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); + + assertTrue(m.find()); + assertEquals(8, m.start()); + assertEquals("2019", m.group()); + assertEquals(12, m.end()); + + assertTrue(m.find()); + assertEquals(25, m.start()); + assertEquals("2020", m.group()); + assertEquals(29, m.end()); + + assertFalse(m.find()); + } + + @Test + public void givenStartIndex_whenFindFourDigitWorks_thenCorrect() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); + + assertTrue(m.find(20)); + assertEquals(25, m.start()); + assertEquals("2020", m.group()); + assertEquals(29, m.end()); + } + + @Test + public void whenMatchFourDigitWorks_thenFail() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); + assertFalse(m.matches()); + } + + @Test + public void whenMatchFourDigitWorks_thenCorrect() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("2019"); + + assertTrue(m.matches()); + assertEquals(0, m.start()); + assertEquals("2019", m.group()); + assertEquals(4, m.end()); + + assertTrue(m.matches());// matches will always return the same return + } + +} diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java new file mode 100644 index 0000000000..11bf1618b6 --- /dev/null +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java @@ -0,0 +1,129 @@ +package com.baeldung.regex.phonenumbers; + +import static org.junit.Assert.*; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; + +public class PhoneNumbersRegexUnitTest { + + @Test + public void whenMatchesTenDigitsNumber_thenCorrect() { + Pattern pattern = Pattern.compile("^\\d{10}$"); + Matcher matcher = pattern.matcher("2055550125"); + assertTrue(matcher.matches()); + } + + @Test + public void whenMOreThanTenDigits_thenNotCorrect() { + Pattern pattern = Pattern.compile("^\\d{10}$"); + Matcher matcher = pattern.matcher("20555501251"); + assertFalse(matcher.matches()); + } + + @Test + public void whenMatchesTenDigitsNumberWhitespacesDotHyphen_thenCorrect() { + Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$"); + Matcher matcher = pattern.matcher("202 555 0125"); + assertTrue(matcher.matches()); + } + + @Test + public void whenIncludesBracket_thenNotCorrect() { + Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$"); + Matcher matcher = pattern.matcher("202]555 0125"); + assertFalse(matcher.matches()); + } + + @Test + public void whenNotStartsWithBatchesOfThreeDigits_thenNotCorrect() { + Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$"); + Matcher matcher = pattern.matcher("2021 555 0125"); + assertFalse(matcher.matches()); + } + + @Test + public void whenLastPartWithNoFourDigits_thenNotCorrect() { + Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$"); + Matcher matcher = pattern.matcher("202 555 012"); + assertFalse(matcher.matches()); + } + + @Test + public void whenMatchesTenDigitsNumberParenthesis_thenCorrect() { + Pattern pattern = Pattern.compile("^((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("(202) 555-0125"); + assertTrue(matcher.matches()); + } + + @Test + public void whenJustOpeningParenthesis_thenNotCorrect() { + Pattern pattern = Pattern.compile("^((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("(202 555-0125"); + assertFalse(matcher.matches()); + } + + @Test + public void whenJustClosingParenthesis_thenNotCorrect() { + Pattern pattern = Pattern.compile("^((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("202) 555-0125"); + assertFalse(matcher.matches()); + } + + @Test + public void whenMatchesTenDigitsNumberPrefix_thenCorrect() { + Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("+111 (202) 555-0125"); + assertTrue(matcher.matches()); + } + + @Test + public void whenIncorrectPrefix_thenNotCorrect() { + Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("-111 (202) 555-0125"); + assertFalse(matcher.matches()); + } + + @Test + public void whenTooLongPrefix_thenNotCorrect() { + Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("+1111 (202) 555-0125"); + assertFalse(matcher.matches()); + } + + @Test + public void whenMatchesPhoneNumber_thenCorrect() { + String patterns + = "^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$"; + + String[] validPhoneNumbers + = {"2055550125","202 555 0125", "(202) 555-0125", "+111 (202) 555-0125", "636 856 789", "+111 636 856 789", "636 85 67 89", "+111 636 85 67 89"}; + + Pattern pattern = Pattern.compile(patterns); + for(String phoneNumber : validPhoneNumbers) { + Matcher matcher = pattern.matcher(phoneNumber); + assertTrue(matcher.matches()); + } + } + + @Test + public void whenNotMatchesPhoneNumber_thenNotCorrect() { + String patterns + = "^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$"; + + String[] invalidPhoneNumbers + = {"20555501251","202]555 0125", "2021 555 012", "(202 555-0125", "202) 555-0125", "-111 (202) 555-0125", "+1111 (202) 555-0125", "636 85 789", "636 85 67 893"}; + + Pattern pattern = Pattern.compile(patterns); + for(String phoneNumber : invalidPhoneNumbers) { + Matcher matcher = pattern.matcher(phoneNumber); + assertFalse(matcher.matches()); + } + } +} diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java rename to core-java-modules/core-java-regex/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherManualTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherManualTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherManualTest.java rename to core-java-modules/core-java-regex/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherManualTest.java diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/replaceall/ReplaceAllWithWhitespaceRegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/replaceall/ReplaceAllWithWhitespaceRegexUnitTest.java new file mode 100644 index 0000000000..a95d1afd80 --- /dev/null +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/replaceall/ReplaceAllWithWhitespaceRegexUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.replaceall; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ReplaceAllWithWhitespaceRegexUnitTest { + private static final String INPUT_STR = "Text With Whitespaces! "; + + @Test + public void givenString_whenReplaceBySingleCharClass_thenGetExpect() { + String expected = "Text___With_____Whitespaces!___"; + String result = INPUT_STR.replaceAll("\\s", "_"); + assertEquals(expected, result); + } + + @Test + public void givenString_whenReplaceBySingleCharClassWithPlus_thenGetExpect() { + String expected = "Text_With_Whitespaces!_"; + String result = INPUT_STR.replaceAll("\\s+", "_"); + assertEquals(expected, result); + } + + @Test + public void givenString_whenRemoveByWhitespace_thenGetSameResult() { + String expected = "TextWithWhitespaces!"; + String result1 = INPUT_STR.replaceAll("\\s", ""); + String result2 = INPUT_STR.replaceAll("\\s+", ""); + assertEquals(expected, result1); + assertEquals(result1, result2); + } +} diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/replacetokens/ReplacingTokensUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/replacetokens/ReplacingTokensUnitTest.java new file mode 100644 index 0000000000..b42a17f88e --- /dev/null +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/replacetokens/ReplacingTokensUnitTest.java @@ -0,0 +1,79 @@ +package com.baeldung.replacetokens; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.baeldung.replacetokens.ReplacingTokens.TITLE_CASE_PATTERN; +import static com.baeldung.replacetokens.ReplacingTokens.replaceTokens; +import static org.assertj.core.api.Assertions.assertThat; + +public class ReplacingTokensUnitTest { + private static final String EXAMPLE_INPUT = "First 3 Capital Words! then 10 TLAs, I Found"; + private static final String EXAMPLE_INPUT_PROCESSED = "first 3 capital words! then 10 TLAs, i found"; + + @Test + public void whenFindMatches_thenTitleWordsFound() { + Matcher matcher = TITLE_CASE_PATTERN.matcher(EXAMPLE_INPUT); + List matches = new ArrayList<>(); + while (matcher.find()) { + matches.add(matcher.group(1)); + } + + assertThat(matches) + .containsExactly("First", "Capital", "Words", "I", "Found"); + } + + @Test + public void exploreMatches() { + Matcher matcher = TITLE_CASE_PATTERN.matcher(EXAMPLE_INPUT); + while (matcher.find()) { + System.out.println("Match: " + matcher.group(0)); + System.out.println("Start: " + matcher.start()); + System.out.println("End: " + matcher.end()); + } + } + + @Test + public void whenReplaceTokensWithLowerCase() { + assertThat(ReplacingTokens.replaceTitleCaseWithLowerCase(EXAMPLE_INPUT)) + .isEqualTo(EXAMPLE_INPUT_PROCESSED); + } + + @Test + public void whenReplaceTokensWithLowerCaseUsingGeneralPurpose() { + assertThat(replaceTokens("First 3 Capital Words! then 10 TLAs, I Found", + TITLE_CASE_PATTERN, + match -> match.group(1).toLowerCase())) + .isEqualTo("first 3 capital words! then 10 TLAs, i found"); + } + + @Test + public void escapeRegexCharacters() { + Pattern regexCharacters = Pattern.compile("[<(\\[{\\\\^\\-=$!|\\]})?*+.>]"); + + assertThat(replaceTokens("A regex character like [", + regexCharacters, + match -> "\\" + match.group())) + .isEqualTo("A regex character like \\["); + } + + @Test + public void replacePlaceholders() { + Pattern placeholderPattern = Pattern.compile("\\$\\{(?[A-Za-z0-9-_]+)}"); + + Map placeholderValues = new HashMap<>(); + placeholderValues.put("name", "Bill"); + placeholderValues.put("company", "Baeldung"); + + assertThat(replaceTokens("Hi ${name} at ${company}", + placeholderPattern, + match -> placeholderValues.get(match.group("placeholder")))) + .isEqualTo("Hi Bill at Baeldung"); + } +} diff --git a/core-java-modules/core-java-security-2/README.md b/core-java-modules/core-java-security-2/README.md new file mode 100644 index 0000000000..24a821bd4d --- /dev/null +++ b/core-java-modules/core-java-security-2/README.md @@ -0,0 +1,12 @@ +## Core Java Security + +This module contains articles about core Java Security + +### Relevant Articles: + +- [Guide To The Java Authentication And Authorization Service (JAAS)](https://www.baeldung.com/java-authentication-authorization-service) +- [MD5 Hashing in Java](http://www.baeldung.com/java-md5) +- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) +- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) +- [Checksums in Java](https://www.baeldung.com/java-checksums) +- More articles: [[<-- prev]](/core-java-modules/core-java-security) diff --git a/core-java-modules/core-java-security-2/pom.xml b/core-java-modules/core-java-security-2/pom.xml new file mode 100644 index 0000000000..5db3b67c04 --- /dev/null +++ b/core-java-modules/core-java-security-2/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + core-java-security-2 + 0.1.0-SNAPSHOT + core-java-security-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + + commons-codec + commons-codec + ${commons-codec.version} + + + + org.bouncycastle + bcprov-jdk15on + ${bouncycastle.version} + + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + javax.xml.bind + jaxb-api + 2.3.1 + + + + + + + + 1.60 + 1.11 + + + 3.10.0 + + + diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/checksums/ChecksumUtils.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/checksums/ChecksumUtils.java new file mode 100644 index 0000000000..d214a0f757 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/checksums/ChecksumUtils.java @@ -0,0 +1,23 @@ +package com.baeldung.checksums; + +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.CRC32; +import java.util.zip.CheckedInputStream; +import java.util.zip.Checksum; + +public class ChecksumUtils { + + public static long getChecksumCRC32(byte[] bytes) { + Checksum crc32 = new CRC32(); + crc32.update(bytes, 0, bytes.length); + return crc32.getValue(); + } + + public static long getChecksumCRC32(InputStream stream, int bufferSize) throws IOException { + CheckedInputStream checkedInputStream = new CheckedInputStream(stream, new CRC32()); + byte[] buffer = new byte[bufferSize]; + while (checkedInputStream.read(buffer, 0, buffer.length) >= 0) {} + return checkedInputStream.getChecksum().getValue(); + } +} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/DigestAlgorithms.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/DigestAlgorithms.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/DigestAlgorithms.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/DigestAlgorithms.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/Keccak256Hashing.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/Keccak256Hashing.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/Keccak256Hashing.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/Keccak256Hashing.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA256Hashing.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA256Hashing.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA3Hashing.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA3Hashing.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA3Hashing.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA3Hashing.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHACommonUtils.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHACommonUtils.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHACommonUtils.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHACommonUtils.java diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/ConsoleCallbackHandler.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/ConsoleCallbackHandler.java new file mode 100644 index 0000000000..714879e862 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/ConsoleCallbackHandler.java @@ -0,0 +1,24 @@ +package com.baeldung.jaas; + +import javax.security.auth.callback.*; +import java.io.Console; +import java.io.IOException; + +public class ConsoleCallbackHandler implements CallbackHandler { + + @Override + public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { + Console console = System.console(); + for (Callback callback : callbacks) { + if (callback instanceof NameCallback) { + NameCallback nameCallback = (NameCallback) callback; + nameCallback.setName(console.readLine(nameCallback.getPrompt())); + } else if (callback instanceof PasswordCallback) { + PasswordCallback passwordCallback = (PasswordCallback) callback; + passwordCallback.setPassword(console.readPassword(passwordCallback.getPrompt())); + } else { + throw new UnsupportedCallbackException(callback); + } + } + } +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/JaasAuthentication.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/JaasAuthentication.java new file mode 100644 index 0000000000..263daa4008 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/JaasAuthentication.java @@ -0,0 +1,13 @@ +package com.baeldung.jaas; + +import javax.security.auth.Subject; +import javax.security.auth.login.LoginException; + +public class JaasAuthentication { + + public static void main(String[] args) throws LoginException { + LoginService loginService = new LoginService(); + Subject subject = loginService.login(); + System.out.println(subject.getPrincipals().iterator().next() + " sucessfully logeed in"); + } +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/JaasAuthorization.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/JaasAuthorization.java new file mode 100644 index 0000000000..b01179c4d6 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/JaasAuthorization.java @@ -0,0 +1,17 @@ +package com.baeldung.jaas; + +import javax.security.auth.Subject; +import javax.security.auth.login.LoginException; +import java.security.PrivilegedAction; + +public class JaasAuthorization { + + public static void main(String[] args) throws LoginException { + + LoginService loginService = new LoginService(); + Subject subject = loginService.login(); + + PrivilegedAction privilegedAction = new ResourceAction(); + Subject.doAsPrivileged(subject, privilegedAction, null); + } +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/LoginService.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/LoginService.java new file mode 100644 index 0000000000..72c18d211c --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/LoginService.java @@ -0,0 +1,14 @@ +package com.baeldung.jaas; + +import javax.security.auth.Subject; +import javax.security.auth.login.LoginContext; +import javax.security.auth.login.LoginException; + +public class LoginService { + + public Subject login() throws LoginException { + LoginContext loginContext = new LoginContext("jaasApplication", new ConsoleCallbackHandler()); + loginContext.login(); + return loginContext.getSubject(); + } +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/ResourceAction.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/ResourceAction.java new file mode 100644 index 0000000000..274f280c2b --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/ResourceAction.java @@ -0,0 +1,15 @@ +package com.baeldung.jaas; + +import java.security.PrivilegedAction; + +public class ResourceAction implements PrivilegedAction { + @Override + public Object run() { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new ResourcePermission("test_resource")); + } + System.out.println("I have access to test_resource !"); + return null; + } +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/ResourcePermission.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/ResourcePermission.java new file mode 100644 index 0000000000..1ea162f002 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/ResourcePermission.java @@ -0,0 +1,9 @@ +package com.baeldung.jaas; + +import java.security.BasicPermission; + +public class ResourcePermission extends BasicPermission { + public ResourcePermission(String name) { + super(name); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/loginmodule/InMemoryLoginModule.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/loginmodule/InMemoryLoginModule.java new file mode 100644 index 0000000000..6ab606530b --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/jaas/loginmodule/InMemoryLoginModule.java @@ -0,0 +1,74 @@ +package com.baeldung.jaas.loginmodule; + +import com.sun.security.auth.UserPrincipal; + +import javax.security.auth.Subject; +import javax.security.auth.callback.*; +import javax.security.auth.login.LoginException; +import javax.security.auth.spi.LoginModule; +import java.io.IOException; +import java.security.Principal; +import java.util.Map; + +public class InMemoryLoginModule implements LoginModule { + + private static final String USERNAME = "testuser"; + private static final String PASSWORD = "testpassword"; + + private Subject subject; + private CallbackHandler callbackHandler; + private Map sharedState; + private Map options; + + private String username; + private boolean loginSucceeded = false; + private Principal userPrincipal; + + @Override + public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, + Map options) { + this.subject = subject; + this.callbackHandler = callbackHandler; + this.sharedState = sharedState; + this.options = options; + } + + @Override + public boolean login() throws LoginException { + NameCallback nameCallback = new NameCallback("username: "); + PasswordCallback passwordCallback = new PasswordCallback("password: ", false); + try { + callbackHandler.handle(new Callback[]{nameCallback, passwordCallback}); + username = nameCallback.getName(); + String password = new String(passwordCallback.getPassword()); + if (USERNAME.equals(username) && PASSWORD.equals(password)) { + loginSucceeded = true; + } + } catch (IOException | UnsupportedCallbackException e) { + throw new LoginException("Can't login"); + } + return loginSucceeded; + } + + @Override + public boolean commit() throws LoginException { + if (!loginSucceeded) { + return false; + } + userPrincipal = new UserPrincipal(username); + subject.getPrincipals().add(userPrincipal); + return true; + } + + @Override + public boolean abort() throws LoginException { + logout(); + return true; + } + + @Override + public boolean logout() throws LoginException { + subject.getPrincipals().remove(userPrincipal); + return false; + } +} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java diff --git a/core-java-modules/core-java-security-2/src/main/resources/jaas/jaas.login.config b/core-java-modules/core-java-security-2/src/main/resources/jaas/jaas.login.config new file mode 100644 index 0000000000..1163f60c84 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/resources/jaas/jaas.login.config @@ -0,0 +1,3 @@ +jaasApplication { + com.baeldung.jaas.loginmodule.InMemoryLoginModule required debug=true; +}; diff --git a/core-java-modules/core-java-security-2/src/main/resources/jaas/jaas.policy b/core-java-modules/core-java-security-2/src/main/resources/jaas/jaas.policy new file mode 100644 index 0000000000..77f44dbd87 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/resources/jaas/jaas.policy @@ -0,0 +1,14 @@ +grant codebase "file:./target/core-java-security-2-0.1.0-SNAPSHOT.jar" { + permission javax.security.auth.AuthPermission "createLoginContext.jaasApplication"; + permission javax.security.auth.AuthPermission "doAsPrivileged"; + permission java.lang.RuntimePermission "readFileDescriptor"; + permission java.lang.RuntimePermission "writeFileDescriptor"; +}; + +grant codebase "file:./target/core-java-security-2-0.1.0-SNAPSHOT.jar" { + permission javax.security.auth.AuthPermission "modifyPrincipals"; +}; + +grant principal com.sun.security.auth.UserPrincipal "testuser" { + permission com.baeldung.jaas.ResourcePermission "test_resource"; +}; diff --git a/core-java-modules/core-java-security-2/src/test/java/com/baeldung/checksums/ChecksumUtilsUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/checksums/ChecksumUtilsUnitTest.java new file mode 100644 index 0000000000..f5366917f6 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/checksums/ChecksumUtilsUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.checksums; + + +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.jupiter.api.Assertions.*; + +class ChecksumUtilsUnitTest { + + byte[] arr; + + @Before + void setUp() { + arr = new byte[]{0,10,21,20,35,40,120,56,72,22}; + } + + @Test + void givenByteArray_whenChecksumCreated_checkCorrect() { + + long checksum = ChecksumUtils.getChecksumCRC32(arr); + + assertEquals(3915397664L, checksum); + } + + @Test + void givenTwoDifferentStrings_whenChecksumCreated_checkCollision() { + + String plumless = "plumless"; + String buckeroo = "buckeroo"; + + long plumlessChecksum = ChecksumUtils.getChecksumCRC32(plumless.getBytes()); + long buckerooChecksum = ChecksumUtils.getChecksumCRC32(buckeroo.getBytes()); + + assertEquals(plumlessChecksum, buckerooChecksum); + } + + @Test + void givenInputString_whenChecksumCreated_checkCorrect() throws IOException { + + InputStream inputStream = new ByteArrayInputStream(arr); + long checksum = ChecksumUtils.getChecksumCRC32(inputStream, 10); + + assertEquals(3915397664L, checksum); + + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java diff --git a/core-java-modules/core-java-security/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java similarity index 98% rename from core-java-modules/core-java-security/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java index 55e71470c8..67d6918c09 100644 --- a/core-java-modules/core-java-security/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.md5; +package com.baeldung.java.md5; import static org.assertj.core.api.Assertions.assertThat; diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java diff --git a/core-java-modules/core-java-security/src/test/resources/test_md5.txt b/core-java-modules/core-java-security-2/src/test/resources/test_md5.txt similarity index 100% rename from core-java-modules/core-java-security/src/test/resources/test_md5.txt rename to core-java-modules/core-java-security-2/src/test/resources/test_md5.txt diff --git a/core-java-modules/core-java-security-manager/README.md b/core-java-modules/core-java-security-manager/README.md deleted file mode 100644 index a4abe7f80a..0000000000 --- a/core-java-modules/core-java-security-manager/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager) diff --git a/core-java-modules/core-java-security-manager/pom.xml b/core-java-modules/core-java-security-manager/pom.xml deleted file mode 100644 index 52f1554ace..0000000000 --- a/core-java-modules/core-java-security-manager/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - 4.0.0 - core-java-security-manager - 0.1.0-SNAPSHOT - core-java-security-manager - jar - - - com.baeldung.core-java-modules - core-java-modules - 1.0.0-SNAPSHOT - - - diff --git a/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/Service.java b/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/Service.java deleted file mode 100644 index 1b9f14e3b8..0000000000 --- a/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/Service.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.security.manager; - -public class Service { - - public static final String OPERATION = "my-operation"; - - public void operation() { - SecurityManager securityManager = System.getSecurityManager(); - if (securityManager != null) { - securityManager.checkPermission(new CustomPermission(OPERATION)); - } - System.out.println("Operation is executed"); - } - - public static void main(String[] args) { - new Service().operation(); - } -} diff --git a/core-java-modules/core-java-security-manager/src/test/java/com/baeldung/security/manager/SecurityManagerUnitTest.java b/core-java-modules/core-java-security-manager/src/test/java/com/baeldung/security/manager/SecurityManagerUnitTest.java deleted file mode 100644 index a845f233b5..0000000000 --- a/core-java-modules/core-java-security-manager/src/test/java/com/baeldung/security/manager/SecurityManagerUnitTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.security.manager; - -import org.junit.Test; - -import java.net.URL; -import java.security.AccessControlException; -import java.util.concurrent.Callable; - -public class SecurityManagerUnitTest { - - @Test(expected = AccessControlException.class) - public void whenSecurityManagerIsActive_thenNetworkIsNotAccessibleByDefault() throws Exception { - doTest(() -> { - new URL("http://www.google.com").openConnection().connect(); - return null; - }); - } - - @Test(expected = AccessControlException.class) - public void whenUnauthorizedClassTriesToAccessProtectedOperation_thenAnExceptionIsThrown() throws Exception { - doTest(() -> { - new Service().operation(); - return null; - }); - } - - private void doTest(Callable action) throws Exception { - System.setSecurityManager(new SecurityManager()); - try { - action.call(); - } finally { - System.setSecurityManager(null); - } - } -} diff --git a/core-java-modules/core-java-security/README.md b/core-java-modules/core-java-security/README.md index 7386d04e8e..83b12793b5 100644 --- a/core-java-modules/core-java-security/README.md +++ b/core-java-modules/core-java-security/README.md @@ -3,16 +3,16 @@ This module contains articles about core Java Security ### Relevant Articles: -- [MD5 Hashing in Java](http://www.baeldung.com/java-md5) + - [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class) - [Introduction to SSL in Java](http://www.baeldung.com/java-ssl) - [Java KeyStore API](http://www.baeldung.com/java-keystore) - [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream) -- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) - [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures) -- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) - [Enabling TLS v1.2 in Java 7](https://www.baeldung.com/java-7-tls-v12) - [The Java SecureRandom Class](https://www.baeldung.com/java-secure-random) - [An Introduction to Java SASL](https://www.baeldung.com/java-sasl) - [A Guide to Java GSS API](https://www.baeldung.com/java-gss) +- [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager) +- More articles: [[next -->]](/core-java-modules/core-java-security-2) diff --git a/core-java-modules/core-java-security/pom.xml b/core-java-modules/core-java-security/pom.xml index cefbd3a8a7..96024a73a1 100644 --- a/core-java-modules/core-java-security/pom.xml +++ b/core-java-modules/core-java-security/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-security 0.1.0-SNAPSHOT @@ -22,24 +24,9 @@ ${assertj-core.version} test - - - commons-codec - commons-codec - ${commons-codec.version} - - - org.bouncycastle - bcprov-jdk15on - ${bouncycastle.version} - - - 1.60 - 1.11 - 3.10.0 diff --git a/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/CustomPermission.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/CustomPermission.java similarity index 87% rename from core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/CustomPermission.java rename to core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/CustomPermission.java index 5f9c43336f..fa46353893 100644 --- a/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/CustomPermission.java +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/CustomPermission.java @@ -1,4 +1,4 @@ -package com.baeldung.security.manager; +package com.baeldung.securitymanager; import java.security.BasicPermission; diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/Service.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/Service.java new file mode 100644 index 0000000000..21e0c0a657 --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/Service.java @@ -0,0 +1,18 @@ +package com.baeldung.securitymanager; + +public class Service { + + public static final String OPERATION = "my-operation"; + + public void operation() { + SecurityManager securityManager = System.getSecurityManager(); + if (securityManager != null) { + securityManager.checkPermission(new CustomPermission(OPERATION)); + } + System.out.println("Operation is executed"); + } + + public static void main(String[] args) { + new Service().operation(); + } +} diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/securitymanager/SecurityManagerUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/securitymanager/SecurityManagerUnitTest.java new file mode 100644 index 0000000000..a7dcc949d2 --- /dev/null +++ b/core-java-modules/core-java-security/src/test/java/com/baeldung/securitymanager/SecurityManagerUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.securitymanager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.net.URL; +import java.security.AccessControlException; + +public class SecurityManagerUnitTest { + + private static final String TESTING_SECURITY_POLICY = "file:src/test/resources/testing.policy"; + + @Before + public void setUp() { + System.setProperty("java.security.policy", TESTING_SECURITY_POLICY); + System.setSecurityManager(new SecurityManager()); + } + + @After + public void tearDown() { + System.setSecurityManager(null); + } + + @Test(expected = AccessControlException.class) + public void whenSecurityManagerIsActive_thenNetworkIsNotAccessibleByDefault() throws IOException { + new URL("http://www.google.com").openConnection().connect(); + } + + @Test(expected = AccessControlException.class) + public void whenUnauthorizedClassTriesToAccessProtectedOperation_thenAnExceptionIsThrown() { + new Service().operation(); + } +} diff --git a/core-java-modules/core-java-security/src/test/resources/testing.policy b/core-java-modules/core-java-security/src/test/resources/testing.policy new file mode 100644 index 0000000000..16ab8a1869 --- /dev/null +++ b/core-java-modules/core-java-security/src/test/resources/testing.policy @@ -0,0 +1,5 @@ +grant { + // This is for testing purposes only. + // It allows us to properly reset the security manager after the unit test completes. + permission java.lang.RuntimePermission "setSecurityManager"; +}; \ No newline at end of file diff --git a/core-java-modules/core-java-streams-2/pom.xml b/core-java-modules/core-java-streams-2/pom.xml index 58f13d658c..1f47df63a0 100644 --- a/core-java-modules/core-java-streams-2/pom.xml +++ b/core-java-modules/core-java-streams-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-streams-2 1.0 diff --git a/core-java-modules/core-java-streams-3/README.md b/core-java-modules/core-java-streams-3/README.md index a739245399..65713aa04f 100644 --- a/core-java-modules/core-java-streams-3/README.md +++ b/core-java-modules/core-java-streams-3/README.md @@ -9,4 +9,6 @@ This module contains articles about the Stream API in Java. - [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors) - [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) - [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams) +- [Add BigDecimals using the Stream API](https://www.baeldung.com/java-stream-add-bigdecimals) +- [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close) - More articles: [[<-- prev>]](/../core-java-streams-2) diff --git a/core-java-modules/core-java-streams-3/pom.xml b/core-java-modules/core-java-streams-3/pom.xml index 02503d3cab..ae27e28918 100644 --- a/core-java-modules/core-java-streams-3/pom.xml +++ b/core-java-modules/core-java-streams-3/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-streams-3 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/closure/StreamClosureSnippets.java b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/closure/StreamClosureSnippets.java new file mode 100644 index 0000000000..10e5716e31 --- /dev/null +++ b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/closure/StreamClosureSnippets.java @@ -0,0 +1,30 @@ +package com.baeldung.streams.closure; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.stream.Stream; + +/** + * Contains a couple of simple stream API usages. + */ +public class StreamClosureSnippets { + + public static void main(String[] args) throws IOException { + // Collection based streams shouldn't be closed + Arrays.asList("Red", "Blue", "Green") + .stream() + .filter(c -> c.length() > 4) + .map(String::toUpperCase) + .forEach(System.out::print); + + String[] colors = {"Red", "Blue", "Green"}; + Arrays.stream(colors).map(String::toUpperCase).forEach(System.out::println); + + // IO-Based Streams Should be Closed via Try with Resources + try (Stream lines = Files.lines(Paths.get("/path/tp/file"))) { + // lines will be closed after exiting the try block + } + } +} diff --git a/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/bigdecimals/AddNumbersUnitTest.java b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/bigdecimals/AddNumbersUnitTest.java new file mode 100644 index 0000000000..9399908b30 --- /dev/null +++ b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/bigdecimals/AddNumbersUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.streams.bigdecimals; + +import static org.junit.Assert.assertEquals; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.junit.Test; + +public class AddNumbersUnitTest { + + @Test + public void givenIntStream_whenSum_thenResultIsCorrect() { + IntStream intNumbers = IntStream.range(0, 3); + assertEquals(3, intNumbers.sum()); + } + + @Test + public void givenCollectionOfDouble_whenUsingMapToDoubleToSum_thenResultIsCorrect() { + List doubleNumbers = Arrays.asList(23.48, 52.26, 13.5); + double result = doubleNumbers.stream() + .mapToDouble(Double::doubleValue) + .sum(); + assertEquals(89.24, result, .1); + } + + public void givenStreamOfIntegers_whenUsingReduceToSum_thenResultIsCorrect() { + Stream intNumbers = Stream.of(0, 1, 2); + int result = intNumbers.reduce(0, Integer::sum); + assertEquals(106, result); + } + + public void givenStreamOfBigDecimals_whenUsingReduceToSum_thenResultIsCorrect() { + Stream bigDecimalNumber = Stream.of(BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN); + BigDecimal result = bigDecimalNumber.reduce(BigDecimal.ZERO, BigDecimal::add); + assertEquals(11, result); + } + +} diff --git a/core-java-modules/core-java-streams/pom.xml b/core-java-modules/core-java-streams/pom.xml index 56fdd523fe..272a2be540 100644 --- a/core-java-modules/core-java-streams/pom.xml +++ b/core-java-modules/core-java-streams/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-streams 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-string-algorithms-2/pom.xml b/core-java-modules/core-java-string-algorithms-2/pom.xml index a67f1df6d2..f05674034a 100644 --- a/core-java-modules/core-java-string-algorithms-2/pom.xml +++ b/core-java-modules/core-java-string-algorithms-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-string-algorithms-2 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-string-algorithms-3/README.md b/core-java-modules/core-java-string-algorithms-3/README.md index 3aa31cea53..c7b17a6720 100644 --- a/core-java-modules/core-java-string-algorithms-3/README.md +++ b/core-java-modules/core-java-string-algorithms-3/README.md @@ -3,3 +3,5 @@ This module contains articles about string-related algorithms. ### Relevant Articles: + +- [Check if Two Strings are Anagrams in Java](https://www.baeldung.com/java-strings-anagrams) diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index a5dd31c762..583fa99afd 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -1,50 +1,51 @@ - - 4.0.0 - core-java-string-algorithms-3 - 0.1.0-SNAPSHOT - jar - core-java-string-algorithms-3 + + 4.0.0 + core-java-string-algorithms-3 + 0.1.0-SNAPSHOT + jar + core-java-string-algorithms-3 - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + - - - - org.assertj - assertj-core - ${assertj.version} - test - - - com.google.guava - guava - 28.1-jre - + + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.google.guava + guava + ${guava.version} + - - org.junit.jupiter - junit-jupiter-api - ${junit-jupiter-api.version} - test - - + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter-api.version} + test + + + + + core-java-string-algorithms-3 + + + src/main/resources + true + + - - core-java-string-algorithms-3 - - - src/main/resources - true - - - org.apache.maven.plugins @@ -57,13 +58,13 @@ - + - - 3.8.1 - 3.6.1 - 27.0.1-jre - 5.3.1 - + + 3.8.1 + 3.6.1 + 28.1-jre + 5.3.1 + diff --git a/core-java-modules/core-java-string-algorithms/pom.xml b/core-java-modules/core-java-string-algorithms/pom.xml index 6cae320f1d..cb1a25c11b 100644 --- a/core-java-modules/core-java-string-algorithms/pom.xml +++ b/core-java-modules/core-java-string-algorithms/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-string-algorithms 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-string-apis/pom.xml b/core-java-modules/core-java-string-apis/pom.xml index 6d0fd4c6fd..c1cd439386 100644 --- a/core-java-modules/core-java-string-apis/pom.xml +++ b/core-java-modules/core-java-string-apis/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-string-apis 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-string-conversions-2/pom.xml b/core-java-modules/core-java-string-conversions-2/pom.xml index 58b00b757a..53680e4fce 100644 --- a/core-java-modules/core-java-string-conversions-2/pom.xml +++ b/core-java-modules/core-java-string-conversions-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-string-conversions-2 0.1.0-SNAPSHOT @@ -28,8 +30,8 @@ org.hamcrest - hamcrest-library - ${org.hamcrest.version} + hamcrest + ${hamcrest.version} test diff --git a/core-java-modules/core-java-string-conversions/pom.xml b/core-java-modules/core-java-string-conversions/pom.xml index e3d6036e53..302e73e691 100644 --- a/core-java-modules/core-java-string-conversions/pom.xml +++ b/core-java-modules/core-java-string-conversions/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-string-conversions 0.1.0-SNAPSHOT @@ -44,8 +46,8 @@ org.hamcrest - hamcrest-library - ${org.hamcrest.version} + hamcrest + ${hamcrest.version} test diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md index 50f40ac2af..2f54aa9467 100644 --- a/core-java-modules/core-java-string-operations-2/README.md +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -8,4 +8,8 @@ This module contains articles about string operations. - [String Initialization in Java](https://www.baeldung.com/java-string-initialization) - [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case) - [Java String equalsIgnoreCase()](https://www.baeldung.com/java-string-equalsignorecase) +- [Case-Insensitive String Matching in Java](https://www.baeldung.com/java-case-insensitive-string-matching) +- [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives) +- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64) +- [Encode a String to UTF-8 in Java](https://www.baeldung.com/java-string-encode-utf-8) - More articles: [[<-- prev]](../core-java-string-operations) diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml index bd1a34f89f..a00ae80f13 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-string-operations-2 0.1.0-SNAPSHOT @@ -47,10 +49,27 @@ org.hamcrest - hamcrest-library - ${org.hamcrest.version} + hamcrest + ${hamcrest.version} test + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + org.assertj assertj-core @@ -61,6 +80,28 @@ core-java-string-operations-2 + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.0 + + + package + + shade + + + + + org.openjdk.jmh.Main + + + + + + + src/main/resources @@ -73,10 +114,11 @@ 3.6.1 2.0.0.Final 3.8.1 - 27.0.1-jre + 28.2-jre 6.0.2.Final 3.0.0 2.2.6 + 1.14 diff --git a/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/contains/CaseInsensitiveWorkarounds.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/contains/CaseInsensitiveWorkarounds.java new file mode 100644 index 0000000000..e4089a4f53 --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/contains/CaseInsensitiveWorkarounds.java @@ -0,0 +1,78 @@ +package com.baeldung.contains; + +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +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; + +/** + * Based on https://github.com/tedyoung/indexof-contains-benchmark + */ +@Fork(5) +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +public class CaseInsensitiveWorkarounds { + + private String src; + private String dest; + private Pattern pattern; + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + } + + @Setup + public void setup() { + src = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"; + dest = "eiusmod"; + pattern = Pattern.compile(Pattern.quote(dest), Pattern.CASE_INSENSITIVE); + } + + // toLowerCase() and contains() + @Benchmark + public boolean lowerCaseContains() { + return src.toLowerCase() + .contains(dest.toLowerCase()); + } + + // matches() with Regular Expressions + @Benchmark + public boolean matchesRegularExpression() { + return src.matches("(?i).*" + dest + ".*"); + } + + public boolean processRegionMatches(String localSrc, String localDest) { + for (int i = localSrc.length() - localDest.length(); i >= 0; i--) + if (localSrc.regionMatches(true, i, localDest, 0, localDest.length())) + return true; + return false; + } + + // String regionMatches() + @Benchmark + public boolean regionMatches() { + return processRegionMatches(src, dest); + } + + // Pattern CASE_INSENSITIVE with regexp + @Benchmark + public boolean patternCaseInsensitiveRegexp() { + return pattern.matcher(src) + .find(); + } + + // Apache Commons StringUtils containsIgnoreCase + @Benchmark + public boolean apacheCommonsStringUtils() { + return org.apache.commons.lang3.StringUtils.containsIgnoreCase(src, dest); + } + +} diff --git a/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/trim/LTrimRTrim.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/trim/LTrimRTrim.java new file mode 100644 index 0000000000..b300c783e1 --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/trim/LTrimRTrim.java @@ -0,0 +1,124 @@ +package com.baeldung.trim; + +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +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 com.google.common.base.CharMatcher; + +/** + * Based on https://github.com/tedyoung/indexof-contains-benchmark + */ +@Fork(5) +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +public class LTrimRTrim { + + private String src; + private static String ltrimResult; + private static String rtrimResult; + private static Pattern LTRIM = Pattern.compile("^\\s+"); + private static Pattern RTRIM = Pattern.compile("\\s+$"); + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + } + + @Setup + public void setup() { + src = " White spaces left and right "; + ltrimResult = "White spaces left and right "; + rtrimResult = " White spaces left and right"; + } + + public static String whileLtrim(String s) { + int i = 0; + while (i < s.length() && Character.isWhitespace(s.charAt(i))) { + i++; + } + return s.substring(i); + } + + public static String whileRtrim(String s) { + int i = s.length() - 1; + while (i >= 0 && Character.isWhitespace(s.charAt(i))) { + i--; + } + return s.substring(0, i + 1); + } + + private static boolean checkStrings(String ltrim, String rtrim) { + boolean result = false; + + if (ltrimResult.equalsIgnoreCase(ltrim) && rtrimResult.equalsIgnoreCase(rtrim)) + result = true; + + return result; + } + + // Going through the String detecting Whitespaces + @Benchmark + public boolean whileCharacters() { + String ltrim = whileLtrim(src); + String rtrim = whileRtrim(src); + + return checkStrings(ltrim, rtrim); + } + + // replaceAll() and Regular Expressions + @Benchmark + public boolean replaceAllRegularExpression() { + String ltrim = src.replaceAll("^\\s+", ""); + String rtrim = src.replaceAll("\\s+$", ""); + + return checkStrings(ltrim, rtrim); + } + + public static String patternLtrim(String s) { + return LTRIM.matcher(s) + .replaceAll(""); + } + + public static String patternRtrim(String s) { + return RTRIM.matcher(s) + .replaceAll(""); + } + + // Pattern matches() with replaceAll + @Benchmark + public boolean patternMatchesLTtrimRTrim() { + String ltrim = patternLtrim(src); + String rtrim = patternRtrim(src); + + return checkStrings(ltrim, rtrim); + } + + // Guava CharMatcher trimLeadingFrom / trimTrailingFrom + @Benchmark + public boolean guavaCharMatcher() { + String ltrim = CharMatcher.whitespace().trimLeadingFrom(src); + String rtrim = CharMatcher.whitespace().trimTrailingFrom(src); + + return checkStrings(ltrim, rtrim); + } + + // Apache Commons StringUtils containsIgnoreCase + @Benchmark + public boolean apacheCommonsStringUtils() { + String ltrim = StringUtils.stripStart(src, null); + String rtrim = StringUtils.stripEnd(src, null); + + return checkStrings(ltrim, rtrim); + } + +} diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/contains/CaseInsensitiveWorkaroundsUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/contains/CaseInsensitiveWorkaroundsUnitTest.java new file mode 100644 index 0000000000..30b2ca9fa5 --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/contains/CaseInsensitiveWorkaroundsUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.contains; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Assert; +import org.junit.Test; + +import java.util.regex.Pattern; + +/** + * BAEL-3739: Different ways to solve the contains() case insensitive behavior. + */ +public class CaseInsensitiveWorkaroundsUnitTest { + + private String src = "Lorem ipsum dolor sit amet"; + private String dest = "lorem"; + + @Test + public void givenString_whenCallingContainsWithToLowerOrUpperCase_shouldReturnTrue() { + // Use toLowerCase to avoid case insensitive issues + Assert.assertTrue(src.toLowerCase().contains(dest.toLowerCase())); + + // Use toUpperCase to avoid case insensitive issues + Assert.assertTrue(src.toUpperCase().contains(dest.toUpperCase())); + } + + @Test + public void givenString_whenCallingStringMatches_thenReturnsTrue() { + // Use String Matches to avoid case insensitive issues + Assert.assertTrue(src.matches("(?i).*" + dest + ".*")); + } + + @Test + public void givenString_whenCallingStringRegionMatches_thenReturnsTrue() { + // Use String Region Matches to avoid case insensitive issues + CaseInsensitiveWorkarounds comparator = new CaseInsensitiveWorkarounds(); + Assert.assertTrue(comparator.processRegionMatches(src, dest)); + } + + + @Test + public void givenString_whenCallingPaternCompileMatcherFind_thenReturnsTrue() { + // Use Pattern Compile Matcher and Find to avoid case insensitive issues + Assert.assertTrue(Pattern.compile(Pattern.quote(dest), + Pattern.CASE_INSENSITIVE) .matcher(src) .find()); + } + + @Test + public void givenString_whenCallingStringUtilsContainsIgnoreCase_thenReturnsTrue() { + // Use StringUtils containsIgnoreCase to avoid case insensitive issues + Assert.assertTrue(StringUtils.containsIgnoreCase(src, dest)); + } + +} diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encodetoutf8/StringEncodeUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encodetoutf8/StringEncodeUnitTest.java new file mode 100644 index 0000000000..a73104b234 --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encodetoutf8/StringEncodeUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.encodetoutf8; + +import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.codec.binary.StringUtils; +import org.junit.Test; + +public class StringEncodeUnitTest { + + @Test + public void givenGermanAsciiString_whenComparing_thenCompareNotEquals() { + String germanString = "Entwickeln Sie mit Vergnügen"; + byte[] germanBytes = germanString.getBytes(); + + String asciiEncodedString = new String(germanBytes, StandardCharsets.US_ASCII); + + assertNotEquals(germanString, asciiEncodedString); + } + + @Test + public void givenUsAsciiString_whenComparing_thenCompareNotEquals() { + String englishString = "Develop with pleasure"; + byte[] englishBytes = englishString.getBytes(); + + String asciiEncondedEnglishString = new String(englishBytes, StandardCharsets.US_ASCII); + + assertEquals(englishString, asciiEncondedEnglishString); + } + + /* + * ApacheCommonsCodecEncode + */ + @Test + public void givenSomeUnencodedString_whenApacheCommonsCodecEncode_thenCompareEquals() { + String rawString = "Entwickeln Sie mit Vergnügen"; + byte[] bytes = StringUtils.getBytesUtf8(rawString); + + String utf8EncodedString = StringUtils.newStringUtf8(bytes); + + assertEquals(rawString, utf8EncodedString); + } + + /* + * CoreJavaEncode + */ + @Test + public void givenSomeUnencodedString_whenCoreJavaEncode_thenCompareEquals() { + String rawString = "Entwickeln Sie mit Vergnügen"; + byte[] bytes = rawString.getBytes(StandardCharsets.UTF_8); + + String utf8EncodedString = new String(bytes, StandardCharsets.UTF_8); + + assertEquals(rawString, utf8EncodedString); + } + + /* + * Java7StandardCharsetsEncode + */ + @Test + public void givenSomeUnencodedString_whenJava7StandardCharsetsEncode_thenCompareEquals() { + String rawString = "Entwickeln Sie mit Vergnügen"; + ByteBuffer buffer = StandardCharsets.UTF_8.encode(rawString); + + String utf8EncodedString = StandardCharsets.UTF_8.decode(buffer) + .toString(); + + assertEquals(rawString, utf8EncodedString); + } +} diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java new file mode 100644 index 0000000000..0fb61ea121 --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.pdf.base64; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class EncodeDecodeUnitTest { + + private static final String IN_FILE = "src/test/resources/input.pdf"; + private static final String OUT_FILE = "src/test/resources/output.pdf"; + private static byte[] inFileBytes; + + @BeforeClass + public static void fileToByteArray() throws IOException { + inFileBytes = Files.readAllBytes(Paths.get(IN_FILE)); + } + + @Test + public void givenJavaBase64_whenEncoded_thenDecodedOK() throws IOException { + + byte[] encoded = java.util.Base64.getEncoder().encode(inFileBytes); + + byte[] decoded = java.util.Base64.getDecoder().decode(encoded); + + writeToFile(OUT_FILE, decoded); + + assertNotEquals(encoded.length, decoded.length); + assertEquals(inFileBytes.length, decoded.length); + + assertArrayEquals(decoded, inFileBytes); + + } + + @Test + public void givenApacheCommons_givenJavaBase64_whenEncoded_thenDecodedOK() throws IOException { + + byte[] encoded = org.apache.commons.codec.binary.Base64.encodeBase64(inFileBytes); + + byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(encoded); + + writeToFile(OUT_FILE, decoded); + + assertNotEquals(encoded.length, decoded.length); + assertEquals(inFileBytes.length, decoded.length); + + assertArrayEquals(decoded, inFileBytes); + } + + private void writeToFile(String fileName, byte[] bytes) throws IOException { + FileOutputStream fos = new FileOutputStream(fileName); + fos.write(bytes); + fos.flush(); + fos.close(); + } +} diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/trim/LTrimRTrimUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/trim/LTrimRTrimUnitTest.java new file mode 100644 index 0000000000..78bf01e540 --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/trim/LTrimRTrimUnitTest.java @@ -0,0 +1,78 @@ +package com.baeldung.trim; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Assert; +import org.junit.Test; + +import com.google.common.base.CharMatcher; + +import java.util.regex.Pattern; + +/** + * BAEL-3755: LTrim and RTrim examples. + */ +public class LTrimRTrimUnitTest { + + private String src = " White spaces left and right "; + private final static String ltrimResult = "White spaces left and right "; + private final static String rtrimResult = " White spaces left and right"; + + @Test + public void givenString_whenCallingWhileCharacters_thenReturnsTrue() { + String ltrim = LTrimRTrim.whileLtrim(src); + String rtrim = LTrimRTrim.whileRtrim(src); + + // Compare the Strings obtained and the expected + Assert.assertTrue(ltrimResult.equalsIgnoreCase(ltrim)); + + Assert.assertTrue(rtrimResult.equalsIgnoreCase(rtrim)); + } + + @Test + public void givenString_whenCallingContainsWithReplaceAll_shouldReturnTrue() { + // Use replaceAll with Regular Expressions + String ltrim = src.replaceAll("^\\s+", ""); + String rtrim = src.replaceAll("\\s+$", ""); + + // Compare the Strings obtained and the expected + Assert.assertTrue(ltrimResult.equalsIgnoreCase(ltrim)); + + Assert.assertTrue(rtrimResult.equalsIgnoreCase(rtrim)); + } + + @Test + public void givenString_whenCallingPaternCompileMatcherReplaceAll_thenReturnsTrue() { + // Use Pattern Compile Matcher and Find to avoid case insensitive issues + String ltrim = LTrimRTrim.patternLtrim(src); + String rtrim = LTrimRTrim.patternRtrim(src); + + // Compare the Strings obtained and the expected + Assert.assertTrue(ltrimResult.equalsIgnoreCase(ltrim)); + + Assert.assertTrue(rtrimResult.equalsIgnoreCase(rtrim)); + } + + @Test + public void givenString_whenCallingGuavaCharMatcher_thenReturnsTrue() { + // Use StringUtils containsIgnoreCase to avoid case insensitive issues + String ltrim = CharMatcher.whitespace().trimLeadingFrom(src);; + String rtrim = CharMatcher.whitespace().trimTrailingFrom(src); + + // Compare the Strings obtained and the expected + Assert.assertTrue(ltrimResult.equalsIgnoreCase(ltrim)); + + Assert.assertTrue(rtrimResult.equalsIgnoreCase(rtrim)); + } + + @Test + public void givenString_whenCallingStringUtilsStripStartEnd_thenReturnsTrue() { + // Use StringUtils containsIgnoreCase to avoid case insensitive issues + String ltrim = StringUtils.stripStart(src, null); + String rtrim = StringUtils.stripEnd(src, null); + + // Compare the Strings obtained and the expected + Assert.assertTrue(ltrimResult.equalsIgnoreCase(ltrim)); + Assert.assertTrue(rtrimResult.equalsIgnoreCase(rtrim)); + } + +} diff --git a/core-java-modules/core-java-string-operations-2/src/test/resources/input.pdf b/core-java-modules/core-java-string-operations-2/src/test/resources/input.pdf new file mode 100644 index 0000000000..94d9477974 Binary files /dev/null and b/core-java-modules/core-java-string-operations-2/src/test/resources/input.pdf differ diff --git a/core-java-modules/core-java-string-operations/pom.xml b/core-java-modules/core-java-string-operations/pom.xml index a1921c029f..a46b8ac129 100644 --- a/core-java-modules/core-java-string-operations/pom.xml +++ b/core-java-modules/core-java-string-operations/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-string-operations 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java index f701ab2e45..dd8b3a420d 100644 --- a/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java @@ -38,6 +38,11 @@ public class AddingNewLineToString { System.out.println("6. Using System.getProperty(\"line.separator\")"); rhyme = line1 + System.getProperty("line.separator") + line2; System.out.println(rhyme); + + //7. Using %n + System.out.println("7. Using %n"); + rhyme = "Humpty Dumpty sat on a wall.%nHumpty Dumpty had a great fall."; + System.out.println(rhyme); System.out.println("***HTML to rendered in a browser***"); //1. Line break for HTML using
diff --git a/core-java-modules/core-java-strings/README.md b/core-java-modules/core-java-strings/README.md index 4a418db29f..5daae8394a 100644 --- a/core-java-modules/core-java-strings/README.md +++ b/core-java-modules/core-java-strings/README.md @@ -12,3 +12,4 @@ This module contains articles about strings in Java. - [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) - [Java Multi-line String](https://www.baeldung.com/java-multiline-string) - [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) +- [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error) diff --git a/core-java-modules/core-java-strings/pom.xml b/core-java-modules/core-java-strings/pom.xml index 9dfe48527f..9e9bf0748b 100644 --- a/core-java-modules/core-java-strings/pom.xml +++ b/core-java-modules/core-java-strings/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-strings 0.1.0-SNAPSHOT diff --git a/core-java-modules/core-java-strings/src/main/resources/config.properties b/core-java-modules/core-java-strings/src/main/resources/config.properties new file mode 100644 index 0000000000..8197c13543 --- /dev/null +++ b/core-java-modules/core-java-strings/src/main/resources/config.properties @@ -0,0 +1 @@ +string.too.long= StringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLong diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/randomstrings/RandomStringsUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/randomstrings/RandomStringsUnitTest.java index 2806635d03..edfabc8777 100644 --- a/core-java-modules/core-java-strings/src/test/java/com/baeldung/randomstrings/RandomStringsUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/randomstrings/RandomStringsUnitTest.java @@ -1,72 +1,103 @@ -package com.baeldung.randomstrings; - -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.nio.charset.Charset; -import java.util.Random; - -public class RandomStringsUnitTest { - - private static final Logger LOG = LoggerFactory.getLogger(RandomStringsUnitTest.class); - - @Test - public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() { - final byte[] array = new byte[7]; // length is bounded by 7 - new Random().nextBytes(array); - final String generatedString = new String(array, Charset.forName("UTF-8")); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() { - final int leftLimit = 97; // letter 'a' - final int rightLimit = 122; // letter 'z' - final int targetStringLength = 10; - final Random random = new Random(); - final StringBuilder buffer = new StringBuilder(targetStringLength); - - for (int i = 0; i < targetStringLength; i++) { - final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1)); - buffer.append((char) randomLimitedInt); - } - final String generatedString = buffer.toString(); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomString_thenCorrect() { - final String generatedString = RandomStringUtils.random(10); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() { - final String generatedString = RandomStringUtils.randomAlphabetic(10); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { - final String generatedString = RandomStringUtils.randomAlphanumeric(10); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() { - final int length = 10; - final boolean useLetters = true; - final boolean useNumbers = false; - final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); - - LOG.debug(generatedString); - } - -} +package com.baeldung.randomstrings; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.nio.charset.Charset; +import java.util.Random; + +public class RandomStringsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(RandomStringsUnitTest.class); + + @Test + public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() { + byte[] array = new byte[7]; // length is bounded by 7 + new Random().nextBytes(array); + String generatedString = new String(array, Charset.forName("UTF-8")); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() { + int leftLimit = 97; // letter 'a' + int rightLimit = 122; // letter 'z' + int targetStringLength = 10; + Random random = new Random(); + StringBuilder buffer = new StringBuilder(targetStringLength); + + for (int i = 0; i < targetStringLength; i++) { + int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1)); + buffer.append((char) randomLimitedInt); + } + String generatedString = buffer.toString(); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingJava8_whenGeneratingRandomAlphabeticString_thenCorrect() { + int leftLimit = 97; // letter 'a' + int rightLimit = 122; // letter 'z' + int targetStringLength = 10; + Random random = new Random(); + + String generatedString = random.ints(leftLimit, rightLimit + 1) + .limit(targetStringLength) + .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) + .toString(); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingJava8_whenGeneratingRandomAlphanumericString_thenCorrect() { + int leftLimit = 48; // numeral '0' + int rightLimit = 122; // letter 'z' + int targetStringLength = 10; + Random random = new Random(); + + String generatedString = random.ints(leftLimit, rightLimit + 1) + .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)) + .limit(targetStringLength) + .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) + .toString(); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomString_thenCorrect() { + String generatedString = RandomStringUtils.random(10); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() { + String generatedString = RandomStringUtils.randomAlphabetic(10); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { + String generatedString = RandomStringUtils.randomAlphanumeric(10); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() { + int length = 10; + boolean useLetters = true; + boolean useNumbers = false; + String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); + + LOG.debug(generatedString); + } + +} diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringtoolong/StringTooLongUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringtoolong/StringTooLongUnitTest.java new file mode 100644 index 0000000000..4035cadb83 --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringtoolong/StringTooLongUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.stringtoolong; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.apache.commons.io.IOUtils; +import org.junit.Test; + +public class StringTooLongUnitTest { + @Test + public void whenDeclaringTooLongString_thenCompilationError() { + String stringTooLong = ""; + assertThat(stringTooLong).isNotEmpty(); + } + + @Test + public void whenStoringInFileTooLongString_thenNoCompilationError() throws IOException { + FileInputStream fis = new FileInputStream("src/test/resources/stringtoolong.txt"); + String stringTooLong = IOUtils.toString(fis, "UTF-8"); + assertThat(stringTooLong).isNotEmpty(); + } + + @Test + public void whenStoringInPropertiesString_thenNoCompilationError() throws IOException { + String sValue = null; + try (InputStream input = new FileInputStream("src/main/resources/config.properties")) { + Properties prop = new Properties(); + prop.load(input); + sValue = prop.getProperty("string.too.long"); + } + assertThat(sValue).isNotEmpty(); + } +} + \ No newline at end of file diff --git a/core-java-modules/core-java-strings/src/test/resources/stringtoolong.txt b/core-java-modules/core-java-strings/src/test/resources/stringtoolong.txt new file mode 100644 index 0000000000..6b2649aaa8 --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/resources/stringtoolong.txt @@ -0,0 +1 @@ + StringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLong \ No newline at end of file diff --git a/core-java-modules/core-java-sun/pom.xml b/core-java-modules/core-java-sun/pom.xml index 03b6646fec..d60ab71db0 100644 --- a/core-java-modules/core-java-sun/pom.xml +++ b/core-java-modules/core-java-sun/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java-sun 0.1.0-SNAPSHOT @@ -40,20 +42,6 @@ - - org.apache.maven.plugins - maven-jar-plugin - ${maven-jar-plugin.version} - - - - true - libs/ - org.baeldung.executable.ExecutableMavenJar - - - - org.codehaus.mojo exec-maven-plugin @@ -65,7 +53,7 @@ -Xmx300m -XX:+UseParallelGC -classpath - + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed @@ -95,7 +83,7 @@ java -classpath - + org.openjdk.jmh.Main .* @@ -115,7 +103,6 @@ 1.8.0 - 3.0.2 \ No newline at end of file diff --git a/core-java-modules/core-java-text/README.md b/core-java-modules/core-java-text/README.md deleted file mode 100644 index 5a6db4e8fd..0000000000 --- a/core-java-modules/core-java-text/README.md +++ /dev/null @@ -1,6 +0,0 @@ -========= - -## Core Java 8 Cookbooks and Examples - -### Relevant Articles: -- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance) \ No newline at end of file diff --git a/core-java-modules/core-java-text/pom.xml b/core-java-modules/core-java-text/pom.xml deleted file mode 100644 index 640b90764a..0000000000 --- a/core-java-modules/core-java-text/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - 4.0.0 - core-java-text - 0.1.0-SNAPSHOT - core-java-text - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - core-java-text - - - src/main/resources - true - - - - - diff --git a/core-java-modules/core-java-time-measurements/pom.xml b/core-java-modules/core-java-time-measurements/pom.xml index 9377b04690..b751cc0d74 100644 --- a/core-java-modules/core-java-time-measurements/pom.xml +++ b/core-java-modules/core-java-time-measurements/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 com.baeldung.exception.numberformat core-java-time-measurements @@ -95,7 +96,7 @@ 3.6.1 1.8.9 - 2.0.0-RC.4 + 2.0.0 1.44 2.22.1 diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index c7ae946ab5..bffb88cafb 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -2,7 +2,6 @@ ### Relevant Articles: - [Java Timer](http://www.baeldung.com/java-timer-and-timertask) -- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java) - [Getting Started with Java Properties](http://www.baeldung.com/java-properties) - [Introduction to Nashorn](http://www.baeldung.com/java-nashorn) - [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) @@ -11,9 +10,8 @@ - [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method) - [Introduction to Java Serialization](http://www.baeldung.com/java-serialization) - [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) - [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) -- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack) +- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack) - [Compiling Java *.class Files with javac](http://www.baeldung.com/javac) - [Introduction to Javadoc](http://www.baeldung.com/javadoc) - [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable) diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml index 341363f8ed..9b89fffd40 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-java 0.1.0-SNAPSHOT @@ -90,101 +92,6 @@ - - org.apache.maven.plugins - maven-jar-plugin - ${maven-jar-plugin.version} - - - - 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 - ${maven-shade-plugin.version} - - - - shade - - - true - - - org.baeldung.executable.ExecutableMavenJar - - - - - - - - - com.jolira - onejar-maven-plugin - ${onejar-maven-plugin.version} - - - - 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} - - - - repackage - - - spring-boot - org.baeldung.executable.ExecutableMavenJar - - - - - org.codehaus.mojo exec-maven-plugin @@ -196,7 +103,7 @@ -Xmx300m -XX:+UseParallelGC -classpath - + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed @@ -207,8 +114,8 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} @@ -262,7 +169,7 @@ java -classpath - + org.openjdk.jmh.Main .* @@ -273,111 +180,6 @@ - - - - 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 - - - - - - - - @@ -392,11 +194,9 @@ 1.1 3.0.0-M1 - 3.0.2 - 1.4.4 - 3.1.1 - 2.0.3.RELEASE 1.6.0 + 1.8 + 1.8 diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/timer/DatabaseMigrationTask.java b/core-java-modules/core-java/src/main/java/com/baeldung/timer/DatabaseMigrationTask.java new file mode 100644 index 0000000000..322c1d2f4e --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/timer/DatabaseMigrationTask.java @@ -0,0 +1,19 @@ +package com.baeldung.timer; + +import java.util.List; +import java.util.TimerTask; + +public class DatabaseMigrationTask extends TimerTask { + private List oldDatabase; + private List newDatabase; + + public DatabaseMigrationTask(List oldDatabase, List newDatabase) { + this.oldDatabase = oldDatabase; + this.newDatabase = newDatabase; + } + + @Override + public void run() { + newDatabase.addAll(oldDatabase); + } +} diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/timer/NewsletterTask.java b/core-java-modules/core-java/src/main/java/com/baeldung/timer/NewsletterTask.java new file mode 100644 index 0000000000..16dd6c12ff --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/timer/NewsletterTask.java @@ -0,0 +1,14 @@ +package com.baeldung.timer; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.TimerTask; + +public class NewsletterTask extends TimerTask { + @Override + public void run() { + System.out.println("Email sent at: " + + LocalDateTime.ofInstant(Instant.ofEpochMilli(scheduledExecutionTime()), ZoneId.systemDefault())); + } +} diff --git a/core-java-modules/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java b/core-java-modules/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java deleted file mode 100644 index d291ac0d3b..0000000000 --- a/core-java-modules/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.executable; - -import javax.swing.*; - -public class ExecutableMavenJar { - - public static void main(String[] args) { - JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1); - } -} diff --git a/core-java-modules/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/arrays/ArraysJoinAndSplitJUnitTest.java similarity index 97% rename from core-java-modules/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java rename to core-java-modules/core-java/src/test/java/com/baeldung/arrays/ArraysJoinAndSplitJUnitTest.java index 885c3bcd6c..b31a829f34 100644 --- a/core-java-modules/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java +++ b/core-java-modules/core-java/src/test/java/com/baeldung/arrays/ArraysJoinAndSplitJUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.arrays; +package com.baeldung.arrays; import java.util.Arrays; diff --git a/core-java-modules/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/rawtypes/RawTypesUnitTest.java similarity index 90% rename from core-java-modules/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java rename to core-java-modules/core-java/src/test/java/com/baeldung/rawtypes/RawTypesUnitTest.java index 161c053cea..3871368c07 100644 --- a/core-java-modules/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java +++ b/core-java-modules/core-java/src/test/java/com/baeldung/rawtypes/RawTypesUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.rawtypes; +package com.baeldung.rawtypes; import java.util.ArrayList; import java.util.List; diff --git a/core-java-modules/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/sandbox/SandboxJavaManualTest.java similarity index 98% rename from core-java-modules/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java rename to core-java-modules/core-java/src/test/java/com/baeldung/sandbox/SandboxJavaManualTest.java index 877122ce40..a58c2d4e6c 100644 --- a/core-java-modules/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java +++ b/core-java-modules/core-java/src/test/java/com/baeldung/sandbox/SandboxJavaManualTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.sandbox; +package com.baeldung.sandbox; import org.junit.Test; import org.slf4j.Logger; diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java index 2b04617f36..6a2feff551 100644 --- a/core-java-modules/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java +++ b/core-java-modules/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java @@ -1,123 +1,153 @@ package com.baeldung.stack; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.*; +import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.ListIterator; import java.util.Stack; +import java.util.stream.Collectors; -import org.junit.Test; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; public class StackUnitTest { @Test - public void whenStackIsCreated_thenItHasSize0() { - Stack intStack = new Stack(); + public void whenStackIsCreated_thenItHasSizeZero() { + Stack intStack = new Stack<>(); + assertEquals(0, intStack.size()); } @Test - public void givenEmptyStack_whenElementIsPushed_thenStackSizeisIncreased() { - Stack intStack = new Stack(); + public void whenElementIsPushed_thenStackSizeIsIncreased() { + Stack intStack = new Stack<>(); intStack.push(1); + assertEquals(1, intStack.size()); } @Test - public void givenEmptyStack_whenMultipleElementsArePushed_thenStackSizeisIncreased() { - Stack intStack = new Stack(); + public void whenMultipleElementsArePushed_thenStackSizeIsIncreased() { + Stack intStack = new Stack<>(); List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + boolean result = intStack.addAll(intList); + assertTrue(result); assertEquals(7, intList.size()); } @Test public void whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() { - Stack intStack = new Stack(); + Stack intStack = new Stack<>(); intStack.push(5); - intStack.pop(); + + Integer element = intStack.pop(); + + assertEquals(Integer.valueOf(5), element); assertTrue(intStack.isEmpty()); } @Test public void whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() { - Stack intStack = new Stack(); + Stack intStack = new Stack<>(); intStack.push(5); - intStack.peek(); + + Integer element = intStack.peek(); + + assertEquals(Integer.valueOf(5), element); assertEquals(1, intStack.search(5)); assertEquals(1, intStack.size()); } @Test public void whenElementIsOnStack_thenSearchReturnsItsDistanceFromTheTop() { - Stack intStack = new Stack(); + Stack intStack = new Stack<>(); intStack.push(5); - assertEquals(1, intStack.search(5)); + intStack.push(8); + + assertEquals(2, intStack.search(5)); } @Test public void whenElementIsOnStack_thenIndexOfReturnsItsIndex() { - Stack intStack = new Stack(); + Stack intStack = new Stack<>(); intStack.push(5); + int indexOf = intStack.indexOf(5); + assertEquals(0, indexOf); } @Test public void whenMultipleElementsAreOnStack_thenIndexOfReturnsLastElementIndex() { - Stack intStack = new Stack(); + Stack intStack = new Stack<>(); intStack.push(5); intStack.push(5); intStack.push(5); + int lastIndexOf = intStack.lastIndexOf(5); + assertEquals(2, lastIndexOf); } @Test - public void givenElementOnStack_whenRemoveElementIsInvoked_thenElementIsRemoved() { - Stack intStack = new Stack(); + public void whenRemoveElementIsInvoked_thenElementIsRemoved() { + Stack intStack = new Stack<>(); intStack.push(5); intStack.push(5); + intStack.removeElement(5); + assertEquals(1, intStack.size()); } @Test - public void givenElementOnStack_whenRemoveElementAtIsInvoked_thenElementIsRemoved() { - Stack intStack = new Stack(); + public void whenRemoveElementAtIsInvoked_thenElementIsRemoved() { + Stack intStack = new Stack<>(); intStack.push(5); intStack.push(7); + intStack.removeElementAt(1); + assertEquals(-1, intStack.search(7)); } @Test - public void givenElementsOnStack_whenRemoveAllElementsIsInvoked_thenAllElementsAreRemoved() { - Stack intStack = new Stack(); + public void whenRemoveAllElementsIsInvoked_thenAllElementsAreRemoved() { + Stack intStack = new Stack<>(); intStack.push(5); intStack.push(7); + intStack.removeAllElements(); + assertTrue(intStack.isEmpty()); } @Test public void givenElementsOnStack_whenRemoveAllIsInvoked_thenAllElementsFromCollectionAreRemoved() { - Stack intStack = new Stack(); + Stack intStack = new Stack<>(); List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); intStack.addAll(intList); intStack.add(500); + intStack.removeAll(intList); + assertEquals(1, intStack.size()); + assertEquals(1, intStack.search(500)); } @Test - public void givenElementsOnStack_whenRemoveIfIsInvoked_thenAllElementsSatysfyingConditionAreRemoved() { - Stack intStack = new Stack(); + public void whenRemoveIfIsInvoked_thenAllElementsSatysfyingConditionAreRemoved() { + Stack intStack = new Stack<>(); List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); intStack.addAll(intList); + intStack.removeIf(element -> element < 6); + assertEquals(2, intStack.size()); } @@ -126,12 +156,28 @@ public class StackUnitTest { Stack intStack = new Stack<>(); List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); intStack.addAll(intList); + ListIterator it = intStack.listIterator(); - Stack result = new Stack(); + + Stack result = new Stack<>(); while(it.hasNext()) { result.push(it.next()); } assertThat(result, equalTo(intStack)); } + + @Test + public void whenStackIsFiltered_allElementsNotSatisfyingFilterConditionAreDiscarded() { + Stack intStack = new Stack<>(); + List inputIntList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 9, 10); + intStack.addAll(inputIntList); + + List filtered = intStack + .stream() + .filter(element -> element <= 3) + .collect(Collectors.toList()); + + assertEquals(3, filtered.size()); + } } diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/timer/DatabaseMigrationTaskUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/timer/DatabaseMigrationTaskUnitTest.java new file mode 100644 index 0000000000..5f3ae63901 --- /dev/null +++ b/core-java-modules/core-java/src/test/java/com/baeldung/timer/DatabaseMigrationTaskUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.timer; + +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; + +class DatabaseMigrationTaskUnitTest { + @Test + void givenDatabaseMigrationTask_whenTimerScheduledForNowPlusTwoSeconds_thenDataMigratedAfterTwoSeconds() throws Exception { + List oldDatabase = Arrays.asList("Harrison Ford", "Carrie Fisher", "Mark Hamill"); + List newDatabase = new ArrayList<>(); + + LocalDateTime twoSecondsLater = LocalDateTime.now().plusSeconds(2); + Date twoSecondsLaterAsDate = Date.from(twoSecondsLater.atZone(ZoneId.systemDefault()).toInstant()); + + new Timer().schedule(new DatabaseMigrationTask(oldDatabase, newDatabase), twoSecondsLaterAsDate); + + while (LocalDateTime.now().isBefore(twoSecondsLater)) { + assertThat(newDatabase).isEmpty(); + Thread.sleep(500); + } + assertThat(newDatabase).containsExactlyElementsOf(oldDatabase); + } + + @Test + void givenDatabaseMigrationTask_whenTimerScheduledInTwoSeconds_thenDataMigratedAfterTwoSeconds() throws Exception { + List oldDatabase = Arrays.asList("Harrison Ford", "Carrie Fisher", "Mark Hamill"); + List newDatabase = new ArrayList<>(); + + new Timer().schedule(new DatabaseMigrationTask(oldDatabase, newDatabase), 2000); + + LocalDateTime twoSecondsLater = LocalDateTime.now().plusSeconds(2); + + while (LocalDateTime.now().isBefore(twoSecondsLater)) { + assertThat(newDatabase).isEmpty(); + Thread.sleep(500); + } + assertThat(newDatabase).containsExactlyElementsOf(oldDatabase); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/timer/JavaTimerLongRunningUnitTest.java similarity index 99% rename from core-java-modules/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java rename to core-java-modules/core-java/src/test/java/com/baeldung/timer/JavaTimerLongRunningUnitTest.java index 826106a09e..62afcd2f73 100644 --- a/core-java-modules/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java +++ b/core-java-modules/core-java/src/test/java/com/baeldung/timer/JavaTimerLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java; +package com.baeldung.timer; import org.junit.Test; import org.slf4j.Logger; diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java new file mode 100644 index 0000000000..ffbe39c2bc --- /dev/null +++ b/core-java-modules/core-java/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.timer; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.Timer; + +class NewsletterTaskUnitTest { + private final Timer timer = new Timer(); + + @AfterEach + void afterEach() { + timer.cancel(); + } + + @Test + void givenNewsletterTask_whenTimerScheduledEachSecondFixedDelay_thenNewsletterSentEachSecond() throws Exception { + timer.schedule(new NewsletterTask(), 0, 1000); + + for (int i = 0; i < 3; i++) { + Thread.sleep(1000); + } + } + + @Test + void givenNewsletterTask_whenTimerScheduledEachSecondFixedRate_thenNewsletterSentEachSecond() throws Exception { + timer.scheduleAtFixedRate(new NewsletterTask(), 0, 1000); + + for (int i = 0; i < 3; i++) { + Thread.sleep(1000); + } + } +} \ No newline at end of file diff --git a/core-java-modules/multimodulemavenproject/daomodule/pom.xml b/core-java-modules/multimodulemavenproject/daomodule/pom.xml index 79c2628ea4..15f1215d89 100644 --- a/core-java-modules/multimodulemavenproject/daomodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/daomodule/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.daomodule daomodule diff --git a/core-java-modules/multimodulemavenproject/entitymodule/pom.xml b/core-java-modules/multimodulemavenproject/entitymodule/pom.xml index 2cc789ffbb..3e5a478299 100644 --- a/core-java-modules/multimodulemavenproject/entitymodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/entitymodule/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.entitymodule entitymodule diff --git a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml index fa2d92d67f..196e58a419 100644 --- a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.mainappmodule mainappmodule @@ -17,17 +19,17 @@ com.baeldung.entitymodule entitymodule - 1.0 + ${entitymodule.version} com.baeldung.daomodule daomodule - 1.0 + ${daomodule.version} com.baeldung.userdaomodule userdaomodule - 1.0 + ${userdaomodule.version} @@ -43,6 +45,9 @@ 9 9 + 1.0 + 1.0 + 1.0 \ No newline at end of file diff --git a/core-java-modules/multimodulemavenproject/pom.xml b/core-java-modules/multimodulemavenproject/pom.xml index 1d4aebf32e..dcf9f7311e 100644 --- a/core-java-modules/multimodulemavenproject/pom.xml +++ b/core-java-modules/multimodulemavenproject/pom.xml @@ -45,10 +45,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 1.9 - 1.9 + ${source.version} + ${target.version} @@ -56,6 +56,9 @@ + 3.8.0 + 1.9 + 1.9 UTF-8 3.12.2 diff --git a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml index 19012708cf..f4a7e5c8f8 100644 --- a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.userdaomodule userdaomodule @@ -17,12 +19,12 @@ com.baeldung.entitymodule entitymodule - 1.0 + ${entitymodule.version} com.baeldung.daomodule daomodule - 1.0 + ${daomodule.version} @@ -38,6 +40,8 @@ 9 9 + 1.0 + 1.0 \ No newline at end of file diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index dcc98d77f6..c6cc3726e1 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.core-java-modules core-java-modules @@ -14,12 +16,120 @@ - pre-jpms - core-java-optional + core-java + + + + + core-java-8 + core-java-8-2 + + + + + + + + core-java-annotations + + core-java-arrays-sorting + core-java-arrays-guides + core-java-arrays-multidimensional + core-java-arrays-convert + core-java-arrays-operations-basic + core-java-arrays-operations-advanced + + core-java-collections + core-java-collections-2 + core-java-collections-3 + core-java-collections-array-list + core-java-collections-list + core-java-collections-list-2 + core-java-collections-list-3 + core-java-collections-maps + core-java-collections-maps-2 + core-java-collections-maps-3 + + + core-java-concurrency-2 + core-java-concurrency-advanced + core-java-concurrency-advanced-2 + core-java-concurrency-advanced-3 + core-java-concurrency-basic + core-java-concurrency-basic-2 + core-java-concurrency-collections + + + core-java-date-operations-2 + + + + core-java-exceptions + core-java-exceptions-2 + + core-java-function + + core-java-io + core-java-io-2 + core-java-io-apis + core-java-io-conversions + core-java-io-conversions-2 + + core-java-jar + core-java-jndi + + core-java-jvm + + core-java-lambdas + core-java-lang + core-java-lang-2 + core-java-lang-math + core-java-lang-math-2 + core-java-lang-oop-constructors + core-java-lang-oop-patterns + core-java-lang-oop-generics + core-java-lang-oop-modifiers + core-java-lang-oop-types + core-java-lang-oop-inheritance + core-java-lang-oop-methods + core-java-lang-oop-others core-java-lang-operators + core-java-lang-syntax + core-java-lang-syntax-2 + + core-java-networking core-java-networking-2 - core-java-security-manager - core-java-date-operations + core-java-nio + core-java-nio-2 + + core-java-optional + + + core-java-perf + + core-java-reflection + + core-java-security + core-java-security-2 + core-java-streams + core-java-streams-2 + core-java-streams-3 + core-java-string-algorithms + core-java-string-algorithms-2 + core-java-string-algorithms-3 + core-java-string-apis + core-java-string-conversions + core-java-string-conversions-2 + core-java-string-operations + core-java-string-operations-2 + core-java-strings + core-java-sun + + core-java-regex + + + + pre-jpms diff --git a/core-java-modules/pre-jpms/pom.xml b/core-java-modules/pre-jpms/pom.xml index cb23427138..18a2566e92 100644 --- a/core-java-modules/pre-jpms/pom.xml +++ b/core-java-modules/pre-jpms/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 pre-jpms 0.0.1-SNAPSHOT @@ -29,16 +30,16 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} org.apache.maven.plugins maven-dependency-plugin - 3.1.1 + ${dependency.plugin.version} copy-dependencies @@ -70,4 +71,11 @@ + + 3.1.1 + 3.8.0 + 1.8 + 1.8 + + diff --git a/core-kotlin-2/.gitignore b/core-kotlin-2/.gitignore deleted file mode 100644 index 0c017e8f8c..0000000000 --- a/core-kotlin-2/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -/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-2/README.md b/core-kotlin-2/README.md deleted file mode 100644 index 5a443c1831..0000000000 --- a/core-kotlin-2/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Core Kotlin - -This module contains articles about core Kotlin. - -### Relevant articles: - -- [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type) -- [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges) -- [Creating a Kotlin Range Iterator on a Custom Object](https://www.baeldung.com/kotlin-custom-range-iterator) -- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions) -- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations) -- [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) -- [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list) -- More articles: [[<-- prev]](/core-kotlin) diff --git a/core-kotlin-2/build.gradle b/core-kotlin-2/build.gradle deleted file mode 100644 index 1c52172404..0000000000 --- a/core-kotlin-2/build.gradle +++ /dev/null @@ -1,58 +0,0 @@ - - -group 'com.baeldung.ktor' -version '1.0-SNAPSHOT' - - -buildscript { - ext.kotlin_version = '1.3.30' - - 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" } - -repositories { - mavenCentral() - jcenter() - maven { url "https://dl.bintray.com/kotlin/ktor" } -} -sourceSets { - main{ - kotlin{ - srcDirs 'com/baeldung/ktor' - } - } -} - -test { - useJUnitPlatform() - testLogging { - events "passed", "skipped", "failed" - } -} - -dependencies { - implementation "ch.qos.logback:logback-classic:1.2.1" - implementation "org.jetbrains.kotlin:kotlin-stdlib:${kotlin_version}" - testImplementation 'org.junit.jupiter:junit-jupiter:5.4.2' - testImplementation 'junit:junit:4.12' - testImplementation 'org.assertj:assertj-core:3.12.2' - testImplementation 'org.mockito:mockito-core:2.27.0' - testImplementation "org.jetbrains.kotlin:kotlin-test:${kotlin_version}" - testImplementation "org.jetbrains.kotlin:kotlin-test-junit5:${kotlin_version}" -} diff --git a/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar b/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 5c2d1cf016..0000000000 Binary files a/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties b/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 5f1b1201a7..0000000000 --- a/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.4-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/core-kotlin-2/gradlew b/core-kotlin-2/gradlew deleted file mode 100644 index b0d6d0ab5d..0000000000 --- a/core-kotlin-2/gradlew +++ /dev/null @@ -1,188 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 2015 the original author or authors. -# -# 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. -# - -############################################################################## -## -## 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='"-Xmx64m" "-Xms64m"' - -# 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-2/gradlew.bat b/core-kotlin-2/gradlew.bat deleted file mode 100644 index 9991c50326..0000000000 --- a/core-kotlin-2/gradlew.bat +++ /dev/null @@ -1,100 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem 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, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@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="-Xmx64m" "-Xms64m" - -@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-2/pom.xml b/core-kotlin-2/pom.xml deleted file mode 100644 index be2f5fa68f..0000000000 --- a/core-kotlin-2/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - 4.0.0 - core-kotlin-2 - core-kotlin-2 - jar - - - com.baeldung - parent-kotlin - 1.0.0-SNAPSHOT - ../parent-kotlin - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.junit.jupiter - junit-jupiter - ${junit.jupiter.version} - test - - - org.mockito - mockito-core - ${mockito.version} - test - - - net.bytebuddy - byte-buddy - ${byte-buddy.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - org.jetbrains.kotlin - kotlin-test-junit5 - ${kotlin.version} - test - - - - - - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin.version} - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - - 1.8 - - - - - - - 1.3.30 - 5.4.2 - 2.27.0 - 1.9.12 - 3.10.0 - - - diff --git a/core-kotlin-2/resources/logback.xml b/core-kotlin-2/resources/logback.xml deleted file mode 100644 index 9452207268..0000000000 --- a/core-kotlin-2/resources/logback.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - %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-2/settings.gradle b/core-kotlin-2/settings.gradle deleted file mode 100644 index c91c993971..0000000000 --- a/core-kotlin-2/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ -rootProject.name = 'KtorWithKotlin' - diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/lists/ListsUnitTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/lists/ListsUnitTest.kt deleted file mode 100644 index 6fa7983689..0000000000 --- a/core-kotlin-2/src/test/kotlin/com/baeldung/lists/ListsUnitTest.kt +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.lists - -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -class ListsUnitTest { - - var batmans: List = listOf("Christian Bale", "Michael Keaton", "Ben Affleck", "George Clooney") - - @Test - fun whenFindASpecificItem_thenItemIsReturned() { - //Returns the first element matching the given predicate, or null if no such element was found. - val theFirstBatman = batmans.find { actor -> "Michael Keaton".equals(actor) } - assertEquals(theFirstBatman, "Michael Keaton") - } - - @Test - fun whenFilterWithPredicate_thenMatchingItemsAreReturned() { - //Returns a list containing only elements matching the given predicate. - val theCoolestBatmans = batmans.filter { actor -> actor.contains("a") } - assertTrue(theCoolestBatmans.contains("Christian Bale") && theCoolestBatmans.contains("Michael Keaton")) - } - - @Test - fun whenFilterNotWithPredicate_thenMatchingItemsAreReturned() { - //Returns a list containing only elements not matching the given predicate. - val theMehBatmans = batmans.filterNot { actor -> actor.contains("a") } - assertFalse(theMehBatmans.contains("Christian Bale") && theMehBatmans.contains("Michael Keaton")) - assertTrue(theMehBatmans.contains("Ben Affleck") && theMehBatmans.contains("George Clooney")) - } - -} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt deleted file mode 100644 index a9ddc99992..0000000000 --- a/core-kotlin-2/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt +++ /dev/null @@ -1,99 +0,0 @@ -package com.baeldung.lambda - -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -class SplittingTest { - private val evenList = listOf(0, "a", 1, "b", 2, "c"); - - private val unevenList = listOf(0, "a", 1, "b", 2, "c", 3); - - private fun verifyList(resultList: List>) { - assertEquals("[[0, a], [1, b], [2, c]]", resultList.toString()) - } - - private fun verifyPartialList(resultList: List>) { - assertEquals("[[0, a], [1, b], [2, c], [3]]", resultList.toString()) - } - - @Test - fun whenChunked_thenListIsSplit() { - val resultList = evenList.chunked(2) - verifyList(resultList) - } - - @Test - fun whenUnevenChunked_thenListIsSplit() { - val resultList = unevenList.chunked(2) - verifyPartialList(resultList) - } - - @Test - fun whenWindowed_thenListIsSplit() { - val resultList = evenList.windowed(2, 2) - verifyList(resultList) - } - - @Test - fun whenUnevenPartialWindowed_thenListIsSplit() { - val resultList = unevenList.windowed(2, 2, partialWindows = true) - verifyPartialList(resultList) - } - - @Test - fun whenUnevenWindowed_thenListIsSplit() { - val resultList = unevenList.windowed(2, 2, partialWindows = false) - verifyList(resultList) - } - - @Test - fun whenGroupByWithAscendingNumbers_thenListIsSplit() { - val numberList = listOf(1, 2, 3, 4, 5, 6); - val resultList = numberList.groupBy { (it + 1) / 2 } - assertEquals("[[1, 2], [3, 4], [5, 6]]", resultList.values.toString()) - assertEquals("[1, 2, 3]", resultList.keys.toString()) - } - - @Test - fun whenGroupByWithAscendingNumbersUneven_thenListIsSplit() { - val numberList = listOf(1, 2, 3, 4, 5, 6, 7); - val resultList = numberList.groupBy { (it + 1) / 2 }.values - assertEquals("[[1, 2], [3, 4], [5, 6], [7]]", resultList.toString()) - } - - @Test - fun whenGroupByWithRandomNumbers_thenListIsSplitInWrongWay() { - val numberList = listOf(1, 3, 8, 20, 23, 30); - val resultList = numberList.groupBy { (it + 1) / 2 } - assertEquals("[[1], [3], [8], [20], [23], [30]]", resultList.values.toString()) - assertEquals("[1, 2, 4, 10, 12, 15]", resultList.keys.toString()) - } - - @Test - fun whenWithIndexGroupBy_thenListIsSplit() { - val resultList = evenList.withIndex() - .groupBy { it.index / 2 } - .map { it.value.map { it.value } } - verifyList(resultList) - } - - @Test - fun whenWithIndexGroupByUneven_thenListIsSplit() { - val resultList = unevenList.withIndex() - .groupBy { it.index / 2 } - .map { it.value.map { it.value } } - verifyPartialList(resultList) - } - - @Test - fun whenFoldIndexed_thenListIsSplit() { - val resultList = evenList.foldIndexed(ArrayList>(evenList.size / 2)) { index, acc, item -> - if (index % 2 == 0) { - acc.add(ArrayList(2)) - } - acc.last().add(item) - acc - } - verifyList(resultList) - } -} \ No newline at end of file diff --git a/core-kotlin-2/src/test/resources/Kotlin.in b/core-kotlin-2/src/test/resources/Kotlin.in deleted file mode 100644 index d140d4429e..0000000000 --- a/core-kotlin-2/src/test/resources/Kotlin.in +++ /dev/null @@ -1,5 +0,0 @@ -Hello to Kotlin. Its: -1. Concise -2. Safe -3. Interoperable -4. Tool-friendly \ No newline at end of file diff --git a/core-kotlin-2/src/test/resources/Kotlin.out b/core-kotlin-2/src/test/resources/Kotlin.out deleted file mode 100644 index 63d15d2528..0000000000 --- a/core-kotlin-2/src/test/resources/Kotlin.out +++ /dev/null @@ -1,2 +0,0 @@ -Kotlin -Concise, Safe, Interoperable, Tool-friendly \ No newline at end of file diff --git a/core-kotlin-modules/README.md b/core-kotlin-modules/README.md deleted file mode 100644 index 974db9378a..0000000000 --- a/core-kotlin-modules/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Core Kotlin - -This module contains articles about core Kotlin. - - diff --git a/core-kotlin-modules/core-kotlin-2/README.md b/core-kotlin-modules/core-kotlin-2/README.md new file mode 100644 index 0000000000..d6d6b2f706 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-2/README.md @@ -0,0 +1,9 @@ +## Core Kotlin 2 + +This module contains articles about Kotlin core features. + +### Relevant articles: +- [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates) +- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-operator) +- [Sequences in Kotlin](https://www.baeldung.com/kotlin/sequences) +- [[<-- Prev]](/core-kotlin-modules/core-kotlin) diff --git a/core-kotlin-modules/core-kotlin-2/pom.xml b/core-kotlin-modules/core-kotlin-2/pom.xml new file mode 100644 index 0000000000..ae6e2d175a --- /dev/null +++ b/core-kotlin-modules/core-kotlin-2/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + core-kotlin-2 + core-kotlin-2 + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseDuration.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt similarity index 90% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UseDuration.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt index 40fb161c08..922c3a1988 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseDuration.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt @@ -1,4 +1,4 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime import java.time.Duration import java.time.LocalTime diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDate.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt similarity index 96% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDate.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt index 250c071bbe..81d50a70b2 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDate.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt @@ -1,4 +1,4 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime import java.time.DayOfWeek import java.time.LocalDate diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDateTime.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt similarity index 84% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDateTime.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt index ab7bbfcee1..5d0eb6a911 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDateTime.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt @@ -1,4 +1,4 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime import java.time.LocalDateTime diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalTime.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt similarity index 92% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalTime.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt index 152515621f..24402467e8 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalTime.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt @@ -1,6 +1,5 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime -import java.time.LocalDateTime import java.time.LocalTime import java.time.temporal.ChronoUnit diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UsePeriod.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt similarity index 90% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UsePeriod.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt index df66a3d546..d15e02eb37 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UsePeriod.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt @@ -1,4 +1,4 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime import java.time.LocalDate import java.time.Period diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseZonedDateTime.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt similarity index 87% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UseZonedDateTime.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt index fd1838bd2d..e2f3a207c4 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseZonedDateTime.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt @@ -1,4 +1,4 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime import java.time.LocalDateTime import java.time.ZoneId diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/CreateDateUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt similarity index 95% rename from kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/CreateDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt index d52a2f0f19..af5e08ea2d 100644 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/CreateDateUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt @@ -1,34 +1,34 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.LocalDate -import java.time.format.DateTimeFormatter - -class CreateDateUnitTest { - - @Test - fun givenString_whenDefaultFormat_thenCreated() { - - var date = LocalDate.parse("2018-12-31") - - assertThat(date).isEqualTo("2018-12-31") - } - - @Test - fun givenString_whenCustomFormat_thenCreated() { - - var formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy") - var date = LocalDate.parse("31-12-2018", formatter) - - assertThat(date).isEqualTo("2018-12-31") - } - - @Test - fun givenYMD_whenUsingOf_thenCreated() { - var date = LocalDate.of(2018, 12, 31) - - assertThat(date).isEqualTo("2018-12-31") - } - +package com.baeldung.kotlin.dates + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +class CreateDateUnitTest { + + @Test + fun givenString_whenDefaultFormat_thenCreated() { + + var date = LocalDate.parse("2018-12-31") + + assertThat(date).isEqualTo("2018-12-31") + } + + @Test + fun givenString_whenCustomFormat_thenCreated() { + + var formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy") + var date = LocalDate.parse("31-12-2018", formatter) + + assertThat(date).isEqualTo("2018-12-31") + } + + @Test + fun givenYMD_whenUsingOf_thenCreated() { + var date = LocalDate.of(2018, 12, 31) + + assertThat(date).isEqualTo("2018-12-31") + } + } \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/ExtractDateUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt similarity index 96% rename from kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/ExtractDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt index ef3841752b..d297f4b6c3 100644 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/ExtractDateUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt @@ -1,29 +1,29 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.DayOfWeek -import java.time.LocalDate -import java.time.Month - -class ExtractDateUnitTest { - - @Test - fun givenDate_thenExtractedYMD() { - var date = LocalDate.parse("2018-12-31") - - assertThat(date.year).isEqualTo(2018) - assertThat(date.month).isEqualTo(Month.DECEMBER) - assertThat(date.dayOfMonth).isEqualTo(31) - } - - @Test - fun givenDate_thenExtractedEraDowDoy() { - var date = LocalDate.parse("2018-12-31") - - assertThat(date.era.toString()).isEqualTo("CE") - assertThat(date.dayOfWeek).isEqualTo(DayOfWeek.MONDAY) - assertThat(date.dayOfYear).isEqualTo(365) - } - +package com.baeldung.kotlin.dates + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.Month + +class ExtractDateUnitTest { + + @Test + fun givenDate_thenExtractedYMD() { + var date = LocalDate.parse("2018-12-31") + + assertThat(date.year).isEqualTo(2018) + assertThat(date.month).isEqualTo(Month.DECEMBER) + assertThat(date.dayOfMonth).isEqualTo(31) + } + + @Test + fun givenDate_thenExtractedEraDowDoy() { + var date = LocalDate.parse("2018-12-31") + + assertThat(date.era.toString()).isEqualTo("CE") + assertThat(date.dayOfWeek).isEqualTo(DayOfWeek.MONDAY) + assertThat(date.dayOfYear).isEqualTo(365) + } + } \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/FormatDateUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt similarity index 96% rename from kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/FormatDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt index 11ff6ec9f0..f7ca414aee 100644 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/FormatDateUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt @@ -1,29 +1,29 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.LocalDate -import java.time.format.DateTimeFormatter - -class FormatDateUnitTest { - - @Test - fun givenDate_whenDefaultFormat_thenFormattedString() { - - var date = LocalDate.parse("2018-12-31") - - assertThat(date.toString()).isEqualTo("2018-12-31") - } - - @Test - fun givenDate_whenCustomFormat_thenFormattedString() { - - var date = LocalDate.parse("2018-12-31") - - var formatter = DateTimeFormatter.ofPattern("dd-MMMM-yyyy") - var formattedDate = date.format(formatter) - - assertThat(formattedDate).isEqualTo("31-December-2018") - } - +package com.baeldung.kotlin.dates + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +class FormatDateUnitTest { + + @Test + fun givenDate_whenDefaultFormat_thenFormattedString() { + + var date = LocalDate.parse("2018-12-31") + + assertThat(date.toString()).isEqualTo("2018-12-31") + } + + @Test + fun givenDate_whenCustomFormat_thenFormattedString() { + + var date = LocalDate.parse("2018-12-31") + + var formatter = DateTimeFormatter.ofPattern("dd-MMMM-yyyy") + var formattedDate = date.format(formatter) + + assertThat(formattedDate).isEqualTo("31-December-2018") + } + } \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/PeriodDateUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt similarity index 96% rename from kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/PeriodDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt index e6b66634d3..e8ca2971e8 100644 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/PeriodDateUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt @@ -1,48 +1,48 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.LocalDate -import java.time.Period - -class PeriodDateUnitTest { - - @Test - fun givenYMD_thenCreatePeriod() { - var period = Period.of(1, 2, 3) - - assertThat(period.toString()).isEqualTo("P1Y2M3D") - } - - @Test - fun givenPeriod_whenAdd_thenModifiedDate() { - var period = Period.of(1, 2, 3) - - var date = LocalDate.of(2018, 6, 25) - var modifiedDate = date.plus(period) - - assertThat(modifiedDate).isEqualTo("2019-08-28") - } - - @Test - fun givenPeriod_whenSubtracted_thenModifiedDate() { - var period = Period.of(1, 2, 3) - - var date = LocalDate.of(2018, 6, 25) - var modifiedDate = date.minus(period) - - assertThat(modifiedDate).isEqualTo("2017-04-22") - } - - @Test - fun givenTwoDate_whenUsingBetween_thenDiffOfDates() { - - var date1 = LocalDate.parse("2018-06-25") - var date2 = LocalDate.parse("2018-12-25") - - var period = Period.between(date1, date2) - - assertThat(period.toString()).isEqualTo("P6M") - } - +package com.baeldung.kotlin.dates + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import java.time.LocalDate +import java.time.Period + +class PeriodDateUnitTest { + + @Test + fun givenYMD_thenCreatePeriod() { + var period = Period.of(1, 2, 3) + + assertThat(period.toString()).isEqualTo("P1Y2M3D") + } + + @Test + fun givenPeriod_whenAdd_thenModifiedDate() { + var period = Period.of(1, 2, 3) + + var date = LocalDate.of(2018, 6, 25) + var modifiedDate = date.plus(period) + + assertThat(modifiedDate).isEqualTo("2019-08-28") + } + + @Test + fun givenPeriod_whenSubtracted_thenModifiedDate() { + var period = Period.of(1, 2, 3) + + var date = LocalDate.of(2018, 6, 25) + var modifiedDate = date.minus(period) + + assertThat(modifiedDate).isEqualTo("2017-04-22") + } + + @Test + fun givenTwoDate_whenUsingBetween_thenDiffOfDates() { + + var date1 = LocalDate.parse("2018-06-25") + var date2 = LocalDate.parse("2018-12-25") + + var period = Period.between(date1, date2) + + assertThat(period.toString()).isEqualTo("P6M") + } + } \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt similarity index 92% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateTimeUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt index 8f9f8374ed..f3615a527c 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateTimeUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt @@ -1,14 +1,12 @@ package com.baeldung.kotlin.datetime -import com.baeldung.datetime.UseLocalDateTime +import com.baeldung.dates.datetime.UseLocalDateTime +import org.junit.Assert.assertEquals +import org.junit.Test import java.time.LocalDate import java.time.LocalTime import java.time.Month -import org.junit.Test - -import org.junit.Assert.assertEquals - class UseLocalDateTimeUnitTest { var useLocalDateTime = UseLocalDateTime() diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt similarity index 97% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt index ac42e91c6c..e6353c9dab 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt @@ -1,6 +1,6 @@ package com.baeldung.kotlin.datetime -import com.baeldung.datetime.UseLocalDate +import com.baeldung.dates.datetime.UseLocalDate import org.junit.Assert import org.junit.Test import java.time.DayOfWeek diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt similarity index 95% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalTimeUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt index 83fc57f850..1afe03ca48 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalTimeUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt @@ -1,10 +1,9 @@ package com.baeldung.kotlin.datetime -import com.baeldung.datetime.UseLocalTime -import java.time.LocalTime - +import com.baeldung.dates.datetime.UseLocalTime import org.junit.Assert import org.junit.Test +import java.time.LocalTime class UseLocalTimeUnitTest { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UsePeriodUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt similarity index 94% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UsePeriodUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt index 48be72feb0..36e1e5533a 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UsePeriodUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt @@ -1,11 +1,10 @@ package com.baeldung.kotlin.datetime -import com.baeldung.datetime.UsePeriod -import java.time.LocalDate -import java.time.Period - +import com.baeldung.dates.datetime.UsePeriod import org.junit.Assert import org.junit.Test +import java.time.LocalDate +import java.time.Period class UsePeriodUnitTest { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseZonedDateTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt similarity index 90% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseZonedDateTimeUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt index a9d7d973ef..aa2cdaa4f3 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseZonedDateTimeUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt @@ -1,6 +1,6 @@ package com.baeldung.kotlin.datetime -import com.baeldung.datetime.UseZonedDateTime +import com.baeldung.dates.datetime.UseZonedDateTime import org.junit.Assert import org.junit.Test import java.time.LocalDateTime diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt new file mode 100644 index 0000000000..a41e213c44 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt @@ -0,0 +1,54 @@ +package com.baeldung.sequeces + +import org.junit.Test +import kotlin.test.assertEquals +import java.time.Instant + +class SequencesTest { + + @Test + fun shouldBuildSequenceWhenUsingFromElements() { + val seqOfElements = sequenceOf("first" ,"second", "third") + .toList() + assertEquals(3, seqOfElements.count()) + } + + @Test + fun shouldBuildSequenceWhenUsingFromFunction() { + val seqFromFunction = generateSequence(Instant.now()) {it.plusSeconds(1)} + .take(3) + .toList() + assertEquals(3, seqFromFunction.count()) + } + + @Test + fun shouldBuildSequenceWhenUsingFromChunks() { + val seqFromChunks = sequence { + yield(1) + yieldAll((2..5).toList()) + }.toList() + assertEquals(5, seqFromChunks.count()) + } + + @Test + fun shouldBuildSequenceWhenUsingFromCollection() { + val seqFromIterable = (1..10) + .asSequence() + .toList() + assertEquals(10, seqFromIterable.count()) + } + + @Test + fun shouldShowNoCountDiffWhenUsingWithAndWithoutSequence() { + val withSequence = (1..10).asSequence() + .filter{it % 2 == 1} + .map { it * 2 } + .toList() + val withoutSequence = (1..10) + .filter{it % 2 == 1} + .map { it * 2 } + .toList() + assertEquals(withSequence.count(), withoutSequence.count()) + } + +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt new file mode 100644 index 0000000000..21dfdd2ae0 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt @@ -0,0 +1,24 @@ +package com.baeldung.ternary + +import org.junit.Test +import kotlin.test.assertEquals + +class TernaryOperatorTest { + + @Test + fun `using If`() { + val a = true + val result = if (a) "yes" else "no" + assertEquals("yes", result) + } + + @Test + fun `using When`() { + val a = true + val result = when(a) { + true -> "yes" + false -> "no" + } + assertEquals("yes", result) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/README.md b/core-kotlin-modules/core-kotlin-advanced/README.md new file mode 100644 index 0000000000..2e99e3b078 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-advanced/README.md @@ -0,0 +1,11 @@ +## Core Kotlin Advanced + +This module contains articles about advanced topics in Kotlin. + +### Relevant articles: +- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl) +- [Regular Expressions in Kotlin](https://www.baeldung.com/kotlin-regular-expressions) +- [Idiomatic Logging in Kotlin](https://www.baeldung.com/kotlin-logging) +- [Mapping of Data Objects in Kotlin](https://www.baeldung.com/kotlin-data-objects) +- [Reflection with Kotlin](https://www.baeldung.com/kotlin-reflection) +- [Kotlin Contracts](https://www.baeldung.com/kotlin-contracts) diff --git a/core-kotlin-modules/core-kotlin-advanced/pom.xml b/core-kotlin-modules/core-kotlin-advanced/pom.xml new file mode 100644 index 0000000000..5ddfef23cc --- /dev/null +++ b/core-kotlin-modules/core-kotlin-advanced/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + core-kotlin-advanced + core-kotlin-advanced + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + + + 1.3.30 + 3.10.0 + + + \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/contract/CallsInPlaceEffect.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/contract/CallsInPlaceEffect.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/contract/CallsInPlaceEffect.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/contract/CallsInPlaceEffect.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/contract/ReturnsEffect.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/contract/ReturnsEffect.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/contract/ReturnsEffect.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/contract/ReturnsEffect.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datamapping/User.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/User.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/datamapping/User.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/User.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt similarity index 82% rename from core-kotlin/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt index 6113ed3591..1f3d7f3b47 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt @@ -3,10 +3,10 @@ package com.baeldung.datamapping import kotlin.reflect.full.memberProperties fun User.toUserView() = UserView( - name = "$firstName $lastName", - address = "$street $houseNumber", - telephone = phone, - age = age + name = "$firstName $lastName", + address = "$street $houseNumber", + telephone = phone, + age = age ) fun User.toUserViewReflection() = with(::UserView) { diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datamapping/UserView.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/UserView.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/datamapping/UserView.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/UserView.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/dsl/SqlDsl.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/dsl/SqlDsl.kt similarity index 98% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/dsl/SqlDsl.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/dsl/SqlDsl.kt index 5296d301a3..207e9dbd53 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/dsl/SqlDsl.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/dsl/SqlDsl.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.dsl +package com.baeldung.dsl abstract class Condition { diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnAny.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnAny.kt similarity index 93% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnAny.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnAny.kt index 32d968fff5..01edf5e871 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnAny.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnAny.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.logging +package com.baeldung.logging import org.slf4j.Logger diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnMarkerInterface.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnMarkerInterface.kt similarity index 95% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnMarkerInterface.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnMarkerInterface.kt index b33d4c9f93..8210361345 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnMarkerInterface.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnMarkerInterface.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.logging +package com.baeldung.logging import org.slf4j.Logger import org.slf4j.LoggerFactory diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsProperty.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsProperty.kt similarity index 88% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsProperty.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsProperty.kt index 979b3b3a10..60ac0800e2 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsProperty.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsProperty.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.logging +package com.baeldung.logging open class LoggerAsProperty { private val logger = getLogger(javaClass) diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsPropertyDelegate.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsPropertyDelegate.kt similarity index 92% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsPropertyDelegate.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsPropertyDelegate.kt index 23f04722be..83cde2b446 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsPropertyDelegate.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsPropertyDelegate.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.logging +package com.baeldung.logging import org.slf4j.Logger import kotlin.properties.ReadOnlyProperty @@ -43,5 +43,5 @@ fun main(args: Array) { class LoggerDelegate : ReadOnlyProperty { override fun getValue(thisRef: R, property: KProperty<*>) = - getLogger(getClassForLogging(thisRef.javaClass)) + getLogger(getClassForLogging(thisRef.javaClass)) } diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerInCompanionObject.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerInCompanionObject.kt similarity index 97% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerInCompanionObject.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerInCompanionObject.kt index f973606369..6a44675e45 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerInCompanionObject.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerInCompanionObject.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.logging +package com.baeldung.logging open class LoggerInCompanionObject { companion object { diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/Util.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/Util.kt similarity index 90% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/Util.kt rename to core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/Util.kt index b9c0d9e34c..44dba53cb7 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/Util.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/Util.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.logging +package com.baeldung.logging import org.slf4j.Logger import org.slf4j.LoggerFactory diff --git a/core-kotlin/src/test/kotlin/com/baeldung/datamapping/UserTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/datamapping/UserTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/datamapping/UserTest.kt rename to core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/datamapping/UserTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/dsl/SqlDslTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/dsl/SqlDslTest.kt similarity index 97% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/dsl/SqlDslTest.kt rename to core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/dsl/SqlDslTest.kt index 55ae44e4dc..a370e7f15d 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/dsl/SqlDslTest.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/dsl/SqlDslTest.kt @@ -1,8 +1,7 @@ -package com.baeldung.kotlin.dsl +package com.baeldung.dsl import org.assertj.core.api.Assertions.assertThat import org.junit.Test -import java.lang.Exception class SqlDslTest { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/JavaReflectionTest.kt similarity index 95% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt rename to core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/JavaReflectionTest.kt index 0d0e7b724d..c77774dd81 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/JavaReflectionTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.reflection +package com.baeldung.reflection import org.junit.Ignore import org.junit.Test diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KClassTest.kt similarity index 98% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt rename to core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KClassTest.kt index 56183b50be..f5d83cd13d 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KClassTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.reflection +package com.baeldung.reflection import org.junit.Assert import org.junit.Ignore diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KMethodTest.kt similarity index 98% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt rename to core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KMethodTest.kt index 17e9913731..b58c199a7c 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KMethodTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.reflection +package com.baeldung.reflection import org.junit.Assert import org.junit.Test diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/stdlib/RegexTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/regex/RegexTest.kt similarity index 95% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/stdlib/RegexTest.kt rename to core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/regex/RegexTest.kt index eeb587ee22..5cb54b4dda 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/stdlib/RegexTest.kt +++ b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/regex/RegexTest.kt @@ -1,12 +1,7 @@ -package com.baeldung.kotlin.stdlib +package com.baeldung.regex import org.junit.Test -import java.beans.ExceptionListener -import java.beans.XMLEncoder -import java.io.* -import java.lang.Exception import kotlin.test.* -import kotlin.text.RegexOption.* class RegexTest { diff --git a/core-kotlin-modules/core-kotlin-collections/README.md b/core-kotlin-modules/core-kotlin-collections/README.md new file mode 100644 index 0000000000..f0da2b4cfd --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/README.md @@ -0,0 +1,11 @@ +## Core Kotlin Collections + +This module contains articles about core Kotlin collections. + +### Relevant articles: +- [Split a List Into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) +- [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list) +- [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api) +- [Converting a List to Map in Kotlin](https://www.baeldung.com/kotlin-list-to-map) +- [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection) +- [Collection Transformations in Kotlin](https://www.baeldung.com/kotlin-collection-transformations) diff --git a/core-kotlin-modules/core-kotlin-collections/pom.xml b/core-kotlin-modules/core-kotlin-collections/pom.xml new file mode 100644 index 0000000000..52401d267c --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + core-kotlin-collections + core-kotlin-collections + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + + + 1.3.30 + 3.6.1 + 3.10.0 + + + \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CollectionsTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/CollectionsTest.kt similarity index 99% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/CollectionsTest.kt rename to core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/CollectionsTest.kt index 59d6adccac..64b1f72eab 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CollectionsTest.kt +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/CollectionsTest.kt @@ -1,9 +1,9 @@ -package com.baeldung.kotlin +package com.baeldung.collections import org.junit.Test -import kotlin.test.assertTrue -import kotlin.test.assertFalse import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue class CollectionsTest { @@ -142,5 +142,5 @@ class CollectionsTest { val finalResult = theList.fold( 1000, { oldResult, currentItem -> oldResult + (currentItem *currentItem)}) print(finalResult) assertEquals(1091, finalResult) - } + } } \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/AssociateUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/AssociateUnitTest.kt new file mode 100644 index 0000000000..68f7040c4c --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/AssociateUnitTest.kt @@ -0,0 +1,48 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class AssociateUnitTest { + @Test + fun testToMap() { + val input = listOf(Pair("one", 1), Pair("two", 2)) + val map = input.toMap() + assertEquals(mapOf("one" to 1, "two" to 2), map) + } + + @Test + fun testAssociateWith() { + val inputs = listOf("Hi", "there") + val map = inputs.associateWith { k -> k.length } + assertEquals(mapOf("Hi" to 2, "there" to 5), map) + } + + @Test + fun testAssociateBy() { + val inputs = listOf("Hi", "there") + val map = inputs.associateBy { v -> v.length } + assertEquals(mapOf(2 to "Hi", 5 to "there"), map) + } + + @Test + fun testAssociate() { + val inputs = listOf("Hi", "there") + val map = inputs.associate { e -> Pair(e.toUpperCase(), e.reversed()) } + assertEquals(mapOf("HI" to "iH", "THERE" to "ereht"), map) + } + + @Test + fun testAssociateByDuplicateKeys() { + val inputs = listOf("one", "two") + val map = inputs.associateBy { v -> v.length } + assertEquals(mapOf(3 to "two"), map) + } + + @Test + fun testGroupBy() { + val inputs = listOf("one", "two", "three") + val map = inputs.groupBy { v -> v.length } + assertEquals(mapOf(3 to listOf("one", "two"), 5 to listOf("three")), map) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FilterUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FilterUnitTest.kt new file mode 100644 index 0000000000..591577e4f3 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FilterUnitTest.kt @@ -0,0 +1,43 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class FilterUnitTest { + @Test + fun testFilterWithLambda() { + val input = listOf(1, 2, 3, 4, 5) + val filtered = input.filter { it <= 3 } + assertEquals(listOf(1, 2, 3), filtered) + } + + @Test + fun testFilterWithMethodReference() { + val input = listOf(1, 2, 3, 4, 5) + val filtered = input.filter(this::isSmall) + assertEquals(listOf(1, 2, 3), filtered) + } + + @Test + fun testFilterNotWithMethodReference() { + val input = listOf(1, 2, 3, 4, 5) + val filtered = input.filterNot(this::isSmall) + assertEquals(listOf(4, 5), filtered) + } + + @Test + fun testFilterIndexed() { + val input = listOf(5, 4, 3, 2, 1) + val filtered = input.filterIndexed { index, element -> index < 3 } + assertEquals(listOf(5, 4, 3), filtered) + } + + @Test + fun testFilterNotNull() { + val nullable: List = listOf("Hello", null, "World") + val nonnull: List = nullable.filterNotNull() + assertEquals(listOf("Hello", "World"), nonnull) + } + + private fun isSmall(i: Int) = i <= 3 +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FlattenUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FlattenUnitTest.kt new file mode 100644 index 0000000000..69fbceb8e3 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FlattenUnitTest.kt @@ -0,0 +1,21 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class FlattenUnitTest { + @Test + fun testFlatten() { + val inputs = listOf("one", "two", "three") + val characters = inputs.map(String::toList) + val flattened = characters.flatten(); + assertEquals(listOf('o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e'), flattened) + } + + @Test + fun testFlatMap() { + val inputs = listOf("one", "two", "three") + val characters = inputs.flatMap(String::toList) + assertEquals(listOf('o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e'), characters) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/JoinToUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/JoinToUnitTest.kt new file mode 100644 index 0000000000..2ac0cdca50 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/JoinToUnitTest.kt @@ -0,0 +1,46 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class JoinToUnitTest { + @Test + fun testJoinToString() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val simpleString = inputs.joinToString() + assertEquals("Jan, Feb, Mar, Apr, May", simpleString) + + val detailedString = inputs.joinToString(separator = ",", prefix="Months: ", postfix=".") + assertEquals("Months: Jan,Feb,Mar,Apr,May.", detailedString) + } + + @Test + fun testJoinToStringLimits() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val simpleString = inputs.joinToString(limit = 3) + assertEquals("Jan, Feb, Mar, ...", simpleString) + } + + @Test + fun testJoinToStringTransform() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val simpleString = inputs.joinToString(transform = String::toUpperCase) + assertEquals("JAN, FEB, MAR, APR, MAY", simpleString) + } + + @Test + fun testJoinTo() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val output = StringBuilder() + output.append("My ") + .append(inputs.size) + .append(" elements: ") + inputs.joinTo(output) + + assertEquals("My 5 elements: Jan, Feb, Mar, Apr, May", output.toString()) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/MapUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/MapUnitTest.kt new file mode 100644 index 0000000000..e22fcbe903 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/MapUnitTest.kt @@ -0,0 +1,53 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class MapUnitTest { + @Test + fun testMapWithLambda() { + val input = listOf("one", "two", "three") + + val reversed = input.map { it.reversed() } + assertEquals(listOf("eno", "owt", "eerht"), reversed) + + val lengths = input.map { it.length } + assertEquals(listOf(3, 3, 5), lengths) + } + + @Test + fun testMapIndexed() { + val input = listOf(3, 2, 1) + val result = input.mapIndexed { index, value -> index * value } + assertEquals(listOf(0, 2, 2), result) + } + + @Test + fun testMapNotNull() { + val input = listOf(1, 2, 3, 4, 5) + val smallSquares = input.mapNotNull { + if (it <= 3) { + it * it + } else { + null + } + } + assertEquals(listOf(1, 4, 9), smallSquares) + } + + @Test + fun mapMapKeys() { + val inputs = mapOf("one" to 1, "two" to 2, "three" to 3) + + val uppercases = inputs.mapKeys { it.key.toUpperCase() } + assertEquals(mapOf("ONE" to 1, "TWO" to 2, "THREE" to 3), uppercases) + } + + @Test + fun mapMapValues() { + val inputs = mapOf("one" to 1, "two" to 2, "three" to 3) + + val squares = inputs.mapValues { it.value * it.value } + assertEquals(mapOf("one" to 1, "two" to 4, "three" to 9), squares) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ReduceUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ReduceUnitTest.kt new file mode 100644 index 0000000000..6821b7cdb9 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ReduceUnitTest.kt @@ -0,0 +1,22 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class ReduceUnitTest { + @Test + fun testJoinToStringAsReduce() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val result = inputs.reduce { acc, next -> "$acc, $next" } + assertEquals("Jan, Feb, Mar, Apr, May", result) + } + + @Test + fun testFoldToLength() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val result = inputs.fold(0) { acc, next -> acc + next.length } + assertEquals(15, result) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ZipUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ZipUnitTest.kt new file mode 100644 index 0000000000..66aeeceef4 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ZipUnitTest.kt @@ -0,0 +1,34 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class ZipUnitTest { + @Test + fun testZip() { + val left = listOf("one", "two", "three") + val right = listOf(1, 2, 3) + val zipped = left.zip(right) + assertEquals (listOf(Pair("one", 1), Pair("two", 2), Pair("three", 3)), zipped) + } + + @Test + fun testZipShort() { + val left = listOf("one", "two") + val right = listOf(1, 2, 3) + val zipped = left.zip(right) + assertEquals (listOf(Pair("one", 1), Pair("two", 2)), zipped) + } + + @Test + fun testUnzip() { + val left = listOf("one", "two", "three") + val right = listOf(1, 2, 3) + val zipped = left.zip(right) + + val (newLeft, newRight) = zipped.unzip() + assertEquals(left, newLeft) + assertEquals(right, newRight) + } + +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/filter/ChunkedTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/ChunkedTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/filter/ChunkedTest.kt rename to core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/ChunkedTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/filter/DistinctTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/DistinctTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/filter/DistinctTest.kt rename to core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/DistinctTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/filter/DropTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/DropTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/filter/DropTest.kt rename to core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/DropTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/filter/FilterTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/FilterTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/filter/FilterTest.kt rename to core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/FilterTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/filter/SliceTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/SliceTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/filter/SliceTest.kt rename to core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/SliceTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/filter/TakeTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/TakeTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/filter/TakeTest.kt rename to core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/TakeTest.kt diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/findelement/FindAnElementInAListUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/findelement/FindAnElementInAListUnitTest.kt new file mode 100644 index 0000000000..52e7e2a5b5 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/findelement/FindAnElementInAListUnitTest.kt @@ -0,0 +1,34 @@ +package com.baeldung.findelement + +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class FindAnElementInAListUnitTest { + + var batmans: List = listOf("Christian Bale", "Michael Keaton", "Ben Affleck", "George Clooney") + + @Test + fun whenFindASpecificItem_thenItemIsReturned() { + //Returns the first element matching the given predicate, or null if no such element was found. + val theFirstBatman = batmans.find { actor -> "Michael Keaton".equals(actor) } + assertEquals(theFirstBatman, "Michael Keaton") + } + + @Test + fun whenFilterWithPredicate_thenMatchingItemsAreReturned() { + //Returns a list containing only elements matching the given predicate. + val theCoolestBatmans = batmans.filter { actor -> actor.contains("a") } + assertTrue(theCoolestBatmans.contains("Christian Bale") && theCoolestBatmans.contains("Michael Keaton")) + } + + @Test + fun whenFilterNotWithPredicate_thenMatchingItemsAreReturned() { + //Returns a list containing only elements not matching the given predicate. + val theMehBatmans = batmans.filterNot { actor -> actor.contains("a") } + assertFalse(theMehBatmans.contains("Christian Bale") && theMehBatmans.contains("Michael Keaton")) + assertTrue(theMehBatmans.contains("Ben Affleck") && theMehBatmans.contains("George Clooney")) + } + +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt new file mode 100644 index 0000000000..7b263914c6 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt @@ -0,0 +1,59 @@ +package com.baeldung.foldvsreduce + +import org.junit.Test +import org.junit.jupiter.api.assertThrows +import java.lang.RuntimeException +import kotlin.test.assertEquals + +class FoldAndReduceTest { + + @Test + fun testReduceLimitations() { + val numbers: List = listOf(1, 2, 3) + val sum: Number = numbers.reduce { acc, next -> acc + next } + assertEquals(6, sum) + + val emptyList = listOf() + assertThrows { emptyList.reduce { acc, next -> acc + next } } + + // doesn't compile + // val sum = numbers.reduce { acc, next -> acc.toLong() + next.toLong()} + } + + @Test + fun testFold() { + + val numbers: List = listOf(1, 2, 3) + val sum: Int = numbers.fold(0, { acc, next -> acc + next }) + assertEquals(6, sum) + + //change result type + val sumLong: Long = numbers.fold(0L, { acc, next -> acc + next.toLong() }) + assertEquals(6L, sumLong) + + val emptyList = listOf() + val emptySum = emptyList.fold(0, { acc, next -> acc + next }) + assertEquals(0, emptySum) + + //power of changing result type + val (even, odd) = numbers.fold(Pair(listOf(), listOf()), { acc, next -> + if (next % 2 == 0) Pair(acc.first + next, acc.second) + else Pair(acc.first, acc.second + next) + }) + + assertEquals(listOf(2), even) + assertEquals(listOf(1, 3), odd) + } + + @Test + fun testVariationsOfFold() { + val numbers = listOf(1, 2, 3) + val reversed = numbers.foldRight(listOf(), { next, acc -> acc + next}) + assertEquals(listOf(3,2,1), reversed) + + val reversedIndexes = numbers.foldRightIndexed(listOf(), { i, _, acc -> acc + i }) + assertEquals(listOf(2,1,0), reversedIndexes) + } + + +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ListToMapTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/ListToMapTest.kt similarity index 98% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/ListToMapTest.kt rename to core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/ListToMapTest.kt index e3477931bb..93e4f11fdf 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ListToMapTest.kt +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/ListToMapTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.listtomap import org.junit.Test import kotlin.test.assertTrue diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/User.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/User.kt new file mode 100644 index 0000000000..89eb9ac701 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/User.kt @@ -0,0 +1,3 @@ +package com.baeldung.listtomap + +data class User(val name: String, val age: Int, val hobbies: List) diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/splitlist/SplitListIntoPartsTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/splitlist/SplitListIntoPartsTest.kt new file mode 100644 index 0000000000..627c7eaacf --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/splitlist/SplitListIntoPartsTest.kt @@ -0,0 +1,99 @@ +package com.baeldung.splitlist + +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class SplitListIntoPartsTest { + private val evenList = listOf(0, "a", 1, "b", 2, "c"); + + private val unevenList = listOf(0, "a", 1, "b", 2, "c", 3); + + private fun verifyList(resultList: List>) { + assertEquals("[[0, a], [1, b], [2, c]]", resultList.toString()) + } + + private fun verifyPartialList(resultList: List>) { + assertEquals("[[0, a], [1, b], [2, c], [3]]", resultList.toString()) + } + + @Test + fun whenChunked_thenListIsSplit() { + val resultList = evenList.chunked(2) + verifyList(resultList) + } + + @Test + fun whenUnevenChunked_thenListIsSplit() { + val resultList = unevenList.chunked(2) + verifyPartialList(resultList) + } + + @Test + fun whenWindowed_thenListIsSplit() { + val resultList = evenList.windowed(2, 2) + verifyList(resultList) + } + + @Test + fun whenUnevenPartialWindowed_thenListIsSplit() { + val resultList = unevenList.windowed(2, 2, partialWindows = true) + verifyPartialList(resultList) + } + + @Test + fun whenUnevenWindowed_thenListIsSplit() { + val resultList = unevenList.windowed(2, 2, partialWindows = false) + verifyList(resultList) + } + + @Test + fun whenGroupByWithAscendingNumbers_thenListIsSplit() { + val numberList = listOf(1, 2, 3, 4, 5, 6); + val resultList = numberList.groupBy { (it + 1) / 2 } + assertEquals("[[1, 2], [3, 4], [5, 6]]", resultList.values.toString()) + assertEquals("[1, 2, 3]", resultList.keys.toString()) + } + + @Test + fun whenGroupByWithAscendingNumbersUneven_thenListIsSplit() { + val numberList = listOf(1, 2, 3, 4, 5, 6, 7); + val resultList = numberList.groupBy { (it + 1) / 2 }.values + assertEquals("[[1, 2], [3, 4], [5, 6], [7]]", resultList.toString()) + } + + @Test + fun whenGroupByWithRandomNumbers_thenListIsSplitInWrongWay() { + val numberList = listOf(1, 3, 8, 20, 23, 30); + val resultList = numberList.groupBy { (it + 1) / 2 } + assertEquals("[[1], [3], [8], [20], [23], [30]]", resultList.values.toString()) + assertEquals("[1, 2, 4, 10, 12, 15]", resultList.keys.toString()) + } + + @Test + fun whenWithIndexGroupBy_thenListIsSplit() { + val resultList = evenList.withIndex() + .groupBy { it.index / 2 } + .map { it.value.map { it.value } } + verifyList(resultList) + } + + @Test + fun whenWithIndexGroupByUneven_thenListIsSplit() { + val resultList = unevenList.withIndex() + .groupBy { it.index / 2 } + .map { it.value.map { it.value } } + verifyPartialList(resultList) + } + + @Test + fun whenFoldIndexed_thenListIsSplit() { + val resultList = evenList.foldIndexed(ArrayList>(evenList.size / 2)) { index, acc, item -> + if (index % 2 == 0) { + acc.add(ArrayList(2)) + } + acc.last().add(item) + acc + } + verifyList(resultList) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/README.md b/core-kotlin-modules/core-kotlin-concurrency/README.md new file mode 100644 index 0000000000..09d9055a2b --- /dev/null +++ b/core-kotlin-modules/core-kotlin-concurrency/README.md @@ -0,0 +1,7 @@ +## Core Kotlin Concurrency + +This module contains articles about concurrency in Kotlin. + +### Relevant articles: +- [Threads vs Coroutines in Kotlin](https://www.baeldung.com/kotlin-threads-coroutines) +- [Introduction to Kotlin Coroutines](https://www.baeldung.com/kotlin-coroutines) diff --git a/core-kotlin-modules/core-kotlin-concurrency/pom.xml b/core-kotlin-modules/core-kotlin-concurrency/pom.xml new file mode 100644 index 0000000000..7c3b0fb5b6 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-concurrency/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + core-kotlin-concurrency + core-kotlin-concurrency + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + + + 1.3.30 + 3.10.0 + + + \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleRunnable.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleRunnable.kt new file mode 100644 index 0000000000..80ffb4077a --- /dev/null +++ b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleRunnable.kt @@ -0,0 +1,8 @@ +package com.baeldung.threadsvscoroutines + +class SimpleRunnable: Runnable { + + override fun run() { + println("${Thread.currentThread()} has run.") + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleThread.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleThread.kt new file mode 100644 index 0000000000..6647dac0ef --- /dev/null +++ b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleThread.kt @@ -0,0 +1,8 @@ +package com.baeldung.threadsvscoroutines + +class SimpleThread: Thread() { + + override fun run() { + println("${Thread.currentThread()} has run.") + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesUnitTest.kt b/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/coroutines/CoroutinesUnitTest.kt similarity index 99% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesUnitTest.kt rename to core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/coroutines/CoroutinesUnitTest.kt index 324cf1109b..6b9437a8ab 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/coroutines/CoroutinesUnitTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.coroutines import kotlinx.coroutines.* import org.junit.Test diff --git a/core-kotlin/src/test/kotlin/com/baeldung/thread/CoroutineUnitTest.kt b/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/CoroutineUnitTest.kt similarity index 96% rename from core-kotlin/src/test/kotlin/com/baeldung/thread/CoroutineUnitTest.kt rename to core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/CoroutineUnitTest.kt index 1f1609b06b..ff385d0869 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/thread/CoroutineUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/CoroutineUnitTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.thread +package com.baeldung.threadsvscoroutines import kotlinx.coroutines.* import org.junit.jupiter.api.Test diff --git a/core-kotlin/src/test/kotlin/com/baeldung/thread/ThreadUnitTest.kt b/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/ThreadUnitTest.kt similarity index 94% rename from core-kotlin/src/test/kotlin/com/baeldung/thread/ThreadUnitTest.kt rename to core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/ThreadUnitTest.kt index fa2f1edc36..9503751fa3 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/thread/ThreadUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/ThreadUnitTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.thread +package com.baeldung.threadsvscoroutines import org.junit.jupiter.api.Test import kotlin.concurrent.thread diff --git a/core-kotlin-modules/core-kotlin-lang-2/README.md b/core-kotlin-modules/core-kotlin-lang-2/README.md new file mode 100644 index 0000000000..e64a39cb9b --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/README.md @@ -0,0 +1,13 @@ +## Core Kotlin Lang + +This module contains articles about core features in the Kotlin language. + +### Relevant articles: +- [Kotlin return, break, continue Keywords](https://www.baeldung.com/kotlin-return-break-continue) +- [Infix Functions in Kotlin](https://www.baeldung.com/kotlin-infix-functions) +- [Lambda Expressions in Kotlin](https://www.baeldung.com/kotlin-lambda-expressions) +- [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final) +- [Initializing Arrays in Kotlin](https://www.baeldung.com/kotlin-initialize-array) +- [Lazy Initialization in Kotlin](https://www.baeldung.com/kotlin-lazy-initialization) +- [Comprehensive Guide to Null Safety in Kotlin](https://www.baeldung.com/kotlin-null-safety) +- [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang) diff --git a/core-kotlin-modules/core-kotlin-lang-2/pom.xml b/core-kotlin-modules/core-kotlin-lang-2/pom.xml new file mode 100644 index 0000000000..753147728d --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + core-kotlin-lang-2 + core-kotlin-lang-2 + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + \ No newline at end of file diff --git a/core-kotlin/src/main/java/com/baeldung/lazy/ClassWithHeavyInitialization.java b/core-kotlin-modules/core-kotlin-lang-2/src/main/java/com/baeldung/lazy/ClassWithHeavyInitialization.java similarity index 100% rename from core-kotlin/src/main/java/com/baeldung/lazy/ClassWithHeavyInitialization.java rename to core-kotlin-modules/core-kotlin-lang-2/src/main/java/com/baeldung/lazy/ClassWithHeavyInitialization.java diff --git a/core-kotlin/src/main/kotlin/com/baeldung/lambda/Lambda.kt b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/lambda/Lambda.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/lambda/Lambda.kt rename to core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/lambda/Lambda.kt diff --git a/core-kotlin/src/test/java/com/baeldung/kotlin/LazyJavaUnitTest.java b/core-kotlin-modules/core-kotlin-lang-2/src/test/java/com/baeldung/lazy/LazyJavaUnitTest.java similarity index 86% rename from core-kotlin/src/test/java/com/baeldung/kotlin/LazyJavaUnitTest.java rename to core-kotlin-modules/core-kotlin-lang-2/src/test/java/com/baeldung/lazy/LazyJavaUnitTest.java index e2fe58d537..01c87d9543 100644 --- a/core-kotlin/src/test/java/com/baeldung/kotlin/LazyJavaUnitTest.java +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/java/com/baeldung/lazy/LazyJavaUnitTest.java @@ -1,7 +1,5 @@ -package com.baeldung.kotlin; +package com.baeldung.lazy; - -import com.baeldung.lazy.ClassWithHeavyInitialization; import org.junit.Test; import static junit.framework.TestCase.assertTrue; diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayInitializationTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/arrayinitialization/ArrayInitializationTest.kt similarity index 96% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayInitializationTest.kt rename to core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/arrayinitialization/ArrayInitializationTest.kt index ba3694c831..d4b9d607fb 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayInitializationTest.kt +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/arrayinitialization/ArrayInitializationTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.arrayinitialization import org.junit.Test import kotlin.test.assertEquals diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/ConstantUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/ConstantUnitTest.kt similarity index 79% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/ConstantUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/ConstantUnitTest.kt index 51d45b8df0..d9bf433208 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/ConstantUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/ConstantUnitTest.kt @@ -1,5 +1,5 @@ -import com.baeldung.kotlin.constant.TestKotlinConstantClass -import com.baeldung.kotlin.constant.TestKotlinConstantObject +package com.baeldung.constant + import org.junit.jupiter.api.Test import kotlin.test.assertEquals diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantClass.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantClass.kt new file mode 100644 index 0000000000..3c4d4db220 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantClass.kt @@ -0,0 +1,8 @@ +package com.baeldung.constant + + +class TestKotlinConstantClass { + companion object { + const val COMPANION_OBJECT_NUMBER = 40 + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/TestKotlinConstantObject.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantObject.kt similarity index 86% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/TestKotlinConstantObject.kt rename to core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantObject.kt index 815fdeaf14..a6951b4481 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/TestKotlinConstantObject.kt +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantObject.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.constant +package com.baeldung.constant object TestKotlinConstantObject { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/InfixFunctionsTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/infixfunctions/InfixFunctionsTest.kt similarity index 97% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/InfixFunctionsTest.kt rename to core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/infixfunctions/InfixFunctionsTest.kt index fc4286460a..0b09d34013 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/InfixFunctionsTest.kt +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/infixfunctions/InfixFunctionsTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.infixfunctions import org.junit.Assert import org.junit.Test diff --git a/core-kotlin/src/test/java/com/baeldung/lambda/LambdaKotlinUnitTest.java b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lambda/LambdaKotlinUnitTest.java similarity index 100% rename from core-kotlin/src/test/java/com/baeldung/lambda/LambdaKotlinUnitTest.java rename to core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lambda/LambdaKotlinUnitTest.java diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt new file mode 100644 index 0000000000..bddabee462 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt @@ -0,0 +1,96 @@ +package com.baeldung.lambda + +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class LambdaTest { + + @Test + fun whenCallingALambda_thenPerformTheAction() { + assertEquals(9, inferredType(3)) + } + + @Test + fun whenCallingAMoreComplicatedLambda_thenPerformTheAction() { + assertEquals("500", intToBiggerString(5)) + } + + @Test + fun whenPassingALambdaObject_thenCallTriggerLambda() { + val lambda = { arg: Double -> + arg == 4.329 + } + + val result = invokeLambda(lambda) + + assertTrue(result) + } + + @Test + fun whenPassingALambdaLiteral_thenCallTriggerLambda() { + val result = invokeLambda({ + true + }) + + assertTrue(result) + } + + @Test + fun whenPassingALambdaLiteralOutsideBrackets_thenCallTriggerLambda() { + val result = invokeLambda { arg -> arg.isNaN() } + + assertFalse(result) + } + + @Test + fun whenPassingAnAnonymousFunction_thenCallTriggerLambda() { + val result = invokeLambda(fun(arg: Double): Boolean { + return arg >= 0 + }) + + assertTrue(result) + } + + @Test + fun whenUsingLambda_thenCalculateGrade() { + val gradeCalculation = getCalculationLambda() + + assertEquals(false, gradeCalculation(-40)) + assertEquals("Pass", gradeCalculation(50)) + } + + @Test + fun whenUsingReturnStatementLambda_thenCalculateGrade() { + val gradeCalculation: Int.() -> String = getCalculationLambdaWithReturn() + + assertEquals("Distinction", 80.gradeCalculation()) + assertEquals("Error", 244_234_324.gradeCalculation()) + } + + @Test + fun whenUsingAnonymousFunction_thenCalculateGrade() { + val gradeCalculation = getCalculationAnonymousFunction() + + assertEquals("Error", gradeCalculation(244_234_324)) + assertEquals("Pass", gradeCalculation(50)) + } + + @Test + fun whenPassingAFunctionReference_thenCallTriggerLambda() { + val reference = Double::isFinite + val result = invokeLambda(reference) + + assertTrue(result) + } + + @Test + fun givenArray_whenMappingArray_thenPerformCalculationOnAllElements() { + val expected = listOf("100", "200", "300", "400", "500") + val actual = manyLambda(arrayOf(1, 2, 3, 4, 5)) + + assertEquals(expected, actual) + } + +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/late/LateInitUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/late/LateInitUnitTest.kt new file mode 100644 index 0000000000..c99e438742 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/late/LateInitUnitTest.kt @@ -0,0 +1,22 @@ +package com.baeldung.late + +import org.junit.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class LateInitUnitTest { + + private lateinit var answer: String + + @Test(expected = UninitializedPropertyAccessException::class) + fun givenLateInit_WhenNotInitialized_ShouldThrowAnException() { + answer.length + } + + @Test + fun givenLateInit_TheIsInitialized_ReturnsTheInitializationStatus() { + assertFalse { this::answer.isInitialized } + answer = "42" + assertTrue { this::answer.isInitialized } + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LazyUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lazy/LazyUnitTest.kt similarity index 98% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/LazyUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lazy/LazyUnitTest.kt index 1169fb9193..b9b21ed4d9 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LazyUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lazy/LazyUnitTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.lazy import org.junit.Test import java.util.concurrent.CountDownLatch diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/NullSafetyTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/nullsafety/NullSafetyTest.kt similarity index 98% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/NullSafetyTest.kt rename to core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/nullsafety/NullSafetyTest.kt index 0ecc74b6fb..66fc043581 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/NullSafetyTest.kt +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/nullsafety/NullSafetyTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.nullsafety import org.junit.Test import kotlin.test.assertEquals @@ -8,6 +8,7 @@ import kotlin.test.assertTrue class NullSafetyTest { + @Test fun givenNonNullableField_whenAssignValueToIt_thenNotNeedToCheckAgainstNull() { //given diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/structuraljump/StructuralJumpUnitTest.kt similarity index 98% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/structuraljump/StructuralJumpUnitTest.kt index 436dc9e2ba..88011ab396 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/structuraljump/StructuralJumpUnitTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.structuraljump import org.junit.Test import kotlin.test.assertEquals diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/README.md b/core-kotlin-modules/core-kotlin-lang-oop-2/README.md new file mode 100644 index 0000000000..27536273dc --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-oop-2/README.md @@ -0,0 +1,10 @@ +## Core Kotlin Lang OOP + +This module contains articles about Object-Oriented Programming in Kotlin + +### Relevant articles: + +- [Generics in Kotlin](https://www.baeldung.com/kotlin-generics) +- [Delegated Properties in Kotlin](https://www.baeldung.com/kotlin-delegated-properties) +- [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern) +- [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang-oop) diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/pom.xml b/core-kotlin-modules/core-kotlin-lang-oop-2/pom.xml new file mode 100644 index 0000000000..f0adea121e --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-oop-2/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + core-kotlin-lang-oop-2 + core-kotlin-lang-oop-2 + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/generic/Reified.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/generic/Reified.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/generic/Reified.kt rename to core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/generic/Reified.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt rename to core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt rename to core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt rename to core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt rename to core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/GenericsTest.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/GenericsTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/GenericsTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/GenericsTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt diff --git a/core-kotlin-modules/core-kotlin-lang-oop/README.md b/core-kotlin-modules/core-kotlin-lang-oop/README.md new file mode 100644 index 0000000000..0c1aeb7850 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-oop/README.md @@ -0,0 +1,17 @@ +## Core Kotlin Lang OOP + +This module contains articles about Object-Oriented Programming in Kotlin + +### Relevant articles: + +- [Data Classes in Kotlin](https://www.baeldung.com/kotlin-data-classes) +- [Sealed Classes in Kotlin](https://www.baeldung.com/kotlin-sealed-classes) +- [Extension Methods in Kotlin](https://www.baeldung.com/kotlin-extension-methods) +- [Objects in Kotlin](https://www.baeldung.com/kotlin-objects) +- [Working with Enums in Kotlin](https://www.baeldung.com/kotlin-enum) +- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors) +- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes) +- [Guide to Kotlin Interfaces](https://www.baeldung.com/kotlin-interfaces) +- [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes) +- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods) +- More articles: [[next -->]](/core-kotlin-modules/core-kotlin-lang-oop-2) diff --git a/core-kotlin-modules/core-kotlin-lang-oop/pom.xml b/core-kotlin-modules/core-kotlin-lang-oop/pom.xml new file mode 100644 index 0000000000..03fc80f07d --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-oop/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + core-kotlin-lang-oop + core-kotlin-lang-oop + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + \ No newline at end of file diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Car.kt similarity index 100% rename from core-kotlin/src/main/java/com/baeldung/constructor/Car.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Car.kt diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Employee.kt similarity index 100% rename from core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Employee.kt diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Person.java b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Person.java similarity index 100% rename from core-kotlin/src/main/java/com/baeldung/constructor/Person.java rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Person.java diff --git a/core-kotlin/src/main/java/com/baeldung/dataclass/Movie.java b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/dataclass/Movie.java similarity index 100% rename from core-kotlin/src/main/java/com/baeldung/dataclass/Movie.java rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/dataclass/Movie.java diff --git a/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/constructor/Person.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/constructor/Person.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/dataclass/Movie.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Movie.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/dataclass/Movie.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Movie.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/dataclass/Sandbox.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Sandbox.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/dataclass/Sandbox.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Sandbox.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/CardType.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/CardType.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/ICardLimit.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/ICardLimit.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/Sealed.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/Sealed.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/StringUtil.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/StringUtil.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/StringUtil.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/StringUtil.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/nested/Computer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/nested/Computer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/static/LoggingUtils.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/LoggingUtils.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/static/LoggingUtils.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/LoggingUtils.kt diff --git a/core-kotlin/src/test/java/com/baeldung/kotlin/StringUtilUnitTest.java b/core-kotlin-modules/core-kotlin-lang-oop/src/test/java/com/baeldung/kotlin/StringUtilUnitTest.java similarity index 100% rename from core-kotlin/src/test/java/com/baeldung/kotlin/StringUtilUnitTest.java rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/java/com/baeldung/kotlin/StringUtilUnitTest.java diff --git a/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/ObjectsTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ObjectsTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/ObjectsTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ObjectsTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/OuterClass.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/OuterClass.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/OuterClass.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/OuterClass.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/ReverseStringComparator.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ReverseStringComparator.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/ReverseStringComparator.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ReverseStringComparator.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/SimpleSingleton.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/SimpleSingleton.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/SimpleSingleton.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/SimpleSingleton.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/StaticClass.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/StaticClass.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/StaticClass.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/StaticClass.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-lang/README.md b/core-kotlin-modules/core-kotlin-lang/README.md new file mode 100644 index 0000000000..eaeae76854 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang/README.md @@ -0,0 +1,16 @@ +## Core Kotlin Lang + +This module contains articles about core features in the Kotlin language. + +### Relevant articles: +- [Guide to the “when{}” Block in Kotlin](https://www.baeldung.com/kotlin-when) +- [Difference Between “==” and “===” Operators in Kotlin](https://www.baeldung.com/kotlin-equality-operators) +- [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach) +- [Destructuring Declarations in Kotlin](https://www.baeldung.com/kotlin-destructuring-declarations) +- [Try-with-resources in Kotlin](https://www.baeldung.com/kotlin-try-with-resources) +- [Operator Overloading in Kotlin](https://www.baeldung.com/kotlin-operator-overloading) +- [Inline Functions in Kotlin](https://www.baeldung.com/kotlin-inline-functions) +- [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type) +- [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges) +- [Creating a Kotlin Range Iterator on a Custom Object](https://www.baeldung.com/kotlin-custom-range-iterator) +- [[More --> ]](/core-kotlin-modules/core-kotlin-lang-2) diff --git a/core-kotlin-modules/core-kotlin-lang/pom.xml b/core-kotlin-modules/core-kotlin-lang/pom.xml new file mode 100644 index 0000000000..d3ac7f690c --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + core-kotlin-lang + core-kotlin-lang + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt similarity index 94% rename from core-kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt index a5018d93c8..f845d01539 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt +++ b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt @@ -1,7 +1,5 @@ package com.baeldung.destructuringdeclarations -import com.baeldung.destructuringdeclarations.Person - fun main(args: Array) { //2.1. Objects diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/equalityoperators/User.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/equalityoperators/User.kt new file mode 100644 index 0000000000..030169bb8a --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/equalityoperators/User.kt @@ -0,0 +1,3 @@ +package com.baeldung.equalityoperators + +data class User(val name: String, val age: Int, val hobbies: List) diff --git a/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/forEach/forEach.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/forEach/forEach.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt similarity index 88% rename from core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt index 239c425c03..3b179642ba 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt +++ b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt @@ -1,4 +1,4 @@ -package com.baeldung.functions +package com.baeldung.inline import kotlin.random.Random diff --git a/core-kotlin/src/main/kotlin/com/baeldung/operators/Money.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Money.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/operators/Money.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Money.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/operators/Page.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Page.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/operators/Page.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Page.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/operators/Point.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Point.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/operators/Point.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Point.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/operators/Utils.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Utils.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/operators/Utils.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Utils.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/CharRange.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/CharRange.kt similarity index 100% rename from core-kotlin-2/src/main/kotlin/com/baeldung/range/CharRange.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/CharRange.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/Color.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Color.kt similarity index 100% rename from core-kotlin-2/src/main/kotlin/com/baeldung/range/Color.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Color.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/Filter.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Filter.kt similarity index 100% rename from core-kotlin-2/src/main/kotlin/com/baeldung/range/Filter.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Filter.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/FirstLast.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/FirstLast.kt similarity index 100% rename from core-kotlin-2/src/main/kotlin/com/baeldung/range/FirstLast.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/FirstLast.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/OtherRangeFunctions.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/OtherRangeFunctions.kt similarity index 100% rename from core-kotlin-2/src/main/kotlin/com/baeldung/range/OtherRangeFunctions.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/OtherRangeFunctions.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/Range.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Range.kt similarity index 100% rename from core-kotlin-2/src/main/kotlin/com/baeldung/range/Range.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Range.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/ReverseRange.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/ReverseRange.kt similarity index 100% rename from core-kotlin-2/src/main/kotlin/com/baeldung/range/ReverseRange.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/ReverseRange.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/Step.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Step.kt similarity index 100% rename from core-kotlin-2/src/main/kotlin/com/baeldung/range/Step.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Step.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/UntilRange.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/UntilRange.kt similarity index 100% rename from core-kotlin-2/src/main/kotlin/com/baeldung/range/UntilRange.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/UntilRange.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/CustomColor.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/rangeiterator/CustomColor.kt similarity index 84% rename from core-kotlin-2/src/main/kotlin/com/baeldung/range/CustomColor.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/rangeiterator/CustomColor.kt index b4fed13b18..c1ab8e1610 100644 --- a/core-kotlin-2/src/main/kotlin/com/baeldung/range/CustomColor.kt +++ b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/rangeiterator/CustomColor.kt @@ -1,4 +1,4 @@ -package com.baeldung.range +package com.baeldung.rangeiterator import java.lang.IllegalStateException @@ -8,7 +8,7 @@ class CustomColor(val rgb: Int): Comparable { return this.rgb.compareTo(other.rgb) } - operator fun rangeTo(that: CustomColor) = ColorRange(this,that) + operator fun rangeTo(that: CustomColor) = ColorRange(this, that) operator fun inc(): CustomColor { return CustomColor(rgb + 1) @@ -25,7 +25,7 @@ class CustomColor(val rgb: Int): Comparable { } } class ColorRange(override val start: CustomColor, - override val endInclusive: CustomColor) : ClosedRange, Iterable{ + override val endInclusive: CustomColor) : ClosedRange, Iterable{ override fun iterator(): Iterator { return ColorIterator(start, endInclusive) diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/WhenBlockTypes.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/whenblock/WhenBlockTypes.kt similarity index 95% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/WhenBlockTypes.kt rename to core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/whenblock/WhenBlockTypes.kt index 6180da10d9..a4cd7b98f0 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/WhenBlockTypes.kt +++ b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/whenblock/WhenBlockTypes.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.whenblock enum class UnixFileType { D, HYPHEN_MINUS, L diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/EqualityTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/equalityoperators/EqualityTest.kt similarity index 97% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/EqualityTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/equalityoperators/EqualityTest.kt index 6fb6d0a288..0728d55b73 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/EqualityTest.kt +++ b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/equalityoperators/EqualityTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.equalityoperators import org.junit.Test import kotlin.test.assertFalse diff --git a/core-kotlin/src/test/kotlin/com/baeldung/operators/PageTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/PageTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/operators/PageTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/PageTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/operators/PointTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/PointTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/operators/PointTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/PointTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/operators/UtilsTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/UtilsTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/operators/UtilsTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/UtilsTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/CharRangeTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/CharRangeTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/range/CharRangeTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/CharRangeTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/ColorTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/ColorTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/range/ColorTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/ColorTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/FilterTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/FilterTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/range/FilterTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/FilterTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/FirstLastTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/FirstLastTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/range/FirstLastTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/FirstLastTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/OtherRangeFunctionsTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/OtherRangeFunctionsTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/range/OtherRangeFunctionsTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/OtherRangeFunctionsTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/RangeTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/RangeTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/range/RangeTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/RangeTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/ReverseRangeTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/ReverseRangeTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/range/ReverseRangeTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/ReverseRangeTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/StepTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/StepTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/range/StepTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/StepTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/UntilRangeTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/UntilRangeTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/range/UntilRangeTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/UntilRangeTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/CustomColorTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/rangeiterator/CustomColorTest.kt similarity index 95% rename from core-kotlin-2/src/test/kotlin/com/baeldung/range/CustomColorTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/rangeiterator/CustomColorTest.kt index 8c8795ac42..676b47ae7a 100644 --- a/core-kotlin-2/src/test/kotlin/com/baeldung/range/CustomColorTest.kt +++ b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/rangeiterator/CustomColorTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.range +package com.baeldung.rangeiterator import org.junit.Test import java.lang.IllegalStateException diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/UseTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/trywithresource/UseTest.kt similarity index 98% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/UseTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/trywithresource/UseTest.kt index 15bdfcafd8..d17832b380 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/UseTest.kt +++ b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/trywithresource/UseTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.trywithresource import org.junit.Test import java.beans.ExceptionListener diff --git a/core-kotlin-2/src/test/kotlin/voidtypes/VoidTypesUnitTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/voidtypes/VoidTypesUnitTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/voidtypes/VoidTypesUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/voidtypes/VoidTypesUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/WhenBlockUnitTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/whenblock/WhenBlockUnitTest.kt similarity index 99% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/WhenBlockUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/whenblock/WhenBlockUnitTest.kt index aa1891fa46..31b6ad69f5 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/WhenBlockUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/whenblock/WhenBlockUnitTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.whenblock import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue diff --git a/core-kotlin-modules/core-kotlin/README.md b/core-kotlin-modules/core-kotlin/README.md new file mode 100644 index 0000000000..90caccf5c8 --- /dev/null +++ b/core-kotlin-modules/core-kotlin/README.md @@ -0,0 +1,19 @@ +## Core Kotlin + +This module contains articles about Kotlin core features. + +### Relevant articles: +- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin-intro) +- [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability) +- [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number) +- [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project) +- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort) +- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern) +- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions) +- [Implementing a Binary Tree in Kotlin](https://www.baeldung.com/kotlin-binary-tree) +- [JUnit 5 for Kotlin Developers](https://www.baeldung.com/junit-5-kotlin) +- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class) +- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel) +- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant) +- [Dependency Injection for Kotlin with Injekt](https://www.baeldung.com/kotlin-dependency-injection-with-injekt) +- [[More --> ]](/core-kotlin-modules/core-kotlin-2) diff --git a/core-kotlin-modules/core-kotlin/pom.xml b/core-kotlin-modules/core-kotlin/pom.xml new file mode 100644 index 0000000000..6e36b7c8ef --- /dev/null +++ b/core-kotlin-modules/core-kotlin/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + core-kotlin + core-kotlin + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + 1.1.1 + + + \ No newline at end of file diff --git a/core-kotlin/src/main/java/com/baeldung/java/ArrayExample.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/ArrayExample.java similarity index 91% rename from core-kotlin/src/main/java/com/baeldung/java/ArrayExample.java rename to core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/ArrayExample.java index ef91db517b..93b9a3984a 100644 --- a/core-kotlin/src/main/java/com/baeldung/java/ArrayExample.java +++ b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/ArrayExample.java @@ -1,4 +1,4 @@ -package com.baeldung.java; +package com.baeldung.interoperability; import java.io.File; import java.io.FileReader; diff --git a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/Customer.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/Customer.java new file mode 100644 index 0000000000..4a070a0f97 --- /dev/null +++ b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/Customer.java @@ -0,0 +1,24 @@ +package com.baeldung.interoperability; + +public class Customer { + + private String firstName; + private String lastName; + + 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; + } + +} diff --git a/core-kotlin/src/main/java/com/baeldung/java/StringUtils.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/introduction/StringUtils.java similarity index 77% rename from core-kotlin/src/main/java/com/baeldung/java/StringUtils.java rename to core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/introduction/StringUtils.java index f405924cdf..1c477ce039 100644 --- a/core-kotlin/src/main/java/com/baeldung/java/StringUtils.java +++ b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/introduction/StringUtils.java @@ -1,4 +1,4 @@ -package com.baeldung.java; +package com.baeldung.introduction; public class StringUtils { public static String toUpperCase(String name) { diff --git a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java new file mode 100644 index 0000000000..ac933d6228 --- /dev/null +++ b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java @@ -0,0 +1,25 @@ +package com.baeldung.mavenjavakotlin; + +import com.baeldung.mavenjavakotlin.services.JavaService; + +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-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java similarity index 100% rename from core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java rename to core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Main.kt similarity index 93% rename from core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Main.kt index 4fd8aa27c7..eee10fbd8b 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Main.kt @@ -1,4 +1,4 @@ -package com.baeldung.datastructures +package com.baeldung.binarytree /** * Example of how to use the {@link Node} class. diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Node.kt similarity index 99% rename from core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Node.kt index b81afe1e4c..77bb98f828 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Node.kt @@ -1,4 +1,4 @@ -package com.baeldung.datastructures +package com.baeldung.binarytree /** * An ADT for a binary search tree. diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Example1.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Example1.kt new file mode 100644 index 0000000000..aacd8f7915 --- /dev/null +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Example1.kt @@ -0,0 +1,5 @@ +package com.baeldung.introduction + +fun main(args: Array){ + println("hello word") +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/Item.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Item.kt similarity index 89% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/Item.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Item.kt index 36994e4994..bb91dd1eae 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/Item.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Item.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.introduction open class Item(val id: String, val name: String = "unknown_name") { open fun getIdOfItem(): String { diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/ItemService.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ItemService.kt similarity index 98% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/ItemService.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ItemService.kt index 88de1aa9be..dfcf17df7c 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/ItemService.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ItemService.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.introduction import java.util.* diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ListExtension.kt similarity index 89% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ListExtension.kt index da1773b7c9..e71292c60a 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ListExtension.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.introduction import java.util.concurrent.ThreadLocalRandom diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/MathematicsOperations.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/MathematicsOperations.kt new file mode 100644 index 0000000000..0ed30ed5b4 --- /dev/null +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/MathematicsOperations.kt @@ -0,0 +1,7 @@ +package com.baeldung.introduction + +class MathematicsOperations { + fun addTwoNumbers(a: Int, b: Int): Int { + return a + b + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/KotlinService.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/KotlinService.kt new file mode 100644 index 0000000000..10d6a792d8 --- /dev/null +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/KotlinService.kt @@ -0,0 +1,9 @@ +package com.baeldung.mavenjavakotlin + +class KotlinService { + + fun sayHello() { + System.out.println("Kotlin says 'Hello World!'") + } + +} \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt similarity index 100% rename from core-kotlin-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt similarity index 97% rename from core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt index 2309d23c36..bf3163bc8f 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt @@ -1,7 +1,5 @@ package com.baeldung.sorting -import kotlin.comparisons.* - fun sortMethodUsage() { val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6) sortedValues.sort() diff --git a/core-kotlin/src/test/java/com/baeldung/kotlin/JavaCallToKotlinUnitTest.java b/core-kotlin-modules/core-kotlin/src/test/java/com/baeldung/introduction/JavaCallToKotlinUnitTest.java similarity index 90% rename from core-kotlin/src/test/java/com/baeldung/kotlin/JavaCallToKotlinUnitTest.java rename to core-kotlin-modules/core-kotlin/src/test/java/com/baeldung/introduction/JavaCallToKotlinUnitTest.java index 370f24785a..2c386eaad3 100644 --- a/core-kotlin/src/test/java/com/baeldung/kotlin/JavaCallToKotlinUnitTest.java +++ b/core-kotlin-modules/core-kotlin/src/test/java/com/baeldung/introduction/JavaCallToKotlinUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.kotlin; +package com.baeldung.introduction; import org.junit.Test; diff --git a/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/binarytree/NodeTest.kt similarity index 98% rename from core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/binarytree/NodeTest.kt index 8a46c5f6ec..9414d7dde9 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/binarytree/NodeTest.kt @@ -1,7 +1,8 @@ -package com.baeldung.datastructures +package com.baeldung.binarytree import org.junit.After -import org.junit.Assert.* +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test diff --git a/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt similarity index 87% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt index bdf44d3b49..9159be96be 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.gson +package com.baeldung.gson import com.google.gson.Gson @@ -11,7 +11,7 @@ class GsonUnitTest { @Test fun givenObject_thenGetJSONString() { - var jsonString = gson.toJson(TestModel(1,"Test")) + var jsonString = gson.toJson(TestModel(1, "Test")) Assert.assertEquals(jsonString, "{\"id\":1,\"description\":\"Test\"}") } diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/ArrayTest.kt similarity index 81% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/ArrayTest.kt index f7d1c53b13..8e9467f92a 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/ArrayTest.kt @@ -1,7 +1,5 @@ -package com.baeldung.kotlin +package com.baeldung.interoperability -import com.baeldung.java.ArrayExample -import com.baeldung.java.Customer import org.junit.Test import kotlin.test.assertEquals @@ -29,7 +27,7 @@ class ArrayTest { val constructors = instance.constructors assertEquals(constructors.size, 1) - assertEquals(constructors[0].name, "com.baeldung.java.Customer") + assertEquals(constructors[0].name, "com.baeldung.interoperability.Customer") } fun makeReadFile() { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CustomerTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/CustomerTest.kt similarity index 88% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/CustomerTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/CustomerTest.kt index 6395dfcfed..c1b09cd0c1 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CustomerTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/CustomerTest.kt @@ -1,6 +1,5 @@ -package com.baeldung.kotlin +package com.baeldung.interoperability -import com.baeldung.java.Customer import org.junit.Test import kotlin.test.assertEquals diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ItemServiceTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ItemServiceTest.kt similarity index 92% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/ItemServiceTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ItemServiceTest.kt index 3d730b1283..2ba14a7462 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ItemServiceTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ItemServiceTest.kt @@ -1,9 +1,10 @@ -package com.baeldung.kotlin +package com.baeldung.introduction import org.junit.Test import kotlin.test.assertNotNull class ItemServiceTest { + @Test fun givenItemId_whenGetForOptionalItem_shouldMakeActionOnNonNullValue() { //given diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KotlinJavaInteroperabilityTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/KotlinJavaInteroperabilityTest.kt similarity index 84% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/KotlinJavaInteroperabilityTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/KotlinJavaInteroperabilityTest.kt index 91ccaabf6f..5dddf9bfc9 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KotlinJavaInteroperabilityTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/KotlinJavaInteroperabilityTest.kt @@ -1,6 +1,5 @@ -package com.baeldung.kotlin +package com.baeldung.introduction -import com.baeldung.java.StringUtils import org.junit.Test import kotlin.test.assertEquals diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/LambdaTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/LambdaTest.kt new file mode 100644 index 0000000000..5e5166074e --- /dev/null +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/LambdaTest.kt @@ -0,0 +1,20 @@ +package com.baeldung.introduction + +import org.junit.Test +import kotlin.test.assertEquals + + +class LambdaTest { + + @Test + fun givenListOfNumber_whenDoingOperationsUsingLambda_shouldReturnProperResult() { + //given + val listOfNumbers = listOf(1, 2, 3) + + //when + val sum = listOfNumbers.reduce { a, b -> a + b } + + //then + assertEquals(6, sum) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ListExtensionTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ListExtensionTest.kt similarity index 79% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/ListExtensionTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ListExtensionTest.kt index 7a496e7437..38f244297b 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ListExtensionTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ListExtensionTest.kt @@ -1,12 +1,12 @@ -package com.baeldung.kotlin +package com.baeldung.introduction -import com.baeldung.kotlin.ListExtension import org.junit.Test import kotlin.test.assertTrue class ListExtensionTest { + @Test - fun givenList_whenExecuteExtensionFunctionOnList_shouldReturnRandomElementOfList(){ + fun givenList_whenExecuteExtensionFunctionOnList_shouldReturnRandomElementOfList() { //given val elements = listOf("a", "b", "c") diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/Calculator.kt similarity index 91% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/Calculator.kt index 1b61c05887..9f6e3ab2b9 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/Calculator.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.junit5 +package com.baeldung.junit5 class Calculator { fun add(a: Int, b: Int) = a + b diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt new file mode 100644 index 0000000000..07cab3b76e --- /dev/null +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt @@ -0,0 +1,82 @@ +package com.baeldung.junit5 + +import org.junit.jupiter.api.* +import org.junit.jupiter.api.function.Executable + +class CalculatorUnitTest { + private val calculator = Calculator() + + @Test + fun `Adding 1 and 3 should be equal to 4`() { + Assertions.assertEquals(4, calculator.add(1, 3)) + } + + @Test + fun `Dividing by zero should throw the DivideByZeroException`() { + val exception = Assertions.assertThrows(DivideByZeroException::class.java) { + calculator.divide(5, 0) + } + + Assertions.assertEquals(5, exception.numerator) + } + + @Test + fun `The square of a number should be equal to that number multiplied in itself`() { + Assertions.assertAll( + Executable { Assertions.assertEquals(1, calculator.square(1)) }, + Executable { Assertions.assertEquals(4, calculator.square(2)) }, + Executable { Assertions.assertEquals(9, calculator.square(3)) } + ) + } + + @TestFactory + fun testSquaresFactory() = listOf( + DynamicTest.dynamicTest("when I calculate 1^2 then I get 1") { Assertions.assertEquals(1,calculator.square(1))}, + DynamicTest.dynamicTest("when I calculate 2^2 then I get 4") { Assertions.assertEquals(4,calculator.square(2))}, + DynamicTest.dynamicTest("when I calculate 3^2 then I get 9") { Assertions.assertEquals(9,calculator.square(3))} + ) + + @TestFactory + fun testSquaresFactory2() = listOf( + 1 to 1, + 2 to 4, + 3 to 9, + 4 to 16, + 5 to 25) + .map { (input, expected) -> + DynamicTest.dynamicTest("when I calculate $input^2 then I get $expected") { + Assertions.assertEquals(expected, calculator.square(input)) + } + } + + private val squaresTestData = listOf( + 1 to 1, + 2 to 4, + 3 to 9, + 4 to 16, + 5 to 25) + + @TestFactory + fun testSquaresFactory3() = squaresTestData + .map { (input, expected) -> + DynamicTest.dynamicTest("when I calculate $input^2 then I get $expected") { + Assertions.assertEquals(expected, calculator.square(input)) + } + } + @TestFactory + fun testSquareRootsFactory3() = squaresTestData + .map { (expected, input) -> + DynamicTest.dynamicTest("I calculate the square root of $input then I get $expected") { + Assertions.assertEquals(expected.toDouble(), calculator.squareRoot(input)) + } + } + + @Tags( + Tag("slow"), + Tag("logarithms") + ) + @Test + fun `Log to base 2 of 8 should be equal to 3`() { + Assertions.assertEquals(3.0, calculator.log(2, 8)) + } +} diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt new file mode 100644 index 0000000000..5675367fd5 --- /dev/null +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt @@ -0,0 +1,3 @@ +package com.baeldung.junit5 + +class DivideByZeroException(val numerator: Int) : Exception() diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt new file mode 100644 index 0000000000..e3fe998efd --- /dev/null +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt @@ -0,0 +1,22 @@ +package com.baeldung.junit5 + +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test + +class SimpleUnitTest { + + @Test + fun `isEmpty should return true for empty lists`() { + val list = listOf() + Assertions.assertTrue(list::isEmpty) + } + + @Test + @Disabled + fun `3 is equal to 4`() { + Assertions.assertEquals(3, 4) { + "Three does not equal four" + } + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt similarity index 86% rename from core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt index 8a94e29c2f..7ac0efa4ef 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt @@ -1,9 +1,8 @@ package com.baeldung.sorting +import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.junit.jupiter.api.Assertions.* - class SortingExampleKtTest { @Test diff --git a/core-kotlin-modules/pom.xml b/core-kotlin-modules/pom.xml index 747e8b69de..de41aecf73 100644 --- a/core-kotlin-modules/pom.xml +++ b/core-kotlin-modules/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.core-kotlin-modules core-kotlin-modules @@ -15,9 +17,18 @@ + core-kotlin + core-kotlin-2 + core-kotlin-advanced core-kotlin-annotations + core-kotlin-collections + core-kotlin-concurrency core-kotlin-io + core-kotlin-lang + core-kotlin-lang-2 core-kotlin-strings + core-kotlin-lang-oop + core-kotlin-lang-oop-2 diff --git a/core-kotlin/.gitignore b/core-kotlin/.gitignore deleted file mode 100644 index 0c017e8f8c..0000000000 --- a/core-kotlin/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -/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 deleted file mode 100644 index f75a4e764c..0000000000 --- a/core-kotlin/README.md +++ /dev/null @@ -1,57 +0,0 @@ -## Core Kotlin - -This module contains articles about core Kotlin. - -### Relevant articles: - -- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin) -- [Guide to the “when{}” Block in Kotlin](https://www.baeldung.com/kotlin-when) -- [Comprehensive Guide to Null Safety in Kotlin](https://www.baeldung.com/kotlin-null-safety) -- [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability) -- [Difference Between “==” and “===” operators in Kotlin](https://www.baeldung.com/kotlin-equality-operators) -- [Generics in Kotlin](https://www.baeldung.com/kotlin-generics) -- [Introduction to Kotlin Coroutines](https://www.baeldung.com/kotlin-coroutines) -- [Destructuring Declarations in Kotlin](https://www.baeldung.com/kotlin-destructuring-declarations) -- [Lazy Initialization in Kotlin](https://www.baeldung.com/kotlin-lazy-initialization) -- [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api) -- [Converting a List to Map in Kotlin](https://www.baeldung.com/kotlin-list-to-map) -- [Data Classes in Kotlin](https://www.baeldung.com/kotlin-data-classes) -- [Delegated Properties in Kotlin](https://www.baeldung.com/kotlin-delegated-properties) -- [Sealed Classes in Kotlin](https://www.baeldung.com/kotlin-sealed-classes) -- [JUnit 5 for Kotlin Developers](https://www.baeldung.com/junit-5-kotlin) -- [Extension Methods in Kotlin](https://www.baeldung.com/kotlin-extension-methods) -- [Infix Functions in Kotlin](https://www.baeldung.com/kotlin-infix-functions) -- [Try-with-resources in Kotlin](https://www.baeldung.com/kotlin-try-with-resources) -- [Regular Expressions in Kotlin](https://www.baeldung.com/kotlin-regular-expressions) -- [Objects in Kotlin](https://www.baeldung.com/kotlin-objects) -- [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection) -- [Lambda Expressions in Kotlin](https://www.baeldung.com/kotlin-lambda-expressions) -- [Working with Enums in Kotlin](https://www.baeldung.com/kotlin-enum) -- [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project) -- [Reflection with Kotlin](https://www.baeldung.com/kotlin-reflection) -- [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number) -- [Idiomatic Logging in Kotlin](https://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) -- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel) -- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant) -- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class) -- [Kotlin return, break, continue Keywords](https://www.baeldung.com/kotlin-return-break-continue) -- [Mapping of Data Objects in Kotlin](https://www.baeldung.com/kotlin-data-objects) -- [Initializing Arrays in Kotlin](https://www.baeldung.com/kotlin-initialize-array) -- [Threads vs Coroutines in Kotlin](https://www.baeldung.com/kotlin-threads-coroutines) -- [Guide to Kotlin Interfaces](https://www.baeldung.com/kotlin-interfaces) -- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort) -- [Dependency Injection for Kotlin with Injekt](https://www.baeldung.com/kotlin-dependency-injection-with-injekt) -- [Implementing a Binary Tree in Kotlin](https://www.baeldung.com/kotlin-binary-tree) -- [Kotlin Contracts](https://www.baeldung.com/kotlin-contracts) -- [Operator Overloading in Kotlin](https://www.baeldung.com/kotlin-operator-overloading) -- [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes) -- [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final) -- [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach) -- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl) -- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods) -- [Inline Functions in Kotlin](https://www.baeldung.com/kotlin-inline-functions) -- [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern) -- More articles: [[next -->]](/core-kotlin-2) diff --git a/core-kotlin/build.gradle b/core-kotlin/build.gradle deleted file mode 100755 index 2b6527fca7..0000000000 --- a/core-kotlin/build.gradle +++ /dev/null @@ -1,48 +0,0 @@ - - -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 deleted file mode 100755 index 01b8bf6b1f..0000000000 Binary files a/core-kotlin/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/core-kotlin/gradle/wrapper/gradle-wrapper.properties b/core-kotlin/gradle/wrapper/gradle-wrapper.properties deleted file mode 100755 index 0b83b5a3e3..0000000000 --- a/core-kotlin/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100755 index cccdd3d517..0000000000 --- a/core-kotlin/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/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 deleted file mode 100755 index e95643d6a2..0000000000 --- a/core-kotlin/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@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 deleted file mode 100644 index 63a6d8035e..0000000000 --- a/core-kotlin/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - 4.0.0 - core-kotlin - core-kotlin - jar - - - com.baeldung - parent-kotlin - 1.0.0-SNAPSHOT - ../parent-kotlin - - - - - org.apache.commons - commons-math3 - ${commons-math3.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - com.h2database - h2 - ${h2.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 - ${kovenant.version} - pom - - - uy.kohesive.injekt - injekt-core - ${injekt-core.version} - - - - - 3.6.1 - 1.1.1 - 5.2.0 - 3.10.0 - 1.15.0 - 3.3.0 - 1.16.1 - - - diff --git a/core-kotlin/resources/logback.xml b/core-kotlin/resources/logback.xml deleted file mode 100755 index 274cdcdb02..0000000000 --- a/core-kotlin/resources/logback.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - %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 deleted file mode 100755 index 13bbce9583..0000000000 --- a/core-kotlin/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ -rootProject.name = 'KtorWithKotlin' - diff --git a/core-kotlin/src/main/java/com/baeldung/java/Customer.java b/core-kotlin/src/main/java/com/baeldung/java/Customer.java deleted file mode 100644 index 0156bf7b44..0000000000 --- a/core-kotlin/src/main/java/com/baeldung/java/Customer.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.java; - -public class Customer { - - private String firstName; - private String lastName; - - 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; - } - -} diff --git a/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java b/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java deleted file mode 100644 index e2cc0f1e01..0000000000 --- a/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java +++ /dev/null @@ -1,26 +0,0 @@ -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/kotlin/com/baeldung/kotlin/Example1.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/Example1.kt deleted file mode 100644 index bca1e54a6c..0000000000 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/Example1.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.kotlin - -fun main(args: Array){ - println("hello word") -} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/MathematicsOperations.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/MathematicsOperations.kt deleted file mode 100644 index 924f9d2323..0000000000 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/MathematicsOperations.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.kotlin - -class MathematicsOperations { - fun addTwoNumbers(a: Int, b: Int): Int { - return a + b - } -} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/User.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/User.kt deleted file mode 100644 index 759627b56e..0000000000 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/User.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.kotlin - -data class User(val name: String, val age: Int, val hobbies: List) 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 deleted file mode 100644 index 114b1c88df..0000000000 --- a/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/services/KotlinService.kt +++ /dev/null @@ -1,9 +0,0 @@ -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/thread/SimpleRunnable.kt b/core-kotlin/src/main/kotlin/com/baeldung/thread/SimpleRunnable.kt deleted file mode 100644 index 7bc0528d06..0000000000 --- a/core-kotlin/src/main/kotlin/com/baeldung/thread/SimpleRunnable.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.thread - -class SimpleRunnable: Runnable { - - override fun run() { - println("${Thread.currentThread()} has run.") - } -} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/thread/SimpleThread.kt b/core-kotlin/src/main/kotlin/com/baeldung/thread/SimpleThread.kt deleted file mode 100644 index 2b2827ae02..0000000000 --- a/core-kotlin/src/main/kotlin/com/baeldung/thread/SimpleThread.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.thread - -class SimpleThread: Thread() { - - override fun run() { - println("${Thread.currentThread()} has run.") - } -} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt deleted file mode 100644 index b7993c5f43..0000000000 --- a/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt +++ /dev/null @@ -1,276 +0,0 @@ -package com.baeldung.fuel - -import com.github.kittinunf.fuel.Fuel -import com.github.kittinunf.fuel.core.FuelManager -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 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() - - } - - -// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library -// @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 -> }) -// } - -// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library -// @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/LambdaTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LambdaTest.kt deleted file mode 100644 index 34217336a0..0000000000 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LambdaTest.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.kotlin - -import org.junit.Test -import kotlin.test.assertEquals - - -class LambdaTest { - @Test - fun givenListOfNumber_whenDoingOperationsUsingLambda_shouldReturnProperResult() { - //given - val listOfNumbers = listOf(1, 2, 3) - - //when - val sum = listOfNumbers.reduce { a, b -> a + b } - - //then - assertEquals(6, sum) - } -} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/TestKotlinConstantClass.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/TestKotlinConstantClass.kt deleted file mode 100644 index 8bcc327999..0000000000 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/TestKotlinConstantClass.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.kotlin.constant - - -class TestKotlinConstantClass { - companion object { - const val COMPANION_OBJECT_NUMBER = 40 - } -} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt deleted file mode 100644 index daaedca5a3..0000000000 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.kotlin.junit5 - -import org.junit.jupiter.api.* -import org.junit.jupiter.api.function.Executable - -class CalculatorTest5 { - private val calculator = Calculator() - - @Test - fun `Adding 1 and 3 should be equal to 4`() { - Assertions.assertEquals(4, calculator.add(1, 3)) - } - - @Test - fun `Dividing by zero should throw the DivideByZeroException`() { - val exception = Assertions.assertThrows(DivideByZeroException::class.java) { - calculator.divide(5, 0) - } - - Assertions.assertEquals(5, exception.numerator) - } - - @Test - fun `The square of a number should be equal to that number multiplied in itself`() { - Assertions.assertAll( - Executable { Assertions.assertEquals(1, calculator.square(1)) }, - Executable { Assertions.assertEquals(4, calculator.square(2)) }, - Executable { Assertions.assertEquals(9, calculator.square(3)) } - ) - } - - @TestFactory - fun testSquaresFactory() = listOf( - DynamicTest.dynamicTest("when I calculate 1^2 then I get 1") { Assertions.assertEquals(1,calculator.square(1))}, - DynamicTest.dynamicTest("when I calculate 2^2 then I get 4") { Assertions.assertEquals(4,calculator.square(2))}, - DynamicTest.dynamicTest("when I calculate 3^2 then I get 9") { Assertions.assertEquals(9,calculator.square(3))} - ) - - @TestFactory - fun testSquaresFactory2() = listOf( - 1 to 1, - 2 to 4, - 3 to 9, - 4 to 16, - 5 to 25) - .map { (input, expected) -> - DynamicTest.dynamicTest("when I calculate $input^2 then I get $expected") { - Assertions.assertEquals(expected, calculator.square(input)) - } - } - - private val squaresTestData = listOf( - 1 to 1, - 2 to 4, - 3 to 9, - 4 to 16, - 5 to 25) - - @TestFactory - fun testSquaresFactory3() = squaresTestData - .map { (input, expected) -> - DynamicTest.dynamicTest("when I calculate $input^2 then I get $expected") { - Assertions.assertEquals(expected, calculator.square(input)) - } - } - @TestFactory - fun testSquareRootsFactory3() = squaresTestData - .map { (expected, input) -> - DynamicTest.dynamicTest("I calculate the square root of $input then I get $expected") { - Assertions.assertEquals(expected.toDouble(), calculator.squareRoot(input)) - } - } - - @Tags( - Tag("slow"), - Tag("logarithms") - ) - @Test - fun `Log to base 2 of 8 should be equal to 3`() { - Assertions.assertEquals(3.0, calculator.log(2, 8)) - } -} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt deleted file mode 100644 index 60bc4e2944..0000000000 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.kotlin.junit5 - -class DivideByZeroException(val numerator: Int) : Exception() diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt deleted file mode 100644 index 15ff201430..0000000000 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.kotlin.junit5 - -import org.junit.jupiter.api.Assertions -import org.junit.jupiter.api.Disabled -import org.junit.jupiter.api.Test - -class SimpleTest5 { - - @Test - fun `isEmpty should return true for empty lists`() { - val list = listOf() - Assertions.assertTrue(list::isEmpty) - } - - @Test - @Disabled - fun `3 is equal to 4`() { - Assertions.assertEquals(3, 4) { - "Three does not equal four" - } - } -} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt deleted file mode 100644 index 3af00c98ff..0000000000 --- a/core-kotlin/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.lambda - -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -class LambdaTest { - @Test - fun whenCallingALambda_thenPerformTheAction() { - assertEquals(9, inferredType(3)) - } - - @Test - fun whenCallingAMoreComplicatedLambda_thenPerformTheAction() { - assertEquals("500", intToBiggerString(5)) - } - - @Test - fun whenPassingALambdaObject_thenCallTriggerLambda() { - val lambda = { arg: Double -> - arg == 4.329 - } - - val result = invokeLambda(lambda) - - assertTrue(result) - } - - @Test - fun whenPassingALambdaLiteral_thenCallTriggerLambda() { - val result = invokeLambda({ - true - }) - - assertTrue(result) - } - - @Test - fun whenPassingALambdaLiteralOutsideBrackets_thenCallTriggerLambda() { - val result = invokeLambda { arg -> arg.isNaN() } - - assertFalse(result) - } - - @Test - fun whenPassingAnAnonymousFunction_thenCallTriggerLambda() { - val result = invokeLambda(fun(arg: Double): Boolean { - return arg >= 0 - }) - - assertTrue(result) - } - - @Test - fun whenUsingLambda_thenCalculateGrade() { - val gradeCalculation = getCalculationLambda() - - assertEquals(false, gradeCalculation(-40)) - assertEquals("Pass", gradeCalculation(50)) - } - - @Test - fun whenUsingReturnStatementLambda_thenCalculateGrade() { - val gradeCalculation: Int.() -> String = getCalculationLambdaWithReturn() - - assertEquals("Distinction", 80.gradeCalculation()) - assertEquals("Error", 244_234_324.gradeCalculation()) - } - - @Test - fun whenUsingAnonymousFunction_thenCalculateGrade() { - val gradeCalculation = getCalculationAnonymousFunction() - - assertEquals("Error", gradeCalculation(244_234_324)) - assertEquals("Pass", gradeCalculation(50)) - } - - @Test - fun whenPassingAFunctionReference_thenCallTriggerLambda() { - val reference = Double::isFinite - val result = invokeLambda(reference) - - assertTrue(result) - } - - @Test - fun givenArray_whenMappingArray_thenPerformCalculationOnAllElements() { - val expected = listOf("100", "200", "300", "400", "500") - val actual = manyLambda(arrayOf(1, 2, 3, 4, 5)) - - assertEquals(expected, actual) - } - -} \ No newline at end of file diff --git a/core-scala/README.md b/core-scala/README.md index e6fc75d59e..72b583c22b 100644 --- a/core-scala/README.md +++ b/core-scala/README.md @@ -1,7 +1,3 @@ -## Core Scala +### Relevant Articles: -This module contains articles about Scala's core features - -### Relevant Articles: - -- [Introduction to Scala](https://www.baeldung.com/scala-intro) +- [Pattern Matching in Scala](https://www.baeldung.com/scala/pattern-matching) diff --git a/core-scala/pom.xml b/core-scala/pom.xml index d6793cf4c6..8277b0f856 100644 --- a/core-scala/pom.xml +++ b/core-scala/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-scala 1.0-SNAPSHOT @@ -28,7 +30,7 @@ net.alchim31.maven scala-maven-plugin - 3.3.2 + ${scala.plugin.version} @@ -49,6 +51,7 @@ 2.12.7 + 3.3.2 - + diff --git a/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala b/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala deleted file mode 100644 index 7c1281e573..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.scala - -/** - * Sample code demonstrating the various control structured. - * - * @author Chandra Prakash - * - */ -object ControlStructuresDemo { - def gcd(x : Int, y : Int) : Int = { - if (y == 0) x else gcd(y, x % y) - } - - def gcdIter(x : Int, y : Int) : Int = { - var a = x - var b = y - while (b > 0) { - a = a % b - val t = a - a = b - b = t - } - a - } - - def rangeSum(a : Int, b : Int) = { - var sum = 0; - for (i <- a to b) { - sum += i - } - sum - } - - def factorial(a : Int) : Int = { - var result = 1; - var i = 1; - do { - result *= i - i = i + 1 - } while (i <= a) - result - } - -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/Employee.scala b/core-scala/src/main/scala/com/baeldung/scala/Employee.scala deleted file mode 100644 index 9291d958b3..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/Employee.scala +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.scala - -/** - * Sample Code demonstrating a class. - * - * @author Chandra Prakash - * - */ -class Employee(val name : String, - var salary : Int, - annualIncrement : Int = 20) { - - def incrementSalary() : Unit = { - salary += annualIncrement - } - - override def toString = - s"Employee(name=$name, salary=$salary)" -} - -/** - * A Trait which will make the toString return upper case value. - */ -trait UpperCasePrinter { - override def toString: String = super.toString toUpperCase -} - diff --git a/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala b/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala deleted file mode 100644 index b3f0ce09a5..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.scala - -object HelloWorld extends App { - println("Hello World!") - args foreach println -} diff --git a/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala b/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala deleted file mode 100644 index 02c41a5f8c..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.scala - -/** - * Sample higher order functions. - * - * @author Chandra Prakash - * - */ -object HigherOrderFunctions { - - def mapReduce(r : (Int, Int) => Int, - i : Int, - m : Int => Int, - a : Int, b : Int): Int = { - def iter(a : Int, result : Int) : Int = { - if (a > b) result - else iter(a + 1, r(m(a), result)) - } - iter(a, i) - } - - def whileLoop(condition : => Boolean)(body : => Unit) : Unit = - if (condition) { - body - whileLoop(condition)(body) - } -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala b/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala deleted file mode 100644 index f1a5722a4e..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.scala - -/** - * An abstract class for set of integers and its implementation. - * - * @author Chandra Prakash - * - */ -abstract class IntSet { - // add an element to the set - def incl(x : Int) : IntSet - - // whether an element belongs to the set - def contains(x : Int) : Boolean -} - -class EmptyIntSet extends IntSet { - - def contains(x : Int) : Boolean = false - - def incl(x : Int) = - new NonEmptyIntSet(x, this) -} - -class NonEmptyIntSet(val head : Int, val tail : IntSet) - extends IntSet { - - def contains(x : Int) : Boolean = - head == x || (tail contains x) - - def incl(x : Int) : IntSet = - if (this contains x) this - else new NonEmptyIntSet(x, this) -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/PatternMatching.scala b/core-scala/src/main/scala/com/baeldung/scala/PatternMatching.scala deleted file mode 100644 index 71458237d6..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/PatternMatching.scala +++ /dev/null @@ -1,137 +0,0 @@ -package com.baeldung.scala - -// Case Class -abstract class Animal - -case class Mammal(name: String, fromSea: Boolean) extends Animal - -case class Bird(name: String) extends Animal - -case class Fish(name: String) extends Animal - -// Sealed Class -sealed abstract class CardSuit - -case class Spike() extends CardSuit - -case class Diamond() extends CardSuit - -case class Heart() extends CardSuit - -case class Club() extends CardSuit - -object Person { - def apply(fullName: String) = fullName - - def unapply(fullName: String): Option[String] = { - if (!fullName.isEmpty) - Some(fullName.replaceAll("(?<=\\w)(\\w+)", ".")) - else - None - } -} - -class PatternMatching { - - def caseClassesPatternMatching(animal: Animal): String = { - animal match { - case Mammal(name, fromSea) => s"I'm a $name, a kind of mammal. Am I from the sea? $fromSea" - case Bird(name) => s"I'm a $name, a kind of bird" - case _ => "I'm an unknown animal" - } - } - - def constantsPatternMatching(constant: Any): String = { - constant match { - case 0 => "I'm equal to zero" - case 4.5d => "I'm a double" - case false => "I'm the contrary of true" - case _ => s"I'm unknown and equal to $constant" - } - } - - def sequencesPatternMatching(sequence: Any): String = { - sequence match { - case List(singleElement) => s"I'm a list with one element: $singleElement" - case List(_, _*) => s"I'm a list with one or multiple elements: $sequence" - case Vector(1, 2, _*) => s"I'm a vector: $sequence" - case _ => s"I'm an unrecognized sequence. My value: $sequence" - } - } - - def tuplesPatternMatching(tuple: Any): String = { - tuple match { - case (first, second) => s"I'm a tuple with two elements: $first & $second" - case (first, second, third) => s"I'm a tuple with three elements: $first & $second & $third" - case _ => s"Unrecognized pattern. My value: $tuple" - } - } - - def typedPatternMatching(any: Any): String = { - any match { - case string: String => s"I'm a string. My value: $string" - case integer: Int => s"I'm an integer. My value: $integer" - case _ => s"I'm from an unknown type. My value: $any" - } - } - - def regexPatterns(toMatch: String): String = { - val numeric = """([0-9]+)""".r - val alphabetic = """([a-zA-Z]+)""".r - val alphanumeric = """([a-zA-Z0-9]+)""".r - - toMatch match { - case numeric(value) => s"I'm a numeric with value $value" - case alphabetic(value) => s"I'm an alphabetic with value $value" - case alphanumeric(value) => s"I'm an alphanumeric with value $value" - case _ => s"I contain other characters than alphanumerics. My value $toMatch" - } - } - - def optionsPatternMatching(option: Option[String]): String = { - option match { - case Some(value) => s"I'm not an empty option. Value $value" - case None => "I'm an empty option" - } - } - - def patternGuards(toMatch: Any, maxLength: Int): String = { - toMatch match { - case list: List[Any] if (list.size <= maxLength) => "List is of acceptable size" - case list: List[Any] => "List has not an acceptable size" - case string: String if (string.length <= maxLength) => "String is of acceptable size" - case string: String => "String has not an acceptable size" - case _ => "Input is neither a List or a String" - } - } - - def sealedClass(cardSuit: CardSuit): String = { - cardSuit match { - case Spike() => "Card is spike" - case Club() => "Card is club" - case Heart() => "Card is heart" - case Diamond() => "Card is diamond" - } - } - - def extractors(person: Any): String = { - person match { - case Person(initials) => s"My initials are $initials" - case _ => "Could not extract initials" - } - } - - def closuresPatternMatching(list: List[Any]): List[Any] = { - list.collect { case i: Int if (i < 10) => i } - } - - def catchBlocksPatternMatching(exception: Exception): String = { - try { - throw exception - } catch { - case ex: IllegalArgumentException => "It's an IllegalArgumentException" - case ex: RuntimeException => "It's a RuntimeException" - case _ => "It's an unknown kind of exception" - } - } -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/Utils.scala b/core-scala/src/main/scala/com/baeldung/scala/Utils.scala deleted file mode 100644 index 20bc413646..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/Utils.scala +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.scala - -/** - * Some utility methods. - * - * @author Chandra Prakash - * - */ -object Utils { - def average(x : Double, y : Double): Double = (x + y) / 2 - - def randomLessThan(d : Double): Double = { - var random = 0d - do { - random = Math.random() - } while (random >= d) - random - } - - def power(x : Int, y : Int) : Int = { - def powNested(i : Int, accumulator : Int) : Int = { - if (i <= 0) accumulator - else powNested(i - 1, x * accumulator) - } - powNested(y, 1) - } - - def fibonacci(n : Int) : Int = n match { - case 0 | 1 => 1 - case x if x > 1 => - fibonacci(x - 1) + fibonacci(x - 2) - } -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala deleted file mode 100644 index 584038ee2c..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.scala - -import com.baeldung.scala.ControlStructuresDemo._ -import org.junit.Assert.assertEquals -import org.junit.Test - -class ControlStructuresDemoUnitTest { - @Test - def givenTwoIntegers_whenGcdCalled_thenCorrectValueReturned() = { - assertEquals(3, gcd(15, 27)) - } - - @Test - def givenTwoIntegers_whenGcdIterCalled_thenCorrectValueReturned() = { - assertEquals(3, gcdIter(15, 27)) - } - - @Test - def givenTwoIntegers_whenRangeSumcalled_thenCorrectValueReturned() = { - assertEquals(55, rangeSum(1, 10)) - } - - @Test - def givenPositiveInteger_whenFactorialInvoked_thenCorrectValueReturned() = { - assertEquals(720, factorial(6)) - } - - @Test - def whenFactorialOf0Invoked_then1Returned() = { - assertEquals(1, factorial(0)) - } - -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala deleted file mode 100644 index 0828752a8a..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.scala - -import org.junit.Assert.assertEquals -import org.junit.Test - -class EmployeeUnitTest { - - @Test - def whenEmployeeSalaryIncremented_thenCorrectSalary() = { - val employee = new Employee("John Doe", 1000) - employee.incrementSalary() - assertEquals(1020, employee.salary) - } - - @Test - def givenEmployee_whenToStringCalled_thenCorrectStringReturned() = { - val employee = new Employee("John Doe", 1000) - assertEquals("Employee(name=John Doe, salary=1000)", employee.toString) - } - - @Test - def givenEmployeeWithTrait_whenToStringCalled_thenCorrectStringReturned() = { - val employee = - new Employee("John Doe", 1000) with UpperCasePrinter - assertEquals("EMPLOYEE(NAME=JOHN DOE, SALARY=1000)", employee.toString) - } - -} - - diff --git a/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala deleted file mode 100644 index 240c879d7f..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.scala - -import com.baeldung.scala.HigherOrderFunctions.mapReduce -import org.junit.Assert.assertEquals -import org.junit.Test - -class HigherOrderFunctionsUnitTest { - - @Test - def whenCalledWithSumAndSquareFunctions_thenCorrectValueReturned() = { - def square(x : Int) = x * x - - def sum(x : Int, y : Int) = x + y - - def sumSquares(a : Int, b : Int) = - mapReduce(sum, 0, square, a, b) - - assertEquals(385, sumSquares(1, 10)) - } - - @Test - def whenComputingSumOfSquaresWithAnonymousFunctions_thenCorrectValueReturned() = { - def sumSquares(a : Int, b : Int) = - mapReduce((x, y) => x + y, 0, x => x * x, a, b) - - assertEquals(385, sumSquares(1, 10)) - } - - @Test - def givenCurriedFunctions_whenInvoked_thenCorrectValueReturned() = { - // a curried function - def sum(f : Int => Int)(a : Int, - b : Int) : Int = - if (a > b) 0 else f(a) + sum(f)(a + 1, b) - - // another curried function - def mod(n : Int)(x : Int) = x % n - - // application of a curried function - assertEquals(1, mod(5)(6)) - - // partial application of curried function - // trailing underscore is required to make function type explicit - val sumMod5 = sum(mod(5)) _ - - assertEquals(10, sumMod5(6, 10)) - } -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala deleted file mode 100644 index ac27389d70..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.scala - -import org.junit.Assert.assertFalse -import org.junit.Test - -class IntSetUnitTest { - - @Test - def givenSetof1To10_whenContains11Called_thenFalse() = { - - // Set up a set containing integers 1 to 10. - val set1To10 = - Range(1, 10) - .foldLeft(new EmptyIntSet() : IntSet) { - (x, y) => x incl y - } - - assertFalse(set1To10 contains 11) - } - -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/PatternMatchingUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/PatternMatchingUnitTest.scala deleted file mode 100644 index 21a2f0e871..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/PatternMatchingUnitTest.scala +++ /dev/null @@ -1,208 +0,0 @@ -package com.baeldung.scala - -import java.io.FileNotFoundException - -import org.junit.Assert.assertEquals -import org.junit.Test - -class PatternMatchingUnitTest { - @Test - def whenAMammalIsGivenToTheMatchExpression_ThenItsRecognizedAsMammal(): Unit = { - val result = new PatternMatching().caseClassesPatternMatching(Mammal("Lion", fromSea = false)) - assertEquals("I'm a Lion, a kind of mammal. Am I from the sea? false", result) - } - - @Test - def whenABirdIsGivenToTheMatchExpression_ThenItsRecognizedAsBird(): Unit = { - val result = new PatternMatching().caseClassesPatternMatching(Bird("Pigeon")) - assertEquals("I'm a Pigeon, a kind of bird", result) - } - - @Test - def whenAnUnkownAnimalIsGivenToTheMatchExpression_TheDefaultClauseIsUsed(): Unit = { - val result = new PatternMatching().caseClassesPatternMatching(Fish("Tuna")) - assertEquals("I'm an unknown animal", result) - } - - @Test - def whenTheConstantZeroIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().constantsPatternMatching(0) - assertEquals("I'm equal to zero", result) - } - - @Test - def whenFourAndAHalfIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().constantsPatternMatching(4.5d) - assertEquals("I'm a double", result) - } - - @Test - def whenTheBooleanFalseIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().constantsPatternMatching(false) - assertEquals("I'm the contrary of true", result) - } - - @Test - def whenAnUnkownConstantIsPassed_ThenTheDefaultPatternIsUsed(): Unit = { - val result = new PatternMatching().constantsPatternMatching(true) - assertEquals("I'm unknown and equal to true", result) - } - - @Test - def whenASingleElementListIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(List("String")) - assertEquals("I'm a list with one element: String", result) - } - - @Test - def whenAMultipleElementsListIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(List("Multiple", "Elements")) - assertEquals("I'm a list with one or multiple elements: List(Multiple, Elements)", result) - } - - @Test - def whenAVectorBeginningWithOneAndTwoIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(Vector(1, 2, 3)) - assertEquals("I'm a vector: Vector(1, 2, 3)", result) - } - - @Test - def whenANotMatchingVectorIsPassed_ThenItShouldntMatchAndEnterTheDefaultClause(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(Vector(2, 1)) - assertEquals("I'm an unrecognized sequence. My value: Vector(2, 1)", result) - } - - @Test - def whenAnEmptyListIsPassed_ThenItShouldntMatchAndEnterTheDefaultClause(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(List()) - assertEquals("I'm an unrecognized sequence. My value: List()", result) - } - - @Test - def whenATwoElementsTupleIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().tuplesPatternMatching(("First", "Second")) - assertEquals("I'm a tuple with two elements: First & Second", result) - } - - @Test - def whenAThreeElementsTupleIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().tuplesPatternMatching(("First", "Second", "Third")) - assertEquals("I'm a tuple with three elements: First & Second & Third", result) - } - - @Test - def whenAnoterKindOfTupleIsPassed_ThenItShouldntMatchAndReturnTheDefaultPattern(): Unit = { - val result = new PatternMatching().tuplesPatternMatching(("First")) - assertEquals("Unrecognized pattern. My value: First", result) - } - - @Test - def whenAStringConsistingOfNumericsOnlyIsPassed_ThenItShouldMatchTheNumericRegex(): Unit = { - val result = new PatternMatching().regexPatterns("123") - assertEquals("I'm a numeric with value 123", result) - } - - @Test - def whenAStringConsistignOfAlphabeticsOnlyIsPassed_ThenItShouldMatchTheAlphabeticRegex(): Unit = { - val result = new PatternMatching().regexPatterns("abc") - assertEquals("I'm an alphabetic with value abc", result) - } - - @Test - def whenAStringConsistignOfAlphanumericsOnlyIsPassed_ThenItShouldMatchTheAlphanumericRegex(): Unit = { - val result = new PatternMatching().regexPatterns("abc123") - assertEquals("I'm an alphanumeric with value abc123", result) - } - - @Test - def whenAnotherTypeOfStringIsPassed_ThenItShouldntMatchAndReturnTheDefaultPattern(): Unit = { - val result = new PatternMatching().regexPatterns("abc_123") - assertEquals("I contain other characters than alphanumerics. My value abc_123", result) - } - - @Test - def whenAFilledOptionIsPassed_ThenItShouldMatchTheSomeClause(): Unit = { - val result = new PatternMatching().optionsPatternMatching(Option.apply("something")) - assertEquals("I'm not an empty option. Value something", result) - } - - @Test - def whenAnEmptyOptionIsPassed_ThenItShouldMatchTheNoneClause(): Unit = { - val result = new PatternMatching().optionsPatternMatching(Option.empty) - assertEquals("I'm an empty option", result) - } - - @Test - def whenAListWithAcceptedSizeIsPassed_ThenThePositiveMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards(List(1, 2), 3) - assertEquals("List is of acceptable size", result) - } - - @Test - def whenAListWithAnUnacceptedSizeIsPassed_ThenTheNegativeMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards(List(1, 2, 3, 4), 3) - assertEquals("List has not an acceptable size", result) - } - - @Test - def whenAStringWithAcceptedSizeIsPassed_ThenThePositiveMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards("OK", 3) - assertEquals("String is of acceptable size", result) - } - - @Test - def whenAStringWithAnUnacceptedSizeIsPassed_ThenTheNegativeMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards("Not OK", 3) - assertEquals("String has not an acceptable size", result) - } - - @Test - def whenAnObjectWhichIsNotAListOrAStringIsPassed_thenTheDefaultClauseIsUsed(): Unit = { - val result = new PatternMatching().patternGuards(1, 1) - assertEquals("Input is neither a List or a String", result) - } - - @Test - def whenACardSuitIsPassed_ThenTheCorrespondingMatchCaseClauseIsUsed(): Unit = { - assertEquals("Card is spike", new PatternMatching().sealedClass(Spike())) - assertEquals("Card is club", new PatternMatching().sealedClass(Club())) - assertEquals("Card is heart", new PatternMatching().sealedClass(Heart())) - assertEquals("Card is diamond", new PatternMatching().sealedClass(Diamond())) - } - - @Test - def whenAnObjectWithExtractorIsPassed_ThenTheExtractedValueIsUsedInTheCaseClause(): Unit = { - val person = Person("John Smith") - val result = new PatternMatching().extractors(person) - assertEquals("My initials are J. S.", result) - } - - @Test - def whenAnObjectWithExtractorIsPassed_AndTheValueIsEmpty_ThenTheDefaultCaseClauseIsUsed(): Unit = { - val person = Person("") - val result = new PatternMatching().extractors(person) - assertEquals("Could not extract initials", result) - } - - @Test - def whenAListOfRandomElementsIsPassed_ThenOnlyTheIntegersBelowTenAreReturned(): Unit = { - val input = List(1, 2, "5", 11, true) - val result = new PatternMatching().closuresPatternMatching(input) - assertEquals(List(1, 2), result) - } - - @Test - def whenAnExceptionIsPassed_ThenTheCorrespondingMessageIsReturned(): Unit = { - val pm = new PatternMatching() - - val iae = new IllegalArgumentException() - val re = new RuntimeException() - val fnfe = new FileNotFoundException() - - assertEquals("It's an IllegalArgumentException", pm.catchBlocksPatternMatching(iae)) - assertEquals("It's a RuntimeException", pm.catchBlocksPatternMatching(re)) - assertEquals("It's an unknown kind of exception", pm.catchBlocksPatternMatching(fnfe)) - } -} - - diff --git a/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala deleted file mode 100644 index e4995201d8..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.scala - -import com.baeldung.scala.Utils.{average, fibonacci, power, randomLessThan} -import org.junit.Assert.{assertEquals, assertTrue} -import org.junit.Test - -class UtilsUnitTest { - - @Test - def whenAverageCalled_thenCorrectValueReturned(): Unit = { - assertEquals(15.0, average(10, 20), 1e-5) - } - - @Test - def whenRandomLessThanInvokedWithANumber_thenARandomLessThanItReturned: Unit = { - val d = 0.1 - assertTrue(randomLessThan(d) < d) - } - - @Test - def whenPowerInvokedWith2And3_then8Returned: Unit = { - assertEquals(8, power(2, 3)) - } - - @Test - def whenFibonacciCalled_thenCorrectValueReturned: Unit = { - assertEquals(1, fibonacci(0)) - assertEquals(1, fibonacci(1)) - assertEquals(fibonacci(6), - fibonacci(4) + fibonacci(5)) - } -} \ No newline at end of file diff --git a/couchbase/pom.xml b/couchbase/pom.xml index f4e98b32ba..34e2832e55 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 couchbase 0.1-SNAPSHOT diff --git a/custom-pmd/README.md b/custom-pmd/README.md index 0c42106fe8..d49047f180 100644 --- a/custom-pmd/README.md +++ b/custom-pmd/README.md @@ -1,7 +1,3 @@ ## Custom PMD Rules This module contains articles about PMD - -### Relevant Articles: - -- [Introduction To PMD](https://www.baeldung.com/pmd) \ No newline at end of file diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index 601eedf08f..e0f38199ec 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -1,8 +1,10 @@ - + 4.0.0 - org.baeldung.pmd + com.baeldung.pmd custom-pmd 0.0.1 custom-pmd diff --git a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java b/custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java similarity index 97% rename from custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java rename to custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java index 2cbab782ee..e30164ac4f 100644 --- a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java +++ b/custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java @@ -1,4 +1,4 @@ -package org.baeldung.pmd; +package com.baeldung.pmd; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; diff --git a/dagger/pom.xml b/dagger/pom.xml index 528a5383c6..e9410ceb63 100644 --- a/dagger/pom.xml +++ b/dagger/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 dagger dagger @@ -44,4 +46,4 @@ 2.16 - \ No newline at end of file + diff --git a/data-structures/README.md b/data-structures/README.md index 7eeda7c64f..f9ca78679a 100644 --- a/data-structures/README.md +++ b/data-structures/README.md @@ -6,3 +6,7 @@ This module contains articles about data structures in Java - [The Trie Data Structure in Java](https://www.baeldung.com/trie-java) - [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree) +- [Circular Linked List Java Implementation](https://www.baeldung.com/java-circular-linked-list) +- [How to Print a Binary Tree Diagram](https://www.baeldung.com/java-print-binary-tree-diagram) +- [Introduction to Big Queue](https://www.baeldung.com/java-big-queue) +- [Guide to AVL Trees in Java](https://www.baeldung.com/java-avl-trees) diff --git a/data-structures/pom.xml b/data-structures/pom.xml index e8f4628062..e2d2e23090 100644 --- a/data-structures/pom.xml +++ b/data-structures/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 data-structures 0.0.1-SNAPSHOT @@ -12,6 +14,21 @@ 1.0.0-SNAPSHOT + + + github.release.repo + https://raw.github.com/bulldog2011/bulldog-repo/master/repo/releases/ + + + + + + com.leansoft + bigqueue + ${bigqueue.version} + + + @@ -24,4 +41,8 @@ + + 0.7.0 + + diff --git a/data-structures/src/main/java/com/baeldung/avltree/AVLTree.java b/data-structures/src/main/java/com/baeldung/avltree/AVLTree.java new file mode 100644 index 0000000000..ca0cfce7b4 --- /dev/null +++ b/data-structures/src/main/java/com/baeldung/avltree/AVLTree.java @@ -0,0 +1,141 @@ +package com.baeldung.avltree; + +public class AVLTree { + + public class Node { + int key; + int height; + Node left; + Node right; + + Node(int key) { + this.key = key; + } + } + + private Node root; + + public Node find(int key) { + Node current = root; + while (current != null) { + if (current.key == key) { + break; + } + current = current.key < key ? current.right : current.left; + } + return current; + } + + public void insert(int key) { + root = insert(root, key); + } + + public void delete(int key) { + root = delete(root, key); + } + + public Node getRoot() { + return root; + } + + public int height() { + return root == null ? -1 : root.height; + } + + private Node insert(Node node, int key) { + if (node == null) { + return new Node(key); + } else if (node.key > key) { + node.left = insert(node.left, key); + } else if (node.key < key) { + node.right = insert(node.right, key); + } else { + throw new RuntimeException("duplicate Key!"); + } + return rebalance(node); + } + + private Node delete(Node node, int key) { + if (node == null) { + return node; + } else if (node.key > key) { + node.left = delete(node.left, key); + } else if (node.key < key) { + node.right = delete(node.right, key); + } else { + if (node.left == null || node.right == null) { + node = (node.left == null) ? node.right : node.left; + } else { + Node mostLeftChild = mostLeftChild(node.right); + node.key = mostLeftChild.key; + node.right = delete(node.right, node.key); + } + } + if (node != null) { + node = rebalance(node); + } + return node; + } + + private Node mostLeftChild(Node node) { + Node current = node; + /* loop down to find the leftmost leaf */ + while (current.left != null) { + current = current.left; + } + return current; + } + + private Node rebalance(Node z) { + updateHeight(z); + int balance = getBalance(z); + if (balance > 1) { + if (height(z.right.right) > height(z.right.left)) { + z = rotateLeft(z); + } else { + z.right = rotateRight(z.right); + z = rotateLeft(z); + } + } else if (balance < -1) { + if (height(z.left.left) > height(z.left.right)) { + z = rotateRight(z); + } else { + z.left = rotateLeft(z.left); + z = rotateRight(z); + } + } + return z; + } + + private Node rotateRight(Node y) { + Node x = y.left; + Node z = x.right; + x.right = y; + y.left = z; + updateHeight(y); + updateHeight(x); + return x; + } + + private Node rotateLeft(Node y) { + Node x = y.right; + Node z = x.left; + x.left = y; + y.right = z; + updateHeight(y); + updateHeight(x); + return x; + } + + private void updateHeight(Node n) { + n.height = 1 + Math.max(height(n.left), height(n.right)); + } + + private int height(Node n) { + return n == null ? -1 : n.height; + } + + public int getBalance(Node n) { + return (n == null) ? 0 : height(n.right) - height(n.left); + } +} 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 bb62714006..7469e8ba64 100644 --- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java @@ -142,7 +142,7 @@ public class BinaryTree { nodes.add(node.left); } - if (node.left != null) { + if (node.right != null) { nodes.add(node.right); } } diff --git a/data-structures/src/test/java/com/baeldung/avltree/AVLTreeUnitTest.java b/data-structures/src/test/java/com/baeldung/avltree/AVLTreeUnitTest.java new file mode 100644 index 0000000000..56fc893232 --- /dev/null +++ b/data-structures/src/test/java/com/baeldung/avltree/AVLTreeUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.avltree; + +import org.junit.Assert; +import org.junit.Test; + +public class AVLTreeUnitTest { + + @Test + public void givenEmptyTree_whenHeightCalled_shouldReturnMinus1() { + AVLTree tree = new AVLTree(); + Assert.assertEquals(-1, tree.height()); + } + + @Test + public void givenEmptyTree_whenInsertCalled_heightShouldBeZero() { + AVLTree tree = new AVLTree(); + tree.insert(1); + Assert.assertEquals(0, tree.height()); + } + + @Test + public void givenEmptyTree_whenInsertCalled_treeShouldBeAvl() { + AVLTree tree = new AVLTree(); + tree.insert(1); + Assert.assertTrue(isAVL(tree)); + } + + @Test + public void givenSampleTree_whenInsertCalled_treeShouldBeAvl() { + AVLTree tree = getSampleAVLTree(); + int newKey = 11; + tree.insert(newKey); + Assert.assertTrue(isAVL(tree)); + } + + @Test + public void givenSampleTree_whenFindExistingKeyCalled_shouldReturnMatchedNode() { + AVLTree tree = getSampleAVLTree(); + int existingKey = 2; + AVLTree.Node result = tree.find(existingKey); + Assert.assertEquals(result.key, existingKey); + } + + @Test + public void givenSampleTree_whenFindNotExistingKeyCalled_shouldReturnNull() { + AVLTree tree = getSampleAVLTree(); + int notExistingKey = 11; + AVLTree.Node result = tree.find(notExistingKey); + Assert.assertNull(result); + } + + @Test + public void givenEmptyTree_whenDeleteCalled_treeShouldBeAvl() { + AVLTree tree = new AVLTree(); + tree.delete(1); + Assert.assertTrue(isAVL(tree)); + } + + @Test + public void givenSampleTree_whenDeleteCalled_treeShouldBeAvl() { + AVLTree tree = getSampleAVLTree(); + tree.delete(1); + Assert.assertTrue(isAVL(tree, tree.getRoot())); + } + + private boolean isAVL(AVLTree tree) { + return isAVL(tree, tree.getRoot()); + } + + private boolean isAVL(AVLTree tree, AVLTree.Node node) { + if ( node == null ) + return true; + int balance = tree.getBalance(node); + return (balance <= 1 && balance >= -1) && isAVL(tree, node.left) && isAVL(tree, node.right); + } + + private AVLTree getSampleAVLTree() { + AVLTree avlTree = new AVLTree(); + for (int i = 0; i < 10; i++) + avlTree.insert(i); + return avlTree; + } +} diff --git a/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java b/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java new file mode 100644 index 0000000000..c0305a7ca3 --- /dev/null +++ b/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java @@ -0,0 +1,82 @@ +package com.baeldung.bigqueue; + +import com.leansoft.bigqueue.BigQueueImpl; +import com.leansoft.bigqueue.IBigQueue; +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.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@RunWith(JUnit4.class) +public class BigQueueLiveTest { + + private IBigQueue bigQueue; + + @Before + public void setup() throws IOException { + String queueDir = System.getProperty("user.home"); + String queueName = "baeldung-queue"; + bigQueue = new BigQueueImpl(queueDir, queueName); + } + + @After + public void emptyQueue() throws IOException { + bigQueue.removeAll(); + bigQueue.gc(); + bigQueue.close(); + } + + @Test + public void whenAddingRecords_ThenTheSizeIsCorrect() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + + assertEquals(100, bigQueue.size()); + } + + @Test + public void whenAddingRecords_ThenTheyCanBeRetrieved() throws IOException { + bigQueue.enqueue(String.valueOf("new_record").getBytes()); + + String record = new String(bigQueue.dequeue()); + assertEquals("new_record", record); + } + + @Test + public void whenDequeueingRecords_ThenTheyAreConsumed() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + bigQueue.dequeue(); + + assertEquals(99, bigQueue.size()); + } + + @Test + public void whenPeekingRecords_ThenSizeDoesntChange() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + String firstRecord = new String(bigQueue.peek()); + + assertEquals("1", firstRecord); + assertEquals(100, bigQueue.size()); + } + + @Test + public void whenEmptyingTheQueue_ThenItSizeIs0() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + bigQueue.removeAll(); + + assertEquals(0, bigQueue.size()); + } + +} diff --git a/ddd-modules/README.md b/ddd-modules/README.md new file mode 100644 index 0000000000..ba6b8d5016 --- /dev/null +++ b/ddd-modules/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [DDD Bounded Contexts and Java Modules](https://www.baeldung.com/java-modules-ddd-bounded-contexts) diff --git a/ddd-modules/infrastructure/pom.xml b/ddd-modules/infrastructure/pom.xml new file mode 100644 index 0000000000..c301eaa92a --- /dev/null +++ b/ddd-modules/infrastructure/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + com.baeldung.dddmodules.infrastructure + infrastructure + 1.0 + + jar + + + com.baeldung.dddmodules + dddmodules + 1.0 + + + + + com.baeldung.dddmodules.shippingcontext + shippingcontext + ${appmodules.version} + + + com.baeldung.dddmodules.ordercontext + ordercontext + ${appmodules.version} + + + com.baeldung.dddmodules.sharedkernel + sharedkernel + ${appmodules.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${source.version} + ${target.version} + + + + + + + 9 + 9 + + + \ No newline at end of file diff --git a/ddd-modules/infrastructure/src/main/java/com/baeldung/dddmodules/infrastructure/db/InMemoryOrderStore.java b/ddd-modules/infrastructure/src/main/java/com/baeldung/dddmodules/infrastructure/db/InMemoryOrderStore.java new file mode 100644 index 0000000000..13deb2471e --- /dev/null +++ b/ddd-modules/infrastructure/src/main/java/com/baeldung/dddmodules/infrastructure/db/InMemoryOrderStore.java @@ -0,0 +1,79 @@ +package com.baeldung.dddmodules.infrastructure.db; + +import com.baeldung.dddmodules.ordercontext.model.CustomerOrder; +import com.baeldung.dddmodules.ordercontext.repository.CustomerOrderRepository; +import com.baeldung.dddmodules.shippingcontext.model.PackageItem; +import com.baeldung.dddmodules.shippingcontext.model.ShippableOrder; +import com.baeldung.dddmodules.shippingcontext.repository.ShippingOrderRepository; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +public class InMemoryOrderStore implements CustomerOrderRepository, ShippingOrderRepository { + private Map ordersDb = new HashMap<>(); + private volatile static InMemoryOrderStore instance = new InMemoryOrderStore(); + + @Override + public void saveCustomerOrder(CustomerOrder order) { + this.ordersDb.put(order.getOrderId(), new PersistenceOrder(order.getOrderId(), + order.getPaymentMethod(), + order.getAddress(), + order + .getOrderItems() + .stream() + .map(orderItem -> + new PersistenceOrder.OrderItem(orderItem.getProductId(), + orderItem.getQuantity(), + orderItem.getUnitWeight(), + orderItem.getUnitPrice())) + .collect(Collectors.toList()) + )); + } + + @Override + public Optional findShippableOrder(int orderId) { + if (!this.ordersDb.containsKey(orderId)) return Optional.empty(); + PersistenceOrder orderRecord = this.ordersDb.get(orderId); + return Optional.of( + new ShippableOrder(orderRecord.orderId, orderRecord.orderItems + .stream().map(orderItem -> new PackageItem(orderItem.productId, + orderItem.itemWeight, + orderItem.quantity * orderItem.unitPrice) + ).collect(Collectors.toList()))); + } + + public static InMemoryOrderStore provider() { + return instance; + } + + public static class PersistenceOrder { + public int orderId; + public String paymentMethod; + public String address; + public List orderItems; + + public PersistenceOrder(int orderId, String paymentMethod, String address, List orderItems) { + this.orderId = orderId; + this.paymentMethod = paymentMethod; + this.address = address; + this.orderItems = orderItems; + } + + public static class OrderItem { + public int productId; + public float unitPrice; + public float itemWeight; + public int quantity; + + public OrderItem(int productId, int quantity, float unitWeight, float unitPrice) { + this.itemWeight = unitWeight; + this.quantity = quantity; + this.unitPrice = unitPrice; + this.productId = productId; + } + } + } +} diff --git a/ddd-modules/infrastructure/src/main/java/com/baeldung/dddmodules/infrastructure/events/SimpleEventBus.java b/ddd-modules/infrastructure/src/main/java/com/baeldung/dddmodules/infrastructure/events/SimpleEventBus.java new file mode 100644 index 0000000000..6aea7ff6e9 --- /dev/null +++ b/ddd-modules/infrastructure/src/main/java/com/baeldung/dddmodules/infrastructure/events/SimpleEventBus.java @@ -0,0 +1,39 @@ +package com.baeldung.dddmodules.infrastructure.events; + +import com.baeldung.dddmodules.sharedkernel.events.ApplicationEvent; +import com.baeldung.dddmodules.sharedkernel.events.EventBus; +import com.baeldung.dddmodules.sharedkernel.events.EventSubscriber; + +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArraySet; + +public class SimpleEventBus implements EventBus { + private final Map> subscribers = new ConcurrentHashMap<>(); + + @Override + public void publish(E event) { + if (subscribers.containsKey(event.getType())) { + subscribers.get(event.getType()) + .forEach(subscriber -> subscriber.onEvent(event)); + } + } + + @Override + public void subscribe(String eventType, EventSubscriber subscriber) { + Set eventSubscribers = subscribers.get(eventType); + if (eventSubscribers == null) { + eventSubscribers = new CopyOnWriteArraySet<>(); + subscribers.put(eventType, eventSubscribers); + } + eventSubscribers.add(subscriber); + } + + @Override + public void unsubscribe(String eventType, EventSubscriber subscriber) { + if (subscribers.containsKey(eventType)) { + subscribers.get(eventType).remove(subscriber); + } + } +} diff --git a/ddd-modules/infrastructure/src/main/java/module-info.java b/ddd-modules/infrastructure/src/main/java/module-info.java new file mode 100644 index 0000000000..19f7b36548 --- /dev/null +++ b/ddd-modules/infrastructure/src/main/java/module-info.java @@ -0,0 +1,11 @@ +module com.baeldung.dddmodules.infrastructure { + requires transitive com.baeldung.dddmodules.sharedkernel; + requires transitive com.baeldung.dddmodules.ordercontext; + requires transitive com.baeldung.dddmodules.shippingcontext; + provides com.baeldung.dddmodules.sharedkernel.events.EventBus + with com.baeldung.dddmodules.infrastructure.events.SimpleEventBus; + provides com.baeldung.dddmodules.ordercontext.repository.CustomerOrderRepository + with com.baeldung.dddmodules.infrastructure.db.InMemoryOrderStore; + provides com.baeldung.dddmodules.shippingcontext.repository.ShippingOrderRepository + with com.baeldung.dddmodules.infrastructure.db.InMemoryOrderStore; +} diff --git a/ddd-modules/mainapp/pom.xml b/ddd-modules/mainapp/pom.xml new file mode 100644 index 0000000000..a048263d37 --- /dev/null +++ b/ddd-modules/mainapp/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + com.baeldung.dddmodules.mainapp + mainapp + 1.0 + jar + + + com.baeldung.dddmodules + dddmodules + 1.0 + + + + + com.baeldung.dddmodules.infrastructure + infrastructure + ${appmodules.version} + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.16 + + true + + + + org.apache.maven.plugins + maven-compiler-plugin + ${compiler.plugin.version} + + ${source.version} + ${target.version} + + + + + + + 9 + 9 + + + \ No newline at end of file diff --git a/ddd-modules/mainapp/src/main/java/com/baeldung/dddmodules/mainapp/Application.java b/ddd-modules/mainapp/src/main/java/com/baeldung/dddmodules/mainapp/Application.java new file mode 100644 index 0000000000..05e27abe30 --- /dev/null +++ b/ddd-modules/mainapp/src/main/java/com/baeldung/dddmodules/mainapp/Application.java @@ -0,0 +1,54 @@ +package com.baeldung.dddmodules.mainapp; + +import com.baeldung.dddmodules.ordercontext.model.CustomerOrder; +import com.baeldung.dddmodules.ordercontext.model.OrderItem; +import com.baeldung.dddmodules.ordercontext.repository.CustomerOrderRepository; +import com.baeldung.dddmodules.ordercontext.service.OrderService; +import com.baeldung.dddmodules.sharedkernel.events.EventBus; +import com.baeldung.dddmodules.shippingcontext.repository.ShippingOrderRepository; +import com.baeldung.dddmodules.shippingcontext.service.ShippingService; + +import java.util.*; + +public class Application { + + public static void main(String args[]) { + Map, Object> container = createContainer(); + OrderService orderService = (OrderService) container.get(OrderService.class); + ShippingService shippingService = (ShippingService) container.get(ShippingService.class); + shippingService.listenToOrderEvents(); + + CustomerOrder customerOrder = new CustomerOrder(); + int orderId = 1; + customerOrder.setOrderId(orderId); + List orderItems = new ArrayList(); + orderItems.add(new OrderItem(1, 2, 3, 1)); + orderItems.add(new OrderItem(2, 1, 1, 1)); + orderItems.add(new OrderItem(3, 4, 11, 21)); + customerOrder.setOrderItems(orderItems); + customerOrder.setPaymentMethod("PayPal"); + customerOrder.setAddress("Full address here"); + orderService.placeOrder(customerOrder); + + if (orderId == shippingService.getParcelByOrderId(orderId).get().getOrderId()) { + System.out.println("Order has been processed and shipped successfully"); + } + } + + public static Map, Object> createContainer() { + EventBus eventBus = ServiceLoader.load(EventBus.class).findFirst().get(); + CustomerOrderRepository customerOrderRepository = ServiceLoader.load(CustomerOrderRepository.class).findFirst().get(); + ShippingOrderRepository shippingOrderRepository = ServiceLoader.load(ShippingOrderRepository.class).findFirst().get(); + ShippingService shippingService = ServiceLoader.load(ShippingService.class).findFirst().get(); + shippingService.setEventBus(eventBus); + shippingService.setOrderRepository(shippingOrderRepository); + OrderService orderService = ServiceLoader.load(OrderService.class).findFirst().get(); + orderService.setEventBus(eventBus); + orderService.setOrderRepository(customerOrderRepository); + HashMap, Object> container = new HashMap<>(); + container.put(OrderService.class, orderService); + container.put(ShippingService.class, shippingService); + return container; + } + +} diff --git a/ddd-modules/mainapp/src/main/java/module-info.java b/ddd-modules/mainapp/src/main/java/module-info.java new file mode 100644 index 0000000000..356b03731c --- /dev/null +++ b/ddd-modules/mainapp/src/main/java/module-info.java @@ -0,0 +1,8 @@ +module com.baeldung.dddmodules.mainapp { + uses com.baeldung.dddmodules.sharedkernel.events.EventBus; + uses com.baeldung.dddmodules.ordercontext.service.OrderService; + uses com.baeldung.dddmodules.ordercontext.repository.CustomerOrderRepository; + uses com.baeldung.dddmodules.shippingcontext.repository.ShippingOrderRepository; + uses com.baeldung.dddmodules.shippingcontext.service.ShippingService; + requires transitive com.baeldung.dddmodules.infrastructure; +} \ No newline at end of file diff --git a/ddd-modules/ordercontext/pom.xml b/ddd-modules/ordercontext/pom.xml new file mode 100644 index 0000000000..abd166fb69 --- /dev/null +++ b/ddd-modules/ordercontext/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + com.baeldung.dddmodules.ordercontext + ordercontext + 1.0 + jar + + + com.baeldung.dddmodules + dddmodules + 1.0 + + + + + com.baeldung.dddmodules.sharedkernel + sharedkernel + ${appmodules.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${source.version} + ${target.version} + + + + + + + 9 + 9 + 1.0 + 1.0 + + + \ No newline at end of file diff --git a/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/model/CustomerOrder.java b/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/model/CustomerOrder.java new file mode 100644 index 0000000000..ee87de56bd --- /dev/null +++ b/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/model/CustomerOrder.java @@ -0,0 +1,51 @@ +package com.baeldung.dddmodules.ordercontext.model; + +import java.util.List; + +public class CustomerOrder { + private int orderId; + private String paymentMethod; + private String address; + private List orderItems; + + public CustomerOrder() { + + } + + public float calculateTotalPrice() { + return orderItems.stream().map(OrderItem::getTotalPrice) + .reduce(0F, Float::sum); + } + + public void setOrderItems(List orderItems) { + this.orderItems = orderItems; + } + + public int getOrderId() { + return orderId; + } + + public List getOrderItems() { + return orderItems; + } + + public void setOrderId(int orderId) { + this.orderId = orderId; + } + + public String getPaymentMethod() { + return paymentMethod; + } + + public void setPaymentMethod(String paymentMethod) { + this.paymentMethod = paymentMethod; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/model/OrderItem.java b/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/model/OrderItem.java new file mode 100644 index 0000000000..aaad0777e4 --- /dev/null +++ b/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/model/OrderItem.java @@ -0,0 +1,51 @@ +package com.baeldung.dddmodules.ordercontext.model; + +public class OrderItem { + private int productId; + private int quantity; + private float unitPrice; + private float unitWeight; + + public OrderItem(int productId, int quantity, float unitPrice, float unitWeight) { + this.productId = productId; + this.quantity = quantity; + this.unitPrice = unitPrice; + this.unitWeight = unitWeight; + } + + public int getProductId() { + return productId; + } + + public void setProductId(int productId) { + this.productId = productId; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public float getTotalPrice() { + return this.quantity * this.unitPrice; + } + + public void setUnitPrice(float unitPrice) { + this.unitPrice = unitPrice; + } + + public float getUnitWeight() { + return unitWeight; + } + + public float getUnitPrice() { + return unitPrice; + } + + public void setUnitWeight(float unitWeight) { + this.unitWeight = unitWeight; + } +} diff --git a/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/repository/CustomerOrderRepository.java b/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/repository/CustomerOrderRepository.java new file mode 100644 index 0000000000..771bbf3301 --- /dev/null +++ b/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/repository/CustomerOrderRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.dddmodules.ordercontext.repository; + +import com.baeldung.dddmodules.ordercontext.model.CustomerOrder; + +public interface CustomerOrderRepository { + void saveCustomerOrder(CustomerOrder order); +} diff --git a/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/service/CustomerOrderService.java b/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/service/CustomerOrderService.java new file mode 100644 index 0000000000..b9d26e6212 --- /dev/null +++ b/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/service/CustomerOrderService.java @@ -0,0 +1,44 @@ +package com.baeldung.dddmodules.ordercontext.service; + +import com.baeldung.dddmodules.ordercontext.model.CustomerOrder; +import com.baeldung.dddmodules.ordercontext.repository.CustomerOrderRepository; +import com.baeldung.dddmodules.sharedkernel.events.ApplicationEvent; +import com.baeldung.dddmodules.sharedkernel.events.EventBus; + +import java.util.HashMap; +import java.util.Map; + +public class CustomerOrderService implements OrderService { + public static final String EVENT_ORDER_READY_FOR_SHIPMENT = "OrderReadyForShipmentEvent"; + + private CustomerOrderRepository orderRepository; + private EventBus eventBus; + + @Override + public void placeOrder(CustomerOrder order) { + this.orderRepository.saveCustomerOrder(order); + Map payload = new HashMap<>(); + payload.put("order_id", String.valueOf(order.getOrderId())); + ApplicationEvent event = new ApplicationEvent(payload) { + @Override + public String getType() { + return EVENT_ORDER_READY_FOR_SHIPMENT; + } + }; + this.eventBus.publish(event); + } + + @Override + public EventBus getEventBus() { + return eventBus; + } + + public void setOrderRepository(CustomerOrderRepository orderRepository) { + this.orderRepository = orderRepository; + } + + @Override + public void setEventBus(EventBus eventBus) { + this.eventBus = eventBus; + } +} diff --git a/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/service/OrderService.java b/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/service/OrderService.java new file mode 100644 index 0000000000..1bbb8b8398 --- /dev/null +++ b/ddd-modules/ordercontext/src/main/java/com/baeldung/dddmodules/ordercontext/service/OrderService.java @@ -0,0 +1,11 @@ +package com.baeldung.dddmodules.ordercontext.service; + +import com.baeldung.dddmodules.ordercontext.model.CustomerOrder; +import com.baeldung.dddmodules.ordercontext.repository.CustomerOrderRepository; +import com.baeldung.dddmodules.sharedkernel.service.ApplicationService; + +public interface OrderService extends ApplicationService { + void placeOrder(CustomerOrder order); + + void setOrderRepository(CustomerOrderRepository orderRepository); +} diff --git a/ddd-modules/ordercontext/src/main/java/module-info.java b/ddd-modules/ordercontext/src/main/java/module-info.java new file mode 100644 index 0000000000..e9b7cf9535 --- /dev/null +++ b/ddd-modules/ordercontext/src/main/java/module-info.java @@ -0,0 +1,8 @@ +module com.baeldung.dddmodules.ordercontext { + requires com.baeldung.dddmodules.sharedkernel; + exports com.baeldung.dddmodules.ordercontext.service; + exports com.baeldung.dddmodules.ordercontext.model; + exports com.baeldung.dddmodules.ordercontext.repository; + provides com.baeldung.dddmodules.ordercontext.service.OrderService + with com.baeldung.dddmodules.ordercontext.service.CustomerOrderService; +} \ No newline at end of file diff --git a/ddd-modules/pom.xml b/ddd-modules/pom.xml new file mode 100644 index 0000000000..c6dd6e1f25 --- /dev/null +++ b/ddd-modules/pom.xml @@ -0,0 +1,70 @@ + + + 4.0.0 + com.baeldung.dddmodules + ddd-modules + 1.0 + ddd-modules + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../ + + + + sharedkernel + infrastructure + shippingcontext + ordercontext + mainapp + + + + + + junit + junit + ${junit.version} + test + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${compiler.plugin.version} + + ${source.version} + ${target.version} + + + + + + + + 3.8.1 + 9 + 9 + UTF-8 + 3.12.2 + 1.0 + + + diff --git a/ddd-modules/sharedkernel/pom.xml b/ddd-modules/sharedkernel/pom.xml new file mode 100644 index 0000000000..a61f03a494 --- /dev/null +++ b/ddd-modules/sharedkernel/pom.xml @@ -0,0 +1,36 @@ + + + 4.0.0 + com.baeldung.dddmodules.sharedkernel + sharedkernel + 1.0 + jar + + + com.baeldung.dddmodules + dddmodules + 1.0 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${source.version} + ${target.version} + + + + + + + 9 + 9 + + + \ No newline at end of file diff --git a/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/events/ApplicationEvent.java b/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/events/ApplicationEvent.java new file mode 100644 index 0000000000..e3c3ebaf0e --- /dev/null +++ b/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/events/ApplicationEvent.java @@ -0,0 +1,21 @@ +package com.baeldung.dddmodules.sharedkernel.events; + +import java.util.Map; + +public abstract class ApplicationEvent { + protected Map payload; + + public abstract String getType(); + + public String getPayloadValue(String key) { + if (this.payload.containsKey(key)) { + return this.payload.get(key); + } + return ""; + } + + public ApplicationEvent(Map payload) { + this.payload = payload; + } +} + diff --git a/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/events/EventBus.java b/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/events/EventBus.java new file mode 100644 index 0000000000..b128b959e9 --- /dev/null +++ b/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/events/EventBus.java @@ -0,0 +1,9 @@ +package com.baeldung.dddmodules.sharedkernel.events; + +public interface EventBus { + void publish(E event); + + void subscribe(String eventType, EventSubscriber subscriber); + + void unsubscribe(String eventType, EventSubscriber subscriber); +} diff --git a/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/events/EventSubscriber.java b/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/events/EventSubscriber.java new file mode 100644 index 0000000000..0d6d48cc33 --- /dev/null +++ b/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/events/EventSubscriber.java @@ -0,0 +1,5 @@ +package com.baeldung.dddmodules.sharedkernel.events; + +public interface EventSubscriber { + void onEvent(E event); +} diff --git a/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/service/ApplicationService.java b/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/service/ApplicationService.java new file mode 100644 index 0000000000..5ef57ae269 --- /dev/null +++ b/ddd-modules/sharedkernel/src/main/java/com/baeldung/dddmodules/sharedkernel/service/ApplicationService.java @@ -0,0 +1,33 @@ +package com.baeldung.dddmodules.sharedkernel.service; + +import com.baeldung.dddmodules.sharedkernel.events.ApplicationEvent; +import com.baeldung.dddmodules.sharedkernel.events.EventBus; +import com.baeldung.dddmodules.sharedkernel.events.EventSubscriber; + +public interface ApplicationService { + + default void publishEvent(E event) { + EventBus eventBus = getEventBus(); + if (eventBus != null) { + eventBus.publish(event); + } + } + + default void subscribe(String eventType, EventSubscriber subscriber) { + EventBus eventBus = getEventBus(); + if (eventBus != null) { + eventBus.subscribe(eventType, subscriber); + } + } + + default void unsubscribe(String eventType, EventSubscriber subscriber) { + EventBus eventBus = getEventBus(); + if (eventBus != null) { + eventBus.unsubscribe(eventType, subscriber); + } + } + + EventBus getEventBus(); + + void setEventBus(EventBus eventBus); +} diff --git a/ddd-modules/sharedkernel/src/main/java/module-info.java b/ddd-modules/sharedkernel/src/main/java/module-info.java new file mode 100644 index 0000000000..aeb64f52c9 --- /dev/null +++ b/ddd-modules/sharedkernel/src/main/java/module-info.java @@ -0,0 +1,4 @@ +module com.baeldung.dddmodules.sharedkernel { + exports com.baeldung.dddmodules.sharedkernel.events; + exports com.baeldung.dddmodules.sharedkernel.service; +} diff --git a/ddd-modules/shippingcontext/pom.xml b/ddd-modules/shippingcontext/pom.xml new file mode 100644 index 0000000000..2096923f90 --- /dev/null +++ b/ddd-modules/shippingcontext/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + com.baeldung.dddmodules.shippingcontext + shippingcontext + 1.0 + jar + + + com.baeldung.dddmodules + dddmodules + 1.0 + + + + + com.baeldung.dddmodules.sharedkernel + sharedkernel + ${appmodules.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${source.version} + ${target.version} + + + + + + + 9 + 9 + + + \ No newline at end of file diff --git a/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/model/PackageItem.java b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/model/PackageItem.java new file mode 100644 index 0000000000..ed09a0f2a2 --- /dev/null +++ b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/model/PackageItem.java @@ -0,0 +1,37 @@ +package com.baeldung.dddmodules.shippingcontext.model; + +public class PackageItem { + private int productId; + private float weight; + private float estimatedValue; + + public PackageItem(int productId, float weight, float estimatedValue) { + this.productId = productId; + this.weight = weight; + this.estimatedValue = estimatedValue; + } + + public int getProductId() { + return productId; + } + + public void setProductId(int productId) { + this.productId = productId; + } + + public float getWeight() { + return weight; + } + + public void setWeight(float weight) { + this.weight = weight; + } + + public float getEstimatedValue() { + return estimatedValue; + } + + public void setEstimatedValue(float estimatedValue) { + this.estimatedValue = estimatedValue; + } +} diff --git a/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/model/Parcel.java b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/model/Parcel.java new file mode 100644 index 0000000000..70c4f06ac6 --- /dev/null +++ b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/model/Parcel.java @@ -0,0 +1,54 @@ +package com.baeldung.dddmodules.shippingcontext.model; + +import java.util.List; + +public class Parcel { + private int orderId; + private String address; + private String trackingId; + private List packageItems; + + public Parcel(int orderId, String address, List packageItems) { + this.orderId = orderId; + this.address = address; + this.packageItems = packageItems; + } + + public float calculateTotalWeight() { + return packageItems.stream().map(PackageItem::getWeight) + .reduce(0F, Float::sum); + } + + public boolean isTaxable() { + return calculateEstimatedValue() > 100; + } + + public float calculateEstimatedValue() { + return packageItems.stream().map(PackageItem::getWeight) + .reduce(0F, Float::sum); + } + + public int getOrderId() { + return orderId; + } + + public void setOrderId(int orderId) { + this.orderId = orderId; + } + + public String getTrackingId() { + return trackingId; + } + + public void setTrackingId(String trackingId) { + this.trackingId = trackingId; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/model/ShippableOrder.java b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/model/ShippableOrder.java new file mode 100644 index 0000000000..afeea2f472 --- /dev/null +++ b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/model/ShippableOrder.java @@ -0,0 +1,38 @@ +package com.baeldung.dddmodules.shippingcontext.model; + +import java.util.List; + +public class ShippableOrder { + private int orderId; + private String address; + private List packageItems; + + public ShippableOrder(int orderId, List packageItems) { + this.orderId = orderId; + this.packageItems = packageItems; + } + + public int getOrderId() { + return orderId; + } + + public void setOrderId(int orderId) { + this.orderId = orderId; + } + + public List getPackageItems() { + return packageItems; + } + + public void setPackageItems(List packageItems) { + this.packageItems = packageItems; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/repository/ShippingOrderRepository.java b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/repository/ShippingOrderRepository.java new file mode 100644 index 0000000000..b1a643f989 --- /dev/null +++ b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/repository/ShippingOrderRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.dddmodules.shippingcontext.repository; + +import com.baeldung.dddmodules.shippingcontext.model.ShippableOrder; + +import java.util.Optional; + +public interface ShippingOrderRepository { + Optional findShippableOrder(int orderId); +} diff --git a/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/service/ParcelShippingService.java b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/service/ParcelShippingService.java new file mode 100644 index 0000000000..05f261612e --- /dev/null +++ b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/service/ParcelShippingService.java @@ -0,0 +1,63 @@ +package com.baeldung.dddmodules.shippingcontext.service; + +import com.baeldung.dddmodules.sharedkernel.events.ApplicationEvent; +import com.baeldung.dddmodules.sharedkernel.events.EventBus; +import com.baeldung.dddmodules.sharedkernel.events.EventSubscriber; +import com.baeldung.dddmodules.shippingcontext.model.Parcel; +import com.baeldung.dddmodules.shippingcontext.model.ShippableOrder; +import com.baeldung.dddmodules.shippingcontext.repository.ShippingOrderRepository; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class ParcelShippingService implements ShippingService { + public static final String EVENT_ORDER_READY_FOR_SHIPMENT = "OrderReadyForShipmentEvent"; + private ShippingOrderRepository orderRepository; + private EventBus eventBus; + private Map shippedParcels = new HashMap<>(); + + @Override + public void shipOrder(int orderId) { + Optional order = this.orderRepository.findShippableOrder(orderId); + order.ifPresent(completedOrder -> { + Parcel parcel = new Parcel(completedOrder.getOrderId(), completedOrder.getAddress(), completedOrder.getPackageItems()); + if (parcel.isTaxable()) { + // Calculate additional taxes + } + // Ship parcel + this.shippedParcels.put(completedOrder.getOrderId(), parcel); + }); + } + + @Override + public void listenToOrderEvents() { + this.eventBus.subscribe(EVENT_ORDER_READY_FOR_SHIPMENT, new EventSubscriber() { + @Override + public void onEvent(E event) { + shipOrder(Integer.parseInt(event.getPayloadValue("order_id"))); + } + }); + } + + @Override + public Optional getParcelByOrderId(int orderId) { + return Optional.ofNullable(this.shippedParcels.get(orderId)); + } + + public void setOrderRepository(ShippingOrderRepository orderRepository) { + this.orderRepository = orderRepository; + } + + @Override + public EventBus getEventBus() { + return eventBus; + } + + @Override + public void setEventBus(EventBus eventBus) { + this.eventBus = eventBus; + } + + +} diff --git a/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/service/ShippingService.java b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/service/ShippingService.java new file mode 100644 index 0000000000..a2f0095c43 --- /dev/null +++ b/ddd-modules/shippingcontext/src/main/java/com/baeldung/dddmodules/shippingcontext/service/ShippingService.java @@ -0,0 +1,17 @@ +package com.baeldung.dddmodules.shippingcontext.service; + +import com.baeldung.dddmodules.sharedkernel.service.ApplicationService; +import com.baeldung.dddmodules.shippingcontext.model.Parcel; +import com.baeldung.dddmodules.shippingcontext.repository.ShippingOrderRepository; + +import java.util.Optional; + +public interface ShippingService extends ApplicationService { + void shipOrder(int orderId); + + void listenToOrderEvents(); + + Optional getParcelByOrderId(int orderId); + + void setOrderRepository(ShippingOrderRepository orderRepository); +} diff --git a/ddd-modules/shippingcontext/src/main/java/module-info.java b/ddd-modules/shippingcontext/src/main/java/module-info.java new file mode 100644 index 0000000000..a5ec1ca435 --- /dev/null +++ b/ddd-modules/shippingcontext/src/main/java/module-info.java @@ -0,0 +1,8 @@ +module com.baeldung.dddmodules.shippingcontext { + requires com.baeldung.dddmodules.sharedkernel; + exports com.baeldung.dddmodules.shippingcontext.service; + exports com.baeldung.dddmodules.shippingcontext.model; + exports com.baeldung.dddmodules.shippingcontext.repository; + provides com.baeldung.dddmodules.shippingcontext.service.ShippingService + with com.baeldung.dddmodules.shippingcontext.service.ParcelShippingService; +} diff --git a/ddd/README.md b/ddd/README.md index daeb663e3b..ad84dc40b2 100644 --- a/ddd/README.md +++ b/ddd/README.md @@ -6,4 +6,4 @@ This module contains articles about Domain-driven Design (DDD) - [Persisting DDD Aggregates](https://www.baeldung.com/spring-persisting-ddd-aggregates) - [Double Dispatch in DDD](https://www.baeldung.com/ddd-double-dispatch) -- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) +- [Organizing Layers Using Hexagonal Architecture, DDD, and Spring](https://www.baeldung.com/hexagonal-architecture-ddd-spring) diff --git a/ddd/pom.xml b/ddd/pom.xml index 9a0523a4c6..7f3c417b71 100644 --- a/ddd/pom.xml +++ b/ddd/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.ddd ddd @@ -20,6 +22,10 @@ org.springframework.boot spring-boot-starter-data-mongodb + + org.springframework.boot + spring-boot-starter-data-cassandra + org.junit.jupiter junit-jupiter-api @@ -93,4 +99,4 @@ 2.0.6.RELEASE - \ No newline at end of file + diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java index 988f96042b..235021b03e 100644 --- a/ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java @@ -1,13 +1,37 @@ package com.baeldung.dddhexagonalspring; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; +import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.PropertySource; +import com.baeldung.dddhexagonalspring.application.cli.CliOrderController; + @SpringBootApplication @PropertySource(value = { "classpath:ddd-layers.properties" }) -public class DomainLayerApplication { +public class DomainLayerApplication implements CommandLineRunner { + public static void main(final String[] args) { - SpringApplication.run(DomainLayerApplication.class, args); + SpringApplication application = new SpringApplication(DomainLayerApplication.class); + // uncomment to run just the console application + // application.setWebApplicationType(WebApplicationType.NONE); + application.run(args); + } + + @Autowired + public CliOrderController orderController; + + @Autowired + public ConfigurableApplicationContext context; + + @Override + public void run(String... args) throws Exception { + orderController.createCompleteOrder(); + orderController.createIncompleteOrder(); + // uncomment to stop the context when execution is done + // context.close(); } } diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java new file mode 100644 index 0000000000..3d595533f3 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java @@ -0,0 +1,47 @@ +package com.baeldung.dddhexagonalspring.application.cli; + +import java.math.BigDecimal; +import java.util.UUID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.baeldung.dddhexagonalspring.domain.Product; +import com.baeldung.dddhexagonalspring.domain.service.OrderService; + +@Component +public class CliOrderController { + + private static final Logger LOG = LoggerFactory.getLogger(CliOrderController.class); + + private final OrderService orderService; + + @Autowired + public CliOrderController(OrderService orderService) { + this.orderService = orderService; + } + + public void createCompleteOrder() { + LOG.info("<>"); + UUID orderId = createOrder(); + orderService.completeOrder(orderId); + } + + public void createIncompleteOrder() { + LOG.info("<>"); + UUID orderId = createOrder(); + } + + private UUID createOrder() { + LOG.info("Placing a new order with two products"); + Product mobilePhone = new Product(UUID.randomUUID(), BigDecimal.valueOf(200), "mobile"); + Product razor = new Product(UUID.randomUUID(), BigDecimal.valueOf(50), "razor"); + LOG.info("Creating order with mobile phone"); + UUID orderId = orderService.createOrder(mobilePhone); + LOG.info("Adding a razor to the order"); + orderService.addProduct(orderId, razor); + return orderId; + } +} diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/controller/OrderController.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/controller/OrderController.java deleted file mode 100644 index 80ba36d01b..0000000000 --- a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/controller/OrderController.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.dddhexagonalspring.application.controller; - -import com.baeldung.dddhexagonalspring.application.request.AddProductRequest; -import com.baeldung.dddhexagonalspring.application.request.CreateOrderRequest; -import com.baeldung.dddhexagonalspring.application.response.CreateOrderResponse; -import com.baeldung.dddhexagonalspring.domain.service.OrderService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.*; - -import java.util.UUID; - -@RestController -@RequestMapping("/orders") -public class OrderController { - - private final OrderService orderService; - - @Autowired - public OrderController(OrderService orderService) { - this.orderService = orderService; - } - - @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) - CreateOrderResponse createOrder(@RequestBody final CreateOrderRequest createOrderRequest) { - final UUID id = orderService.createOrder(createOrderRequest.getProduct()); - - return new CreateOrderResponse(id); - } - - @PostMapping(value = "/{id}/products", consumes = MediaType.APPLICATION_JSON_VALUE) - void addProduct(@PathVariable final UUID id, @RequestBody final AddProductRequest addProductRequest) { - orderService.addProduct(id, addProductRequest.getProduct()); - } - - @DeleteMapping(value = "/{id}/products", consumes = MediaType.APPLICATION_JSON_VALUE) - void deleteProduct(@PathVariable final UUID id, @RequestParam final UUID productId) { - orderService.deleteProduct(id, productId); - } - - @PostMapping("/{id}/complete") - void completeOrder(@PathVariable final UUID id) { - orderService.completeOrder(id); - } -} diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java new file mode 100644 index 0000000000..12bb8ddea4 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java @@ -0,0 +1,45 @@ +package com.baeldung.dddhexagonalspring.application.rest; + +import com.baeldung.dddhexagonalspring.application.request.AddProductRequest; +import com.baeldung.dddhexagonalspring.application.request.CreateOrderRequest; +import com.baeldung.dddhexagonalspring.application.response.CreateOrderResponse; +import com.baeldung.dddhexagonalspring.domain.service.OrderService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.UUID; + +@RestController +@RequestMapping("/orders") +public class OrderController { + + private final OrderService orderService; + + @Autowired + public OrderController(OrderService orderService) { + this.orderService = orderService; + } + + @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) + CreateOrderResponse createOrder(@RequestBody final CreateOrderRequest createOrderRequest) { + final UUID id = orderService.createOrder(createOrderRequest.getProduct()); + + return new CreateOrderResponse(id); + } + + @PostMapping(value = "/{id}/products", consumes = MediaType.APPLICATION_JSON_VALUE) + void addProduct(@PathVariable final UUID id, @RequestBody final AddProductRequest addProductRequest) { + orderService.addProduct(id, addProductRequest.getProduct()); + } + + @DeleteMapping(value = "/{id}/products", consumes = MediaType.APPLICATION_JSON_VALUE) + void deleteProduct(@PathVariable final UUID id, @RequestParam final UUID productId) { + orderService.deleteProduct(id, productId); + } + + @PostMapping("/{id}/complete") + void completeOrder(@PathVariable final UUID id) { + orderService.completeOrder(id); + } +} diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java index 7d40007411..a8745eadbe 100644 --- a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java @@ -4,6 +4,7 @@ import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.UUID; public class Order { @@ -40,13 +41,11 @@ public class Order { } private OrderItem getOrderItem(final UUID id) { - return orderItems - .stream() - .filter(orderItem -> orderItem - .getProductId() - .equals(id)) - .findFirst() - .orElseThrow(() -> new DomainException("Product with " + id + " doesn't exist.")); + return orderItems.stream() + .filter(orderItem -> orderItem.getProductId() + .equals(id)) + .findFirst() + .orElseThrow(() -> new DomainException("Product with " + id + " doesn't exist.")); } private void validateState() { @@ -77,6 +76,21 @@ public class Order { return Collections.unmodifiableList(orderItems); } + @Override + public int hashCode() { + return Objects.hash(id, orderItems, price, status); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!(obj instanceof Order)) + return false; + Order other = (Order) obj; + return Objects.equals(id, other.id) && Objects.equals(orderItems, other.orderItems) && Objects.equals(price, other.price) && status == other.status; + } + private Order() { } } diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java new file mode 100644 index 0000000000..3b5911979a --- /dev/null +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java @@ -0,0 +1,10 @@ +package com.baeldung.dddhexagonalspring.infrastracture.configuration; + +import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories; + +import com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra.SpringDataCassandraOrderRepository; + +@EnableCassandraRepositories(basePackageClasses = SpringDataCassandraOrderRepository.class) +public class CassandraConfiguration { + +} diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java index fd76b2eb0e..8ec6daf370 100644 --- a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java @@ -1,8 +1,9 @@ package com.baeldung.dddhexagonalspring.infrastracture.configuration; -import com.baeldung.dddhexagonalspring.infrastracture.repository.SpringDataOrderRepository; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; -@EnableMongoRepositories(basePackageClasses = SpringDataOrderRepository.class) +import com.baeldung.dddhexagonalspring.infrastracture.repository.mongo.SpringDataMongoOrderRepository; + +@EnableMongoRepositories(basePackageClasses = SpringDataMongoOrderRepository.class) public class MongoDBConfiguration { } diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/SpringDataOrderRepository.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/SpringDataOrderRepository.java deleted file mode 100644 index 0279a5ce4a..0000000000 --- a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/SpringDataOrderRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.dddhexagonalspring.infrastracture.repository; - -import com.baeldung.dddhexagonalspring.domain.Order; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.stereotype.Repository; - -import java.util.UUID; - -@Repository -public interface SpringDataOrderRepository extends MongoRepository { -} diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java new file mode 100644 index 0000000000..686fc428e7 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java @@ -0,0 +1,38 @@ +package com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra; + +import java.util.Optional; +import java.util.UUID; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.baeldung.dddhexagonalspring.domain.Order; +import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository; + +@Component +public class CassandraDbOrderRepository implements OrderRepository { + + private final SpringDataCassandraOrderRepository orderRepository; + + @Autowired + public CassandraDbOrderRepository(SpringDataCassandraOrderRepository orderRepository) { + this.orderRepository = orderRepository; + } + + @Override + public Optional findById(UUID id) { + Optional orderEntity = orderRepository.findById(id); + if (orderEntity.isPresent()) { + return Optional.of(orderEntity.get() + .toOrder()); + } else { + return Optional.empty(); + } + } + + @Override + public void save(Order order) { + orderRepository.save(new OrderEntity(order)); + } + +} diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java new file mode 100644 index 0000000000..b9841a4433 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java @@ -0,0 +1,75 @@ +package com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra; + +import java.math.BigDecimal; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.springframework.data.cassandra.core.mapping.PrimaryKey; + +import com.baeldung.dddhexagonalspring.domain.Order; +import com.baeldung.dddhexagonalspring.domain.OrderItem; +import com.baeldung.dddhexagonalspring.domain.OrderStatus; +import com.baeldung.dddhexagonalspring.domain.Product; + +public class OrderEntity { + + @PrimaryKey + private UUID id; + private OrderStatus status; + private List orderItemEntities; + private BigDecimal price; + + public OrderEntity(UUID id, OrderStatus status, List orderItemEntities, BigDecimal price) { + this.id = id; + this.status = status; + this.orderItemEntities = orderItemEntities; + this.price = price; + } + + public OrderEntity() { + } + + public OrderEntity(Order order) { + this.id = order.getId(); + this.price = order.getPrice(); + this.status = order.getStatus(); + this.orderItemEntities = order.getOrderItems() + .stream() + .map(OrderItemEntity::new) + .collect(Collectors.toList()); + + } + + public Order toOrder() { + List orderItems = orderItemEntities.stream() + .map(OrderItemEntity::toOrderItem) + .collect(Collectors.toList()); + List namelessProducts = orderItems.stream() + .map(orderItem -> new Product(orderItem.getProductId(), orderItem.getPrice(), "")) + .collect(Collectors.toList()); + Order order = new Order(id, namelessProducts.remove(0)); + namelessProducts.forEach(product -> order.addOrder(product)); + if (status == OrderStatus.COMPLETED) { + order.complete(); + } + return order; + } + + public UUID getId() { + return id; + } + + public OrderStatus getStatus() { + return status; + } + + public List getOrderItems() { + return orderItemEntities; + } + + public BigDecimal getPrice() { + return price; + } + +} diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java new file mode 100644 index 0000000000..2cf8ac7845 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java @@ -0,0 +1,44 @@ +package com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra; + +import java.math.BigDecimal; +import java.util.UUID; + +import org.springframework.data.cassandra.core.mapping.UserDefinedType; + +import com.baeldung.dddhexagonalspring.domain.OrderItem; +import com.baeldung.dddhexagonalspring.domain.Product; + +@UserDefinedType +public class OrderItemEntity { + + private UUID productId; + private BigDecimal price; + + public OrderItemEntity() { + } + + public OrderItemEntity(final OrderItem orderItem) { + this.productId = orderItem.getProductId(); + this.price = orderItem.getPrice(); + } + + public OrderItem toOrderItem() { + return new OrderItem(new Product(productId, price, "")); + } + + public UUID getProductId() { + return productId; + } + + public void setProductId(UUID productId) { + this.productId = productId; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } +} diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java new file mode 100644 index 0000000000..93cd7ab83f --- /dev/null +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra; + +import java.util.UUID; + +import org.springframework.data.cassandra.repository.CassandraRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SpringDataCassandraOrderRepository extends CassandraRepository { +} diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepository.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java similarity index 75% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepository.java rename to ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java index 3123ef3e2f..b48b738cbd 100644 --- a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepository.java +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java @@ -1,20 +1,23 @@ -package com.baeldung.dddhexagonalspring.infrastracture.repository; - -import com.baeldung.dddhexagonalspring.domain.Order; -import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; +package com.baeldung.dddhexagonalspring.infrastracture.repository.mongo; import java.util.Optional; import java.util.UUID; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; + +import com.baeldung.dddhexagonalspring.domain.Order; +import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository; + @Component +@Primary public class MongoDbOrderRepository implements OrderRepository { - private final SpringDataOrderRepository orderRepository; + private final SpringDataMongoOrderRepository orderRepository; @Autowired - public MongoDbOrderRepository(final SpringDataOrderRepository orderRepository) { + public MongoDbOrderRepository(final SpringDataMongoOrderRepository orderRepository) { this.orderRepository = orderRepository; } diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java new file mode 100644 index 0000000000..73aa74e7d7 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.dddhexagonalspring.infrastracture.repository.mongo; + +import com.baeldung.dddhexagonalspring.domain.Order; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +import java.util.UUID; + +@Repository +public interface SpringDataMongoOrderRepository extends MongoRepository { +} diff --git a/ddd/src/main/resources/ddd-layers.properties b/ddd/src/main/resources/ddd-layers.properties index 0479996b17..412c24eef7 100644 --- a/ddd/src/main/resources/ddd-layers.properties +++ b/ddd/src/main/resources/ddd-layers.properties @@ -1,5 +1,12 @@ +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=order-database spring.data.mongodb.username=order -spring.data.mongodb.password=order \ No newline at end of file +spring.data.mongodb.password=order + +spring.data.cassandra.keyspaceName=order_database +spring.data.cassandra.username=cassandra +spring.data.cassandra.password=cassandra +spring.data.cassandra.contactPoints=localhost +spring.data.cassandra.port=9042 \ No newline at end of file diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryIntegrationTest.java b/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryIntegrationTest.java new file mode 100644 index 0000000000..668d1e5e34 --- /dev/null +++ b/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.dddhexagonalspring.infrastracture.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +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.junit.jupiter.SpringJUnitConfig; + +import com.baeldung.dddhexagonalspring.domain.Order; +import com.baeldung.dddhexagonalspring.domain.Product; +import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository; +import com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra.SpringDataCassandraOrderRepository; + +@SpringJUnitConfig +@SpringBootTest +@TestPropertySource("classpath:ddd-layers-test.properties") +class CassandraDbOrderRepositoryIntegrationTest { + + @Autowired + private SpringDataCassandraOrderRepository cassandraOrderRepository; + + @Autowired + private OrderRepository orderRepository; + + @AfterEach + void cleanUp() { + cassandraOrderRepository.deleteAll(); + } + + @Test + void shouldFindById_thenReturnOrder() { + + // given + final UUID id = UUID.randomUUID(); + final Order order = createOrder(id); + order.addOrder(new Product(UUID.randomUUID(), BigDecimal.TEN, "second")); + order.complete(); + + // when + orderRepository.save(order); + + final Optional result = orderRepository.findById(id); + + assertEquals(order, result.get()); + } + + private Order createOrder(UUID id) { + return new Order(id, new Product(UUID.randomUUID(), BigDecimal.TEN, "product")); + } +} \ No newline at end of file diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryIntegrationTest.java b/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9a7736c419 --- /dev/null +++ b/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryIntegrationTest.java @@ -0,0 +1,55 @@ +package com.baeldung.dddhexagonalspring.infrastracture.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +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.junit.jupiter.SpringJUnitConfig; + +import com.baeldung.dddhexagonalspring.domain.Order; +import com.baeldung.dddhexagonalspring.domain.Product; +import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository; +import com.baeldung.dddhexagonalspring.infrastracture.repository.mongo.SpringDataMongoOrderRepository; + +@SpringJUnitConfig +@SpringBootTest +@TestPropertySource("classpath:ddd-layers-test.properties") +class MongoDbOrderRepositoryIntegrationTest { + + @Autowired + private SpringDataMongoOrderRepository mongoOrderRepository; + + @Autowired + private OrderRepository orderRepository; + + @AfterEach + void cleanUp() { + mongoOrderRepository.deleteAll(); + } + + @Test + void shouldFindById_thenReturnOrder() { + + // given + final UUID id = UUID.randomUUID(); + final Order order = createOrder(id); + + // when + orderRepository.save(order); + + final Optional result = orderRepository.findById(id); + + assertEquals(order, result.get()); + } + + private Order createOrder(UUID id) { + return new Order(id, new Product(UUID.randomUUID(), BigDecimal.TEN, "product")); + } +} \ No newline at end of file diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java b/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java index 8f7e8260a3..4c75daaa4d 100644 --- a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java +++ b/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java @@ -2,6 +2,9 @@ package com.baeldung.dddhexagonalspring.infrastracture.repository; import com.baeldung.dddhexagonalspring.domain.Order; import com.baeldung.dddhexagonalspring.domain.Product; +import com.baeldung.dddhexagonalspring.infrastracture.repository.mongo.MongoDbOrderRepository; +import com.baeldung.dddhexagonalspring.infrastracture.repository.mongo.SpringDataMongoOrderRepository; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -14,12 +17,12 @@ import static org.mockito.Mockito.*; class MongoDbOrderRepositoryUnitTest { - private SpringDataOrderRepository springDataOrderRepository; + private SpringDataMongoOrderRepository springDataOrderRepository; private MongoDbOrderRepository tested; @BeforeEach - void setUp(){ - springDataOrderRepository = mock(SpringDataOrderRepository.class); + void setUp() { + springDataOrderRepository = mock(SpringDataMongoOrderRepository.class); tested = new MongoDbOrderRepository(springDataOrderRepository); } diff --git a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md b/ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md index e0337498fc..1355514a3d 100644 --- a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md +++ b/ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md @@ -4,4 +4,6 @@ To run this project, follow these steps: * Run the application database by executing `docker-compose up` in this directory. * Launch the Spring Boot Application (DomainLayerApplication). -* By default, application will connect to this database (configuration in *ddd-layers.properties*) \ No newline at end of file +* By default, the application will connect to the one of the two databases (configuration in *ddd-layers.properties*) + * check `CassandraDbOrderRepository.java` and `MongoDbOrderRepository.java` + * switch between the databases by making one of the above beans primary using the `@Primary` annotation \ No newline at end of file diff --git a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql b/ddd/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql new file mode 100644 index 0000000000..cbb22d2525 --- /dev/null +++ b/ddd/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql @@ -0,0 +1,12 @@ +CREATE KEYSPACE IF NOT exists order_database +WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}; + +CREATE TYPE IF NOT EXISTS order_database.orderitementity (productid uuid, price decimal); + +CREATE TABLE IF NOT EXISTS order_database.orderentity( + id uuid, + status text, + orderitementities list>, + price decimal, + primary key(id) +); diff --git a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml b/ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml index d85ddf4a0e..7de0d30d43 100644 --- a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml +++ b/ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml @@ -3,6 +3,7 @@ version: '3' services: order-mongo-database: image: mongo:3.4.13 + container_name: order-mongo-db restart: always ports: - 27017:27017 @@ -11,4 +12,19 @@ services: MONGO_INITDB_ROOT_PASSWORD: admin MONGO_INITDB_DATABASE: order-database volumes: - - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro \ No newline at end of file + - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro + order-cassandra-database: + image: cassandra:3.11.5 + container_name: order-cassandra-db + restart: always + ports: + - 9042:9042 + order-cassandra-init: + image: cassandra:3.11.5 + container_name: order-cassandra-db-init + depends_on: + - order-cassandra-database + volumes: + - ./cassandra-init.cql:/cassandra-init.cql:ro + command: bin/bash -c "echo Initializing cassandra schema... && sleep 30 && cqlsh -u cassandra -p cassandra -f cassandra-init.cql order-cassandra-db" + \ No newline at end of file diff --git a/ddd/src/test/resources/ddd-layers-test.properties b/ddd/src/test/resources/ddd-layers-test.properties new file mode 100644 index 0000000000..d41689d91b --- /dev/null +++ b/ddd/src/test/resources/ddd-layers-test.properties @@ -0,0 +1,12 @@ +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration +spring.data.mongodb.host=127.0.0.1 +spring.data.mongodb.port=27017 +spring.data.mongodb.database=order-database +spring.data.mongodb.username=order +spring.data.mongodb.password=order + +spring.data.cassandra.keyspaceName=order_database +spring.data.cassandra.username=cassandra +spring.data.cassandra.password=cassandra +spring.data.cassandra.contactPoints=127.0.0.1 +spring.data.cassandra.port=9042 \ No newline at end of file diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index 0e84fa1516..c8fa18cbd4 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.deeplearning4j deeplearning4j @@ -44,12 +46,13 @@ org.apache.httpcomponents httpclient - 4.3.5 + ${httpclient.version} 0.9.1 + 4.3.5 diff --git a/disruptor/pom.xml b/disruptor/pom.xml index 94be78fad6..31fc28986b 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 disruptor 0.1.0-SNAPSHOT diff --git a/dozer/pom.xml b/dozer/pom.xml index e307354603..0fdf7f6fba 100644 --- a/dozer/pom.xml +++ b/dozer/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 dozer 1.0 diff --git a/drools/pom.xml b/drools/pom.xml index b4421ff2e3..e0a7b52938 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 drools drools diff --git a/dropwizard/README.md b/dropwizard/README.md new file mode 100644 index 0000000000..76311ebbb3 --- /dev/null +++ b/dropwizard/README.md @@ -0,0 +1,5 @@ +# Dropwizard + +### Relevant Articles: + +- [Introduction to Dropwizard](https://www.baeldung.com/java-dropwizard) diff --git a/dropwizard/pom.xml b/dropwizard/pom.xml new file mode 100644 index 0000000000..c3e1a4e841 --- /dev/null +++ b/dropwizard/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + dropwizard + 0.0.1-SNAPSHOT + dropwizard + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + io.dropwizard + dropwizard-core + ${dropwizard.version} + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + true + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + package + + shade + + + + + + com.baeldung.dropwizard.introduction.IntroductionApplication + + + + + + + + + + + 2.0.0 + + + \ No newline at end of file diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/IntroductionApplication.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/IntroductionApplication.java new file mode 100644 index 0000000000..d9af590017 --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/IntroductionApplication.java @@ -0,0 +1,51 @@ +package com.baeldung.dropwizard.introduction; + +import com.baeldung.dropwizard.introduction.configuration.ApplicationHealthCheck; +import com.baeldung.dropwizard.introduction.configuration.BasicConfiguration; +import com.baeldung.dropwizard.introduction.domain.Brand; +import com.baeldung.dropwizard.introduction.repository.BrandRepository; +import com.baeldung.dropwizard.introduction.resource.BrandResource; +import io.dropwizard.Application; +import io.dropwizard.configuration.ResourceConfigurationSourceProvider; +import io.dropwizard.setup.Bootstrap; +import io.dropwizard.setup.Environment; + +import java.util.ArrayList; +import java.util.List; + +public class IntroductionApplication extends Application { + + public static void main(final String[] args) throws Exception { + new IntroductionApplication().run("server", "introduction-config.yml"); + } + + @Override + public void run(final BasicConfiguration basicConfiguration, final Environment environment) { + final int defaultSize = basicConfiguration.getDefaultSize(); + final BrandRepository brandRepository = new BrandRepository(initBrands()); + final BrandResource brandResource = new BrandResource(defaultSize, brandRepository); + environment + .jersey() + .register(brandResource); + + final ApplicationHealthCheck healthCheck = new ApplicationHealthCheck(); + environment + .healthChecks() + .register("application", healthCheck); + } + + @Override + public void initialize(final Bootstrap bootstrap) { + bootstrap.setConfigurationSourceProvider(new ResourceConfigurationSourceProvider()); + super.initialize(bootstrap); + } + + private List initBrands() { + final List brands = new ArrayList<>(); + brands.add(new Brand(1L, "Brand1")); + brands.add(new Brand(2L, "Brand2")); + brands.add(new Brand(3L, "Brand3")); + + return brands; + } +} diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/ApplicationHealthCheck.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/ApplicationHealthCheck.java new file mode 100644 index 0000000000..bf4b710937 --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/ApplicationHealthCheck.java @@ -0,0 +1,10 @@ +package com.baeldung.dropwizard.introduction.configuration; + +import com.codahale.metrics.health.HealthCheck; + +public class ApplicationHealthCheck extends HealthCheck { + @Override + protected Result check() throws Exception { + return Result.healthy(); + } +} diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/BasicConfiguration.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/BasicConfiguration.java new file mode 100644 index 0000000000..5098f89d62 --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/BasicConfiguration.java @@ -0,0 +1,20 @@ +package com.baeldung.dropwizard.introduction.configuration; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.dropwizard.Configuration; + +import javax.validation.constraints.NotNull; + +public class BasicConfiguration extends Configuration { + @NotNull private final int defaultSize; + + @JsonCreator + public BasicConfiguration(@JsonProperty("defaultSize") final int defaultSize) { + this.defaultSize = defaultSize; + } + + public int getDefaultSize() { + return defaultSize; + } +} diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/domain/Brand.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/domain/Brand.java new file mode 100644 index 0000000000..c83f67bb6e --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/domain/Brand.java @@ -0,0 +1,19 @@ +package com.baeldung.dropwizard.introduction.domain; + +public class Brand { + private final Long id; + private final String name; + + public Brand(final Long id, final String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } +} diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/repository/BrandRepository.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/repository/BrandRepository.java new file mode 100644 index 0000000000..3f187df3de --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/repository/BrandRepository.java @@ -0,0 +1,32 @@ +package com.baeldung.dropwizard.introduction.repository; + +import com.baeldung.dropwizard.introduction.domain.Brand; +import com.google.common.collect.ImmutableList; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +public class BrandRepository { + private final List brands; + + public BrandRepository(final List brands) { + this.brands = ImmutableList.copyOf(brands); + } + + public List findAll(final int size) { + return brands + .stream() + .limit(size) + .collect(Collectors.toList()); + } + + public Optional findById(final Long id) { + return brands + .stream() + .filter(brand -> brand + .getId() + .equals(id)) + .findFirst(); + } +} diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/resource/BrandResource.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/resource/BrandResource.java new file mode 100644 index 0000000000..5f97e26faf --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/resource/BrandResource.java @@ -0,0 +1,35 @@ +package com.baeldung.dropwizard.introduction.resource; + +import com.baeldung.dropwizard.introduction.domain.Brand; +import com.baeldung.dropwizard.introduction.repository.BrandRepository; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.List; +import java.util.Optional; + +@Path("/brands") +@Produces(MediaType.APPLICATION_JSON) +public class BrandResource { + private final int defaultSize; + private final BrandRepository brandRepository; + + public BrandResource(final int defaultSize, final BrandRepository brandRepository) { + this.defaultSize = defaultSize; + this.brandRepository = brandRepository; + + } + + @GET + public List getBrands(@QueryParam("size") final Optional size) { + return brandRepository.findAll(size.orElse(defaultSize)); + } + + @GET + @Path("/{id}") + public Brand getById(@PathParam("id") final Long id) { + return brandRepository + .findById(id) + .orElseThrow(RuntimeException::new); + } +} diff --git a/dropwizard/src/main/resources/introduction-config.yml b/dropwizard/src/main/resources/introduction-config.yml new file mode 100644 index 0000000000..02ff36de05 --- /dev/null +++ b/dropwizard/src/main/resources/introduction-config.yml @@ -0,0 +1 @@ +defaultSize: 5 \ No newline at end of file diff --git a/dropwizard/src/test/java/com/baeldung/dropwizard/introduction/repository/BrandRepositoryUnitTest.java b/dropwizard/src/test/java/com/baeldung/dropwizard/introduction/repository/BrandRepositoryUnitTest.java new file mode 100644 index 0000000000..b996883ee5 --- /dev/null +++ b/dropwizard/src/test/java/com/baeldung/dropwizard/introduction/repository/BrandRepositoryUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.dropwizard.introduction.repository; + +import com.baeldung.dropwizard.introduction.domain.Brand; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BrandRepositoryUnitTest { + + private static final Brand BRAND_1 = new Brand(1L, "Brand1"); + + private final BrandRepository brandRepository = new BrandRepository(getBrands()); + + @Test + void givenSize_whenFindingAll_thenReturnList() { + final int size = 2; + + final List result = brandRepository.findAll(size); + + assertEquals(size, result.size()); + } + + @Test + void givenId_whenFindingById_thenReturnFoundBrand() { + final Long id = BRAND_1.getId(); + + final Optional result = brandRepository.findById(id); + + Assertions.assertTrue(result.isPresent()); + assertEquals(BRAND_1, result.get()); + } + + + private List getBrands() { + final List brands = new ArrayList<>(); + brands.add(BRAND_1); + brands.add(new Brand(2L, "Brand2")); + brands.add(new Brand(3L, "Brand3")); + + return brands; + } +} \ No newline at end of file diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 9a7aceb9e5..cca1b3a3d1 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 dubbo dubbo diff --git a/ethereum/pom.xml b/ethereum/pom.xml index 6fc31208d2..5953195123 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.ethereum ethereum @@ -159,8 +161,8 @@ org.hamcrest - hamcrest-library - ${org.hamcrest.version} + hamcrest + ${hamcrest.version} test @@ -175,10 +177,10 @@ maven-compiler-plugin - 3.1 + ${compiler.plugin.version} - 1.8 - 1.8 + ${java.version} + ${java.version} @@ -189,7 +191,7 @@ org.apache.maven.plugins maven-war-plugin - 3.0.0 + ${maven-war-plugin.version} src/main/webapp false @@ -215,5 +217,6 @@ 1.2.3 1.7.25 2.0.4.RELEASE + 3.1 diff --git a/feign/pom.xml b/feign/pom.xml index 6dc8e7bafa..4b994be1f2 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.feign feign diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml index 8f7d058db7..566eed95d8 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 flyway-cdi-extension 1.0-SNAPSHOT diff --git a/geotools/pom.xml b/geotools/pom.xml index 71489bdf94..46913daa69 100644 --- a/geotools/pom.xml +++ b/geotools/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 geotools 0.0.1-SNAPSHOT diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml index 15f7f5c824..1e474b5dd0 100644 --- a/google-cloud/pom.xml +++ b/google-cloud/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 google-cloud 0.1-SNAPSHOT diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index e79b43c5e5..6fdcae4f75 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 google-web-toolkit @@ -53,8 +54,7 @@ - + ${project.build.directory}/${project.build.finalName}/WEB-INF/classes @@ -63,7 +63,7 @@ net.ltgt.gwt.maven gwt-maven-plugin - 1.0-rc-8 + ${gwt.plugin.version} @@ -76,9 +76,8 @@ com.baeldung.Google_web_toolkit Google_web_toolkit true - - 1.8 + + ${maven.compiler.source} @@ -98,7 +97,7 @@ maven-surefire-plugin - 2.17 + ${surefire.plugin.version} true @@ -109,9 +108,8 @@ - + 1.8 1.8 @@ -119,6 +117,8 @@ UTF-8 UTF-8 2.8.2 + 1.0-rc-8 + 2.17 diff --git a/gradle-6/.gitignore b/gradle-6/.gitignore new file mode 100644 index 0000000000..6987887957 --- /dev/null +++ b/gradle-6/.gitignore @@ -0,0 +1,18 @@ + +# Gradle + +.gradle +build + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 +# gradle/wrapper/gradle-wrapper.properties + diff --git a/gradle-6/README.md b/gradle-6/README.md new file mode 100644 index 0000000000..a1ea96ad83 --- /dev/null +++ b/gradle-6/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [What’s New in Gradle 6.0](https://www.baeldung.com/gradle-6-features) diff --git a/gradle-6/build.gradle.kts b/gradle-6/build.gradle.kts new file mode 100644 index 0000000000..fb3c3f88a2 --- /dev/null +++ b/gradle-6/build.gradle.kts @@ -0,0 +1,5 @@ +subprojects { + repositories { + mavenCentral() + } +} \ No newline at end of file diff --git a/gradle-6/configuration-avoidance/build.gradle.kts b/gradle-6/configuration-avoidance/build.gradle.kts new file mode 100644 index 0000000000..e84f08bf93 --- /dev/null +++ b/gradle-6/configuration-avoidance/build.gradle.kts @@ -0,0 +1,37 @@ +plugins { + base +} + +description = """ + Demonstrates Gradle Configuraiton Avoidance API. Creates a new configuration "extralibs" to + which we add dependencies. The custom task "copyExtraLibs" copies those dependencies to a new + build directory "extra-libs". This build uses the Task Configuraion Avoidance APIs which have + been marked stable in Gradle 6.0 +""".trimIndent() + +// extraLibs is a NamedDomainObjectProvider - the Configuration object will not be +// realized until it is needed. In the meantime, the build may reference it by name +val extralibs by configurations.registering + +dependencies { + // we can call extralibs.name without causing the extralibs to be realized + add(extralibs.name, "junit:junit:4.12") +} + +// extraLibsDir is a Provider - the Directory object will not be realized until it is +// needed +val extraLibsDir = project.layout.buildDirectory.dir("extra-libs") + +// copyExtraLibs is a TaskProvider - the task will not be realized until it is needed +val copyExtraLibs by tasks.registering(Copy::class) { + // the copy task's "from" and "into" APIs accept Provider types to support configuration + // avoidance + from(extralibs) + into(extraLibsDir) +} + +// configures the "build" task only if it needs to be +tasks.build { + // dependsOn accepts a TaskProvider to avoid realizing the copyExtraLibs needlessly + dependsOn(copyExtraLibs) +} diff --git a/gradle-6/dependency-constraints/build.gradle.kts b/gradle-6/dependency-constraints/build.gradle.kts new file mode 100644 index 0000000000..41336d3c91 --- /dev/null +++ b/gradle-6/dependency-constraints/build.gradle.kts @@ -0,0 +1,29 @@ +plugins { + `java-library` +} + +group = "com.baeldung" +version = "1.0.0" + +dependencies { + api("io.reactivex.rxjava2:rxjava:2.2.16") + implementation("com.google.guava:guava") { + version { + require("10.0") + prefer("28.1-jre") + because("Only uses ImmutableList type, so any version since 2.0 will do, but tested with 28.1-jre") + } + } + + testImplementation("org.junit.jupiter:junit-jupiter-api:5.5.2") + testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.5.2") +} + +tasks.compileJava { + sourceCompatibility = "1.8" + targetCompatibility = "1.8" +} + +tasks.test { + useJUnitPlatform() +} diff --git a/gradle-6/dependency-constraints/src/main/java/com/baeldung/gradle/RxHelloWorld.java b/gradle-6/dependency-constraints/src/main/java/com/baeldung/gradle/RxHelloWorld.java new file mode 100644 index 0000000000..e4ebd9ba6b --- /dev/null +++ b/gradle-6/dependency-constraints/src/main/java/com/baeldung/gradle/RxHelloWorld.java @@ -0,0 +1,24 @@ +package com.baeldung.gradle; + +import com.google.common.collect.ImmutableList; +import io.reactivex.Observable; + +import java.util.List; + +/** + * Demonstrates a library type that returns an RxJava type. + */ +public class RxHelloWorld { + + /** + * @return an {@link Observable} that emits events "hello" and "world" before completing. + */ + public static Observable hello() { + // Guava ImmutableList class is an implementation detail. + List values = ImmutableList.of("hello", "world"); + return Observable.fromIterable(values); + } + + private RxHelloWorld() { + } +} diff --git a/gradle-6/dependency-constraints/src/test/java/com/baeldung/gradle/RxHelloWorldUnitTest.java b/gradle-6/dependency-constraints/src/test/java/com/baeldung/gradle/RxHelloWorldUnitTest.java new file mode 100644 index 0000000000..8a05fcfda3 --- /dev/null +++ b/gradle-6/dependency-constraints/src/test/java/com/baeldung/gradle/RxHelloWorldUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.gradle; + +import org.junit.jupiter.api.Test; + +import static com.baeldung.gradle.RxHelloWorld.hello; + +/** + * Unit test for {@link RxHelloWorld}. + */ +final class RxHelloWorldUnitTest { + @Test void it_emits_hello_world_values() { + hello().test().assertValues("hello", "world").assertComplete(); + } +} diff --git a/gradle-6/fibonacci-recursive/build.gradle.kts b/gradle-6/fibonacci-recursive/build.gradle.kts new file mode 100644 index 0000000000..0872a52472 --- /dev/null +++ b/gradle-6/fibonacci-recursive/build.gradle.kts @@ -0,0 +1,17 @@ +plugins { + `java-library` +} + +dependencies { + api(project(":fibonacci-spi")) + compileOnly("com.google.auto.service:auto-service-annotations:1.0-rc6") + annotationProcessor("com.google.auto.service:auto-service:1.0-rc6") + + testImplementation(testFixtures(project(":fibonacci-spi"))) + testImplementation("org.junit.jupiter:junit-jupiter-api:5.5.2") + testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.5.2") +} + +tasks.test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradle-6/fibonacci-recursive/src/main/java/com/baeldung/fibonacci/impl/RecursiveFibonacci.java b/gradle-6/fibonacci-recursive/src/main/java/com/baeldung/fibonacci/impl/RecursiveFibonacci.java new file mode 100644 index 0000000000..def79521bd --- /dev/null +++ b/gradle-6/fibonacci-recursive/src/main/java/com/baeldung/fibonacci/impl/RecursiveFibonacci.java @@ -0,0 +1,20 @@ +package com.baeldung.fibonacci.impl; + +import com.baeldung.fibonacci.FibonacciSequenceGenerator; +import com.google.auto.service.AutoService; + +/** + * Recursive implementation of the {@link FibonacciSequenceGenerator}. + */ +@AutoService(FibonacciSequenceGenerator.class) public final class RecursiveFibonacci implements FibonacciSequenceGenerator { + + @Override public int generate(int nth) { + if (nth < 0) { + throw new IllegalArgumentException("sequence number must be 0 or greater"); + } + if (nth <= 1) { + return nth; + } + return generate(nth - 1) + generate(nth - 2); + } +} diff --git a/gradle-6/fibonacci-recursive/src/test/java/com/baeldung/fibonacci/impl/RecursiveFibonacciUnitTest.java b/gradle-6/fibonacci-recursive/src/test/java/com/baeldung/fibonacci/impl/RecursiveFibonacciUnitTest.java new file mode 100644 index 0000000000..766f3b251b --- /dev/null +++ b/gradle-6/fibonacci-recursive/src/test/java/com/baeldung/fibonacci/impl/RecursiveFibonacciUnitTest.java @@ -0,0 +1,13 @@ +package com.baeldung.fibonacci.impl; + +import com.baeldung.fibonacci.FibonacciSequenceGenerator; +import com.baeldung.fibonacci.FibonacciSequenceGeneratorFixture; + +/** + * Unit test which reuses the {@link FibonacciSequenceGeneratorFixture} test mix-in exported from the fibonacci-spi project. + */ +final class RecursiveFibonacciUnitTest implements FibonacciSequenceGeneratorFixture { + @Override public FibonacciSequenceGenerator provide() { + return new RecursiveFibonacci(); + } +} diff --git a/gradle-6/fibonacci-spi/build.gradle.kts b/gradle-6/fibonacci-spi/build.gradle.kts new file mode 100644 index 0000000000..e571f329a9 --- /dev/null +++ b/gradle-6/fibonacci-spi/build.gradle.kts @@ -0,0 +1,13 @@ +plugins { + `java-library` + `java-test-fixtures` +} + +dependencies { + testFixturesApi("org.junit.jupiter:junit-jupiter-api:5.5.2") + testFixturesImplementation("org.junit.jupiter:junit-jupiter-engine:5.5.2") +} + +tasks.test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradle-6/fibonacci-spi/src/main/java/com/baeldung/fibonacci/FibonacciSequenceGenerator.java b/gradle-6/fibonacci-spi/src/main/java/com/baeldung/fibonacci/FibonacciSequenceGenerator.java new file mode 100644 index 0000000000..5fd99100fc --- /dev/null +++ b/gradle-6/fibonacci-spi/src/main/java/com/baeldung/fibonacci/FibonacciSequenceGenerator.java @@ -0,0 +1,13 @@ +package com.baeldung.fibonacci; + +/** + * Describes an SPI for a Fibonacci sequence generator function. + */ +public interface FibonacciSequenceGenerator { + + /** + * @param nth the index of the number in the fibonacci sequence + * @return the nth number in the fibonacci sequence + */ + int generate(int nth); +} diff --git a/gradle-6/fibonacci-spi/src/testFixtures/java/com/baeldung/fibonacci/FibonacciSequenceGeneratorFixture.java b/gradle-6/fibonacci-spi/src/testFixtures/java/com/baeldung/fibonacci/FibonacciSequenceGeneratorFixture.java new file mode 100644 index 0000000000..5394590c03 --- /dev/null +++ b/gradle-6/fibonacci-spi/src/testFixtures/java/com/baeldung/fibonacci/FibonacciSequenceGeneratorFixture.java @@ -0,0 +1,30 @@ +package com.baeldung.fibonacci; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Reusable test fixture for {@link FibonacciSequenceGenerator} implementations. Tests will be skipped if no such implementation exists. + */ +public interface FibonacciSequenceGeneratorFixture { + + /** + * @return the implementation of {@link FibonacciSequenceGenerator} to test. Must not be null + */ + FibonacciSequenceGenerator provide(); + + @Test default void when_sequence_index_is_negative_then_throws() { + final FibonacciSequenceGenerator generator = provide(); + assertThrows(IllegalArgumentException.class, () -> generator.generate(-1)); + } + + @Test default void when_given_index_then_generates_fibonacci_number() { + final FibonacciSequenceGenerator generator = provide(); + final int[] sequence = { 0, 1, 1, 2, 3, 5, 8 }; + for (int i = 0; i < sequence.length; i++) { + assertEquals(sequence[i], generator.generate(i)); + } + } +} diff --git a/gradle-6/gradle.properties b/gradle-6/gradle.properties new file mode 100644 index 0000000000..7da8b3d72a --- /dev/null +++ b/gradle-6/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.parallel=true +org.gradle.configureondemand=true diff --git a/gradle-6/gradle/wrapper/gradle-wrapper.jar b/gradle-6/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..cc4fdc293d Binary files /dev/null and b/gradle-6/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle-6/gradle/wrapper/gradle-wrapper.properties b/gradle-6/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..94920145f3 --- /dev/null +++ b/gradle-6/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradle-6/gradlew b/gradle-6/gradlew new file mode 100755 index 0000000000..2fe81a7d95 --- /dev/null +++ b/gradle-6/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# 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 +# +# https://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. +# + +############################################################################## +## +## 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='"-Xmx64m" "-Xms64m"' + +# 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 or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; 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=`expr $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" + +exec "$JAVACMD" "$@" diff --git a/gradle-6/gradlew.bat b/gradle-6/gradlew.bat new file mode 100644 index 0000000000..24467a141f --- /dev/null +++ b/gradle-6/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@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="-Xmx64m" "-Xms64m" + +@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/gradle-6/httpclient-platform/build.gradle.kts b/gradle-6/httpclient-platform/build.gradle.kts new file mode 100644 index 0000000000..a021bff013 --- /dev/null +++ b/gradle-6/httpclient-platform/build.gradle.kts @@ -0,0 +1,11 @@ +plugins { + `java-platform` +} + +dependencies { + constraints { + api("org.apache.httpcomponents:fluent-hc:4.5.10") + api("org.apache.httpcomponents:httpclient:4.5.10") + runtime("commons-logging:commons-logging:1.2") + } +} \ No newline at end of file diff --git a/gradle-6/module-metadata-publishing/build.gradle.kts b/gradle-6/module-metadata-publishing/build.gradle.kts new file mode 100644 index 0000000000..9812c72f6f --- /dev/null +++ b/gradle-6/module-metadata-publishing/build.gradle.kts @@ -0,0 +1,12 @@ +plugins { + java + `maven-publish` +} + +publishing { + publications { + register("mavenJava") { + from(components["java"]) + } + } +} \ No newline at end of file diff --git a/gradle-6/person-rest-client/build.gradle.kts b/gradle-6/person-rest-client/build.gradle.kts new file mode 100644 index 0000000000..c562b3e164 --- /dev/null +++ b/gradle-6/person-rest-client/build.gradle.kts @@ -0,0 +1,8 @@ +plugins { + `java-library` +} + +dependencies { + api(platform(project(":httpclient-platform"))) + implementation("org.apache.httpcomponents:fluent-hc") +} \ No newline at end of file diff --git a/gradle-6/settings.gradle.kts b/gradle-6/settings.gradle.kts new file mode 100644 index 0000000000..88cf74c4d7 --- /dev/null +++ b/gradle-6/settings.gradle.kts @@ -0,0 +1,10 @@ +rootProject.name = "gradle-6" + +include("configuration-avoidance") +include("dependency-constraints") +include("fibonacci-spi") +include("fibonacci-recursive") +include("httpclient-platform") +include("module-metadata-publishing") +include("person-rest-client") +include("widget-rest-client") \ No newline at end of file diff --git a/gradle-6/widget-rest-client/build.gradle.kts b/gradle-6/widget-rest-client/build.gradle.kts new file mode 100644 index 0000000000..e1af4b7f71 --- /dev/null +++ b/gradle-6/widget-rest-client/build.gradle.kts @@ -0,0 +1,8 @@ +plugins { + `java-library` +} + +dependencies { + api(platform(project(":httpclient-platform"))) + implementation("org.apache.httpcomponents:httpclient") +} \ No newline at end of file diff --git a/gradle/gradle-employee-app/.gitignore b/gradle/gradle-employee-app/.gitignore new file mode 100644 index 0000000000..d347f664af --- /dev/null +++ b/gradle/gradle-employee-app/.gitignore @@ -0,0 +1,3 @@ +/.idea +/.gradle +/build diff --git a/gradle/gradle-employee-app/build.gradle b/gradle/gradle-employee-app/build.gradle new file mode 100644 index 0000000000..19b80c0c4a --- /dev/null +++ b/gradle/gradle-employee-app/build.gradle @@ -0,0 +1,38 @@ + +plugins { + id 'java-library' + id 'application' +} + +apply plugin: 'application' +mainClassName = 'employee.EmployeeApp' + +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +println 'This is executed during configuration phase' + +task configured { + println 'The project is configured' +} + +task wrapper(type: Wrapper){ + gradleVersion = '5.3.1' +} + +repositories { + jcenter() +} + +dependencies { + + compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.10' + testImplementation('junit:junit:4.13') + testRuntime('junit:junit:4.13') +} +test { + useJUnit() +} + diff --git a/gradle/gradle-employee-app/src/main/java/employee/Employee.java b/gradle/gradle-employee-app/src/main/java/employee/Employee.java new file mode 100644 index 0000000000..6940c8c28c --- /dev/null +++ b/gradle/gradle-employee-app/src/main/java/employee/Employee.java @@ -0,0 +1,9 @@ +package employee; + +public class Employee { + + String name; + String emailAddress; + int yearOfBirth; + +} \ No newline at end of file diff --git a/gradle/gradle-employee-app/src/main/java/employee/EmployeeApp.java b/gradle/gradle-employee-app/src/main/java/employee/EmployeeApp.java new file mode 100644 index 0000000000..48ef9f5d61 --- /dev/null +++ b/gradle/gradle-employee-app/src/main/java/employee/EmployeeApp.java @@ -0,0 +1,16 @@ +package employee; + +public class EmployeeApp { + + public static void main(String[] args){ + + Employee employee = new Employee(); + employee.name = "John"; + employee.emailAddress = "john@baeldung.com"; + employee.yearOfBirth = 1978; + System.out.println("Name: " + employee.name); + System.out.println("Email Address: " + employee.emailAddress); + System.out.println("Year Of Birth:" + employee.yearOfBirth); + } + +} diff --git a/gradle/gradle-employee-app/src/test/java/employee/EmployeeAppTest.java b/gradle/gradle-employee-app/src/test/java/employee/EmployeeAppTest.java new file mode 100644 index 0000000000..013bcc35b6 --- /dev/null +++ b/gradle/gradle-employee-app/src/test/java/employee/EmployeeAppTest.java @@ -0,0 +1,31 @@ +package employee; + +import employee.Employee; +import org.junit.*; +import static org.junit.Assert.*; + +public class EmployeeAppTest { + + @Test + public void testData(){ + + Employee testEmp = this.getEmployeeTest(); + + assertEquals(testEmp.name, "John"); + assertEquals(testEmp.emailAddress, "john@baeldung.com"); + assertEquals(testEmp.yearOfBirth, 1978); + + + } + + private Employee getEmployeeTest(){ + + Employee employee = new Employee(); + employee.name = "John"; + employee.emailAddress = "john@baeldung.com"; + employee.yearOfBirth = 1978; + + return employee; + } + +} \ No newline at end of file diff --git a/gradle/gradle-to-maven/README.md b/gradle/gradle-to-maven/README.md new file mode 100644 index 0000000000..9acbfb1647 --- /dev/null +++ b/gradle/gradle-to-maven/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Converting Gradle Build File to Maven POM](https://www.baeldung.com/gradle-build-to-maven-pom) diff --git a/gradle/gradle-to-maven/build.gradle b/gradle/gradle-to-maven/build.gradle new file mode 100644 index 0000000000..110edbc421 --- /dev/null +++ b/gradle/gradle-to-maven/build.gradle @@ -0,0 +1,41 @@ +repositories { + mavenCentral() +} + +apply plugin: 'java' +apply plugin: 'maven' + +group = 'com.baeldung' + +// by default, pom's artifactId is taken from the directory name + +version = '0.0.1-SNAPSHOT' + +dependencies { + compile('org.slf4j:slf4j-api') + testCompile('junit:junit') +} + +install { + repositories { + mavenInstaller { + pom.version = '0.0.1-maven-SNAPSHOT' + pom.groupId = 'com.baeldung.sample' + pom.artifactId = 'gradle-maven-converter' + pom.project { + inceptionYear '2020' + licenses { + license { + name 'My License' + url 'http://www.mycompany.com/licenses/license.txt' + distribution 'repo' + } + } + } + pom.whenConfigured {pom -> + pom.dependencies.find {dep -> dep.groupId == 'junit' && dep.artifactId == 'junit' }.optional = true + } + pom.writeTo("${mavenPomDir}/${project.group}/${project.name}/pom.xml") + } + } +} \ No newline at end of file diff --git a/gradle/settings.gradle b/gradle/settings.gradle index f1d64de58a..59300f9281 100644 --- a/gradle/settings.gradle +++ b/gradle/settings.gradle @@ -1,10 +1,10 @@ rootProject.name = 'gradletutorial' - include 'greeting-library' include 'greeting-library-java' include 'greeter' include 'gradletaskdemo' include 'junit5' +include 'gradle-employee-app' println 'This will be executed during the initialization phase.' diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml index 3613d89ae7..30bfbf555a 100644 --- a/graphql/graphql-java/pom.xml +++ b/graphql/graphql-java/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.graphql graphql-java @@ -11,6 +13,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../.. diff --git a/grpc/pom.xml b/grpc/pom.xml index c7ae111da3..5e1c0bb28b 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 grpc 0.0.1-SNAPSHOT diff --git a/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java b/grpc/src/main/java/com/baeldung/grpc/client/GrpcClient.java similarity index 81% rename from grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java rename to grpc/src/main/java/com/baeldung/grpc/client/GrpcClient.java index f653e17910..f10b24faa7 100644 --- a/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java +++ b/grpc/src/main/java/com/baeldung/grpc/client/GrpcClient.java @@ -1,8 +1,8 @@ -package org.baeldung.grpc.client; +package com.baeldung.grpc.client; -import org.baeldung.grpc.HelloRequest; -import org.baeldung.grpc.HelloResponse; -import org.baeldung.grpc.HelloServiceGrpc; +import com.baeldung.grpc.HelloRequest; +import com.baeldung.grpc.HelloResponse; +import com.baeldung.grpc.HelloServiceGrpc; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; diff --git a/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java b/grpc/src/main/java/com/baeldung/grpc/server/GrpcServer.java similarity index 93% rename from grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java rename to grpc/src/main/java/com/baeldung/grpc/server/GrpcServer.java index 8a2b94e53b..2380d73a8c 100644 --- a/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java +++ b/grpc/src/main/java/com/baeldung/grpc/server/GrpcServer.java @@ -1,4 +1,4 @@ -package org.baeldung.grpc.server; +package com.baeldung.grpc.server; import java.io.IOException; diff --git a/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java b/grpc/src/main/java/com/baeldung/grpc/server/HelloServiceImpl.java similarity index 79% rename from grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java rename to grpc/src/main/java/com/baeldung/grpc/server/HelloServiceImpl.java index b08ad02c97..8609477fe9 100644 --- a/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java +++ b/grpc/src/main/java/com/baeldung/grpc/server/HelloServiceImpl.java @@ -1,8 +1,8 @@ -package org.baeldung.grpc.server; +package com.baeldung.grpc.server; -import org.baeldung.grpc.HelloRequest; -import org.baeldung.grpc.HelloResponse; -import org.baeldung.grpc.HelloServiceGrpc.HelloServiceImplBase; +import com.baeldung.grpc.HelloRequest; +import com.baeldung.grpc.HelloResponse; +import com.baeldung.grpc.HelloServiceGrpc.HelloServiceImplBase; import io.grpc.stub.StreamObserver; diff --git a/grpc/src/main/proto/HelloService.proto b/grpc/src/main/proto/HelloService.proto index 4f53191ab9..a008fad4b0 100644 --- a/grpc/src/main/proto/HelloService.proto +++ b/grpc/src/main/proto/HelloService.proto @@ -1,6 +1,6 @@ syntax = "proto3"; option java_multiple_files = true; -package org.baeldung.grpc; +package com.baeldung.grpc; message HelloRequest { string firstName = 1; diff --git a/gson/README.md b/gson/README.md index df6ba0f516..4255e2ead9 100644 --- a/gson/README.md +++ b/gson/README.md @@ -13,4 +13,4 @@ This module contains articles about Gson - [Convert String to JsonObject with Gson](https://www.baeldung.com/gson-string-to-jsonobject) - [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field) - [Serializing and Deserializing a List with Gson](https://www.baeldung.com/gson-list) - +- [Compare Two JSON Objects with Gson](https://www.baeldung.com/gson-compare-json-objects) diff --git a/gson/pom.xml b/gson/pom.xml index f2ed5509fa..0de9a6a533 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 gson 0.1-SNAPSHOT diff --git a/gson/src/test/java/com/baeldung/gson/jsoncompare/JsonCompareUnitTest.java b/gson/src/test/java/com/baeldung/gson/jsoncompare/JsonCompareUnitTest.java new file mode 100644 index 0000000000..84989a7411 --- /dev/null +++ b/gson/src/test/java/com/baeldung/gson/jsoncompare/JsonCompareUnitTest.java @@ -0,0 +1,95 @@ +package com.baeldung.gson.jsoncompare; + +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import org.junit.Test; +import static org.junit.Assert.*; + +public class JsonCompareUnitTest { + @Test + public void givenJsonStrings_whenCompared_thenNotEqual() { + String string1 = "{\"fullName\": \"Emily Jenkins\", \"age\": 27 }"; + String string2 = "{\"fullName\": \"Emily Jenkins\", \"age\": 27}"; + + assertNotEquals(string1, string2); + } + + @Test + public void givenIdenticalSimpleObjects_whenCompared_thenEqual() { + JsonParser parser = new JsonParser(); + String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27 }}"; + String string2 = "{\"customer\": {\"id\": \"44521\", \"fullName\": \"Emily Jenkins\",\"age\": 27}}"; + + assertTrue(parser.parse(string1) + .isJsonObject()); + assertEquals(parser.parse(string1), parser.parse(string2)); + } + + @Test + public void givenSameObjectsInDifferentOrder_whenCompared_thenEqual() { + JsonParser parser = new JsonParser(); + String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27 }}"; + String string2 = "{\"customer\": {\"id\": \"44521\",\"age\": 27, \"fullName\": \"Emily Jenkins\" }}"; + + JsonElement json1 = parser.parse(string1); + JsonElement json2 = parser.parse(string2); + + assertEquals(json1, json2); + } + + @Test + public void givenIdenticalArrays_whenCompared_thenEqual() { + JsonParser parser = new JsonParser(); + String string1 = "[10, 20, 30]"; + String string2 = "[10, 20, 30]"; + + assertTrue(parser.parse(string1) + .isJsonArray()); + assertEquals(parser.parse(string1), parser.parse(string2)); + } + + @Test + public void givenArraysInDifferentOrder_whenCompared_thenNotEqual() { + JsonParser parser = new JsonParser(); + String string1 = "[20, 10, 30]"; + String string2 = "[10, 20, 30]"; + + assertNotEquals(parser.parse(string1), parser.parse(string2)); + } + + @Test + public void givenIdenticalNestedObjects_whenCompared_thenEqual() { + JsonParser parser = new JsonParser(); + String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"fav_product\": \"Coke\", \"last_buy\": \"2012-04-23\"}}}"; + String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"fav_product\": \"Coke\"}}}"; + + JsonElement json1 = parser.parse(string1); + JsonElement json2 = parser.parse(string2); + + assertEquals(json1, json2); + } + + @Test + public void givenIdenticalNestedObjectsWithArray_whenCompared_thenEqual() { + JsonParser parser = new JsonParser(); + String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}"; + String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}"; + + JsonElement json1 = parser.parse(string1); + JsonElement json2 = parser.parse(string2); + + assertEquals(json1, json2); + } + + @Test + public void givenNestedObjectsDifferentArrayOrder_whenCompared_thenNotEqual() { + JsonParser parser = new JsonParser(); + String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}"; + String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"eggs\", \"banana\"]}}}"; + + JsonElement json1 = parser.parse(string1); + JsonElement json2 = parser.parse(string2); + + assertNotEquals(json1, json2); + } +} diff --git a/guava-collections-map/README.md b/guava-collections-map/README.md index b3ec5e2157..4f8743dcfb 100644 --- a/guava-collections-map/README.md +++ b/guava-collections-map/README.md @@ -9,4 +9,5 @@ This module contains articles about map collections in Guava - [Guide to Guava Multimap](https://www.baeldung.com/guava-multimap) - [Guide to Guava RangeMap](https://www.baeldung.com/guava-rangemap) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- [Guide to Guava ClassToInstanceMap](https://www.baeldung.com/guava-class-to-instance-map) \ No newline at end of file +- [Guide to Guava ClassToInstanceMap](https://www.baeldung.com/guava-class-to-instance-map) +- [Using Guava’s MapMaker](https://www.baeldung.com/guava-mapmaker) diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java new file mode 100644 index 0000000000..165c5a9f8f --- /dev/null +++ b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java @@ -0,0 +1,20 @@ +package com.baeldung.guava.mapmaker; + +public class Profile { + private long id; + private String type; + + public Profile(long id, String type) { + this.id = id; + this.type = type; + } + + public long getId() { + return id; + } + + public String getName() { + return type; + } + +} diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java new file mode 100644 index 0000000000..a614f431f8 --- /dev/null +++ b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java @@ -0,0 +1,13 @@ +package com.baeldung.guava.mapmaker; + +public class Session { + private long id; + + public Session(long id) { + this.id = id; + } + + public long getId() { + return id; + } +} diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java new file mode 100644 index 0000000000..a7f0435049 --- /dev/null +++ b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java @@ -0,0 +1,20 @@ +package com.baeldung.guava.mapmaker; + +public class User { + private long id; + private String name; + + public User(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + +} diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java new file mode 100644 index 0000000000..754e3ac099 --- /dev/null +++ b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.guava.mapmaker; + +import com.google.common.collect.MapMaker; +import org.junit.Assert; +import org.junit.Test; + +import java.util.concurrent.ConcurrentMap; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertNotNull; + +public class GuavaMapMakerUnitTest { + @Test + public void whenCreateCaches_thenCreated() { + ConcurrentMap sessionCache = new MapMaker().makeMap(); + assertNotNull(sessionCache); + + ConcurrentMap profileCache = new MapMaker().makeMap(); + assertNotNull(profileCache); + + User userA = new User(1, "UserA"); + + sessionCache.put(userA, new Session(100)); + Assert.assertThat(sessionCache.size(), equalTo(1)); + + profileCache.put(userA, new Profile(1000, "Personal")); + Assert.assertThat(profileCache.size(), equalTo(1)); + } + + @Test + public void whenCreateCacheWithInitialCapacity_thenCreated() { + ConcurrentMap profileCache = new MapMaker().initialCapacity(100).makeMap(); + assertNotNull(profileCache); + } + + @Test + public void whenCreateCacheWithConcurrencyLevel_thenCreated() { + ConcurrentMap sessionCache = new MapMaker().concurrencyLevel(10).makeMap(); + assertNotNull(sessionCache); + } + + @Test + public void whenCreateCacheWithWeakKeys_thenCreated() { + ConcurrentMap sessionCache = new MapMaker().weakKeys().makeMap(); + assertNotNull(sessionCache); + } + + @Test + public void whenCreateCacheWithWeakValues_thenCreated() { + ConcurrentMap profileCache = new MapMaker().weakValues().makeMap(); + assertNotNull(profileCache); + } +} diff --git a/guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSet.java b/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSet.java similarity index 98% rename from guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSet.java rename to guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSet.java index f474fcb17b..d2c772080d 100644 --- a/guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSet.java +++ b/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSet.java @@ -1,4 +1,4 @@ -package org.baeldung.guava; +package com.baeldung.guava; import com.google.common.base.Function; diff --git a/guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java b/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSetUnitTest.java similarity index 98% rename from guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java rename to guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSetUnitTest.java index 03f2d8f891..71a526601b 100644 --- a/guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java +++ b/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSetUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.guava; +package com.baeldung.guava; import com.google.common.base.Function; import org.junit.Test; diff --git a/guava-collections-set/src/test/java/org/baeldung/guava/GuavaMultiSetUnitTest.java b/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMultiSetUnitTest.java similarity index 99% rename from guava-collections-set/src/test/java/org/baeldung/guava/GuavaMultiSetUnitTest.java rename to guava-collections-set/src/test/java/com/baeldung/guava/GuavaMultiSetUnitTest.java index e74db29881..dc1489f7ea 100644 --- a/guava-collections-set/src/test/java/org/baeldung/guava/GuavaMultiSetUnitTest.java +++ b/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMultiSetUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.guava; +package com.baeldung.guava; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; diff --git a/guava-collections-set/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java b/guava-collections-set/src/test/java/com/baeldung/guava/GuavaRangeSetUnitTest.java similarity index 99% rename from guava-collections-set/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java rename to guava-collections-set/src/test/java/com/baeldung/guava/GuavaRangeSetUnitTest.java index edefc61fc4..bd9aa09941 100644 --- a/guava-collections-set/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java +++ b/guava-collections-set/src/test/java/com/baeldung/guava/GuavaRangeSetUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.guava; +package com.baeldung.guava; import com.google.common.collect.ImmutableRangeSet; import com.google.common.collect.Range; diff --git a/guava-collections-set/src/test/java/org/baeldung/guava/GuavaSetOperationsUnitTest.java b/guava-collections-set/src/test/java/com/baeldung/guava/GuavaSetOperationsUnitTest.java similarity index 99% rename from guava-collections-set/src/test/java/org/baeldung/guava/GuavaSetOperationsUnitTest.java rename to guava-collections-set/src/test/java/com/baeldung/guava/GuavaSetOperationsUnitTest.java index dfd90ad738..eaa6d8a832 100644 --- a/guava-collections-set/src/test/java/org/baeldung/guava/GuavaSetOperationsUnitTest.java +++ b/guava-collections-set/src/test/java/com/baeldung/guava/GuavaSetOperationsUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.guava; +package com.baeldung.guava; import com.google.common.base.Function; import com.google.common.base.Joiner; diff --git a/guava-collections/pom.xml b/guava-collections/pom.xml index 9002ac2b91..c6019362c5 100644 --- a/guava-collections/pom.xml +++ b/guava-collections/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 guava-collections 0.1.0-SNAPSHOT diff --git a/guava-io/src/main/test/java/com/baeldung/guava/GuavaCountingOutputStreamUnitTest.java b/guava-io/src/main/test/java/com/baeldung/guava/GuavaCountingOutputStreamUnitTest.java index 7293b1631e..5d846933f9 100644 --- a/guava-io/src/main/test/java/com/baeldung/guava/GuavaCountingOutputStreamUnitTest.java +++ b/guava-io/src/main/test/java/com/baeldung/guava/GuavaCountingOutputStreamUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.guava; +package com.baeldung.guava; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; diff --git a/guava-io/src/main/test/java/com/baeldung/guava/GuavaIOUnitTest.java b/guava-io/src/main/test/java/com/baeldung/guava/GuavaIOUnitTest.java index 4a827dfbc0..7d7b0ea04d 100644 --- a/guava-io/src/main/test/java/com/baeldung/guava/GuavaIOUnitTest.java +++ b/guava-io/src/main/test/java/com/baeldung/guava/GuavaIOUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.guava; +package com.baeldung.guava; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertEquals; diff --git a/guava/README.md b/guava/README.md index c67a3604ea..9c650dbc1d 100644 --- a/guava/README.md +++ b/guava/README.md @@ -12,4 +12,5 @@ This module contains articles a Google Guava - [Guide to Mathematical Utilities in Guava](https://www.baeldung.com/guava-math) - [Bloom Filter in Java using Guava](https://www.baeldung.com/guava-bloom-filter) - [Quick Guide to the Guava RateLimiter](https://www.baeldung.com/guava-rate-limiter) - +- [Introduction to Guava Throwables](https://www.baeldung.com/guava-throwables) +- [Guava Cache](https://www.baeldung.com/guava-cache) diff --git a/guava/pom.xml b/guava/pom.xml index 3f07b77b0b..df6d57bd09 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 guava 0.1.0-SNAPSHOT diff --git a/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java b/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java new file mode 100644 index 0000000000..7d33b38a0e --- /dev/null +++ b/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.guava; + +import com.google.common.base.Throwables; +import org.junit.Test; + +import java.util.function.Supplier; + +public class ThrowablesUnitTest { + + @Test(expected = RuntimeException.class) + public void whenThrowable_shouldWrapItInRuntimeException() throws Exception { + try { + throwThrowable(Throwable::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + @Test(expected = Error.class) + public void whenError_shouldPropagateAsIs() throws Exception { + try { + throwThrowable(Error::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + @Test(expected = Exception.class) + public void whenException_shouldPropagateAsIs() throws Exception { + try { + throwThrowable(Exception::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + private void throwThrowable(Supplier exceptionSupplier) throws Throwable { + throw exceptionSupplier.get(); + } + +} diff --git a/guest/core-kotlin/pom.xml b/guest/core-kotlin/pom.xml index 2d4a0c6144..ad0368c6ab 100644 --- a/guest/core-kotlin/pom.xml +++ b/guest/core-kotlin/pom.xml @@ -46,19 +46,19 @@ org.jetbrains.spek spek-api - 1.1.5 + ${spek.api.version} test org.jetbrains.spek spek-subject-extension - 1.1.5 + ${spek.subject.version} test org.jetbrains.spek spek-junit-platform-engine - 1.1.5 + ${spek.junit.version} test @@ -195,6 +195,9 @@ 5.2.0 3.10.0 3.7.0 + 1.1.5 + 1.1.5 + 1.1.5 diff --git a/guice/pom.xml b/guice/pom.xml index d119bbf78e..6bbad6dddc 100644 --- a/guice/pom.xml +++ b/guice/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.examples.guice guice diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml index 10234bb81f..287542be33 100644 --- a/hazelcast/pom.xml +++ b/hazelcast/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 hazelcast 0.0.1-SNAPSHOT @@ -32,7 +34,7 @@ - + 0.6 diff --git a/hexagonal-architecture-poc/pom.xml b/hexagonal-architecture-poc/pom.xml deleted file mode 100644 index b31a6dec90..0000000000 --- a/hexagonal-architecture-poc/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.0.5.RELEASE - - - com.baeldung - hexagonal-architecture-poc - 0.0.1-SNAPSHOT - hexagonal-architecture-poc - Demo project for Hexagonal Architecture POC - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - runtime - - - org.springframework.boot - spring-boot-starter-web - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - diff --git a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/HexagonalArchitecturePocApplication.java b/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/HexagonalArchitecturePocApplication.java deleted file mode 100644 index 1690fbbeb5..0000000000 --- a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/HexagonalArchitecturePocApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.hexagonal; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class HexagonalArchitecturePocApplication { - - public static void main(String[] args) { - SpringApplication.run(HexagonalArchitecturePocApplication.class, args); - } - -} diff --git a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/boundary/input/OrderService.java b/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/boundary/input/OrderService.java deleted file mode 100644 index 07793f75ab..0000000000 --- a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/boundary/input/OrderService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.hexagonal.boundary.input; - -import org.springframework.stereotype.Service; - -import com.baeldung.hexagonal.core.entities.Order; - -@Service public interface OrderService { - Iterable getOrders(); - Order createOrder(Double total); - boolean registerOrder(Order order); -} diff --git a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/boundary/output/OrderRepository.java b/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/boundary/output/OrderRepository.java deleted file mode 100644 index ea1d38d296..0000000000 --- a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/boundary/output/OrderRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.hexagonal.boundary.output; - -import java.util.List; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.hexagonal.core.entities.Order; - -@Repository public interface OrderRepository extends CrudRepository{ -} diff --git a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/core/entities/Order.java b/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/core/entities/Order.java deleted file mode 100644 index db0c4efd54..0000000000 --- a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/core/entities/Order.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.hexagonal.core.entities; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity @Table(name="Orders") public class Order { - @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; - Double total; - - public Order() { - super(); - } - public Double getTotal() { - return total; - } - public void setTotal(Double total) { - this.total = total; - } - public Long getId() { - return id; - } - - -} diff --git a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/core/services/OrderServiceImpl.java b/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/core/services/OrderServiceImpl.java deleted file mode 100644 index d3d8f1ba6a..0000000000 --- a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/core/services/OrderServiceImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.hexagonal.core.services; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.baeldung.hexagonal.boundary.input.OrderService; -import com.baeldung.hexagonal.boundary.output.OrderRepository; -import com.baeldung.hexagonal.core.entities.Order; - -@Service public class OrderServiceImpl implements OrderService { - - @Autowired OrderRepository orderRepository; - - @Override - public Iterable getOrders() { - return orderRepository.findAll(); - } - - @Override - public boolean registerOrder(Order order) { - if (order.getTotal() > 0) - orderRepository.save(order); - else - return false; - - return true; - } - - @Override - public Order createOrder(Double total) { - Order order = new Order(); - order.setTotal(total); - return order; - } -} diff --git a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/outside/OrderController.java b/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/outside/OrderController.java deleted file mode 100644 index 85c2e42368..0000000000 --- a/hexagonal-architecture-poc/src/main/java/com/baeldung/hexagonal/outside/OrderController.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.hexagonal.outside; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import com.baeldung.hexagonal.boundary.input.OrderService; -import com.baeldung.hexagonal.core.entities.Order; - -@RestController public class OrderController { - - @Autowired OrderService orderService; - - @GetMapping(path = "/orders/list") - public Iterable getOrders(){ - return orderService.getOrders(); - } - - @GetMapping(path = "/orders/add") - public String placeOrder(@RequestParam Double total) { - boolean isPlaced = orderService.registerOrder(orderService.createOrder(total)); - return isPlaced ? "Ok" : "Nok"; - } - - @GetMapping(path = "/orders/add-commission") - public String placeCommissionOrder(@RequestParam Double total) { - boolean isPlaced = orderService.registerOrder(orderService.createOrder(total*1.05)); - return isPlaced ? "Ok" : "Nok"; - } - -} diff --git a/hexagonal-architecture-poc/src/main/resources/application.properties b/hexagonal-architecture-poc/src/main/resources/application.properties deleted file mode 100644 index bc2fdde8c1..0000000000 --- a/hexagonal-architecture-poc/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:testdb -spring.datasource.driverClassName=org.h2.Driver -spring.datasource.username=sa -spring.datasource.password=password -spring.jpa.database-platform=org.hibernate.dialect.H2Dialect diff --git a/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java index 380ff9df6b..cafd8cfb7b 100644 --- a/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java +++ b/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -1,20 +1,20 @@ package com.baeldung.basic; +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import org.springframework.stereotype.Component; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; - @Component public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { @Override - public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException { + public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException { response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); final PrintWriter writer = response.getWriter(); @@ -22,7 +22,7 @@ public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoi } @Override - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() { setRealmName("Baeldung"); super.afterPropertiesSet(); } diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 8c505c9104..1cf8713b91 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/image-processing/README.md b/image-processing/README.md index adb35c2318..50129bb994 100644 --- a/image-processing/README.md +++ b/image-processing/README.md @@ -4,3 +4,5 @@ This module contains articles about image processing. ### Relevant Articles: - [Working with Images in Java](https://www.baeldung.com/java-images) +- [Intro to OpenCV with Java](https://www.baeldung.com/java-opencv) +- [Optical Character Recognition with Tesseract](https://www.baeldung.com/java-ocr-tesseract) diff --git a/image-processing/pom.xml b/image-processing/pom.xml index 7b130329c7..806cccf351 100644 --- a/image-processing/pom.xml +++ b/image-processing/pom.xml @@ -35,6 +35,11 @@ + + org.openpnp + opencv + 3.4.2-0 + com.twelvemonkeys.imageio imageio-core @@ -45,12 +50,24 @@ imageio-bmp ${imageio.version} + + net.sourceforge.tess4j + tess4j + ${tess4j.version} + + + org.bytedeco + tesseract-platform + ${tesseract-platform.version} + - + 1.3.5 1.51h 3.3.2 + 4.5.1 + 4.1.0-1.5.2 \ No newline at end of file diff --git a/image-processing/src/main/java/com/baeldung/imageprocessing/opencv/CameraStream.java b/image-processing/src/main/java/com/baeldung/imageprocessing/opencv/CameraStream.java new file mode 100644 index 0000000000..3e7bd159c4 --- /dev/null +++ b/image-processing/src/main/java/com/baeldung/imageprocessing/opencv/CameraStream.java @@ -0,0 +1,87 @@ +package com.baeldung.imageprocessing.opencv; + +import javafx.animation.AnimationTimer; +import javafx.application.Application; +import javafx.scene.Scene; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.layout.HBox; +import javafx.stage.Stage; +import nu.pattern.OpenCV; +import org.opencv.core.Mat; +import org.opencv.core.MatOfByte; +import org.opencv.core.MatOfRect; +import org.opencv.core.Rect; +import org.opencv.core.Scalar; +import org.opencv.core.Size; +import org.opencv.imgcodecs.Imgcodecs; +import org.opencv.imgproc.Imgproc; +import org.opencv.objdetect.CascadeClassifier; +import org.opencv.objdetect.Objdetect; +import org.opencv.videoio.VideoCapture; + +import java.io.ByteArrayInputStream; + +public class CameraStream extends Application { + private VideoCapture capture; + + public void start(Stage stage) throws Exception { + OpenCV.loadShared(); + capture= new VideoCapture(0); // The number is the ID of the camera + ImageView imageView = new ImageView(); + HBox hbox = new HBox(imageView); + Scene scene = new Scene(hbox); + stage.setScene(scene); + stage.show(); + new AnimationTimer(){ + @Override + public void handle(long l) { + imageView.setImage(getCapture()); + } + }.start(); + } + + public Image getCapture() { + Mat mat = new Mat(); + capture.read(mat); + return mat2Img(mat); + } + + public Image getCaptureWithFaceDetection() { + Mat mat = new Mat(); + capture.read(mat); + Mat haarClassifiedImg = detectFace(mat); + return mat2Img(haarClassifiedImg); + } + + public Image mat2Img(Mat mat) { + MatOfByte bytes = new MatOfByte(); + Imgcodecs.imencode("img", mat, bytes); + ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes.toArray()); + Image img = new Image(inputStream); return img; + } + + public static void main(String[] args) { + Application.launch(args); + } + + public static Mat detectFace(Mat inputImage) { + MatOfRect facesDetected = new MatOfRect(); + CascadeClassifier cascadeClassifier = new CascadeClassifier(); + int minFaceSize = Math.round(inputImage.rows() * 0.1f); + cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml"); + cascadeClassifier.detectMultiScale(inputImage, + facesDetected, + 1.1, + 3, + Objdetect.CASCADE_SCALE_IMAGE, + new Size(minFaceSize, minFaceSize), + new Size() + ); + Rect[] facesArray = facesDetected.toArray(); + for(Rect face : facesArray) { + Imgproc.rectangle(inputImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3 ); + } + return inputImage; + } +} \ No newline at end of file diff --git a/image-processing/src/main/java/com/baeldung/imageprocessing/opencv/FaceDetection.java b/image-processing/src/main/java/com/baeldung/imageprocessing/opencv/FaceDetection.java new file mode 100644 index 0000000000..c53f484510 --- /dev/null +++ b/image-processing/src/main/java/com/baeldung/imageprocessing/opencv/FaceDetection.java @@ -0,0 +1,56 @@ +package com.baeldung.imageprocessing.opencv; + +import org.opencv.core.Mat; +import org.opencv.core.MatOfByte; +import org.opencv.core.MatOfRect; +import org.opencv.core.Rect; +import org.opencv.core.Scalar; +import org.opencv.core.Size; +import org.opencv.imgcodecs.Imgcodecs; +import org.opencv.imgproc.Imgproc; +import org.opencv.objdetect.CascadeClassifier; +import org.opencv.objdetect.Objdetect; +import javafx.scene.image.Image; +import java.io.ByteArrayInputStream; + +public class FaceDetection { + + public static Mat loadImage(String imagePath) { + Imgcodecs imageCodecs = new Imgcodecs(); + return imageCodecs.imread(imagePath); + } + + public static void saveImage(Mat imageMatrix, String targetPath) { + Imgcodecs imgcodecs = new Imgcodecs(); + imgcodecs.imwrite(targetPath, imageMatrix); + } + + public static void detectFace(String sourceImagePath, String targetImagePath) { + Mat loadedImage = loadImage(sourceImagePath); + MatOfRect facesDetected = new MatOfRect(); + CascadeClassifier cascadeClassifier = new CascadeClassifier(); + int minFaceSize = Math.round(loadedImage.rows() * 0.1f); + cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml"); + cascadeClassifier.detectMultiScale(loadedImage, + facesDetected, + 1.1, + 3, + Objdetect.CASCADE_SCALE_IMAGE, + new Size(minFaceSize, minFaceSize), + new Size() + ); + Rect[] facesArray = facesDetected.toArray(); + for(Rect face : facesArray) { + Imgproc.rectangle(loadedImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3 ); + } + saveImage(loadedImage, targetImagePath); + } + + public Image mat2Img(Mat mat) { + MatOfByte bytes = new MatOfByte(); + Imgcodecs.imencode("img", mat, bytes); + ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes.toArray()); + Image img = new Image(inputStream); return img; + } + +} \ No newline at end of file diff --git a/image-processing/src/main/java/com/baeldung/tesseract/Tess4JExample.java b/image-processing/src/main/java/com/baeldung/tesseract/Tess4JExample.java new file mode 100644 index 0000000000..c647de2372 --- /dev/null +++ b/image-processing/src/main/java/com/baeldung/tesseract/Tess4JExample.java @@ -0,0 +1,28 @@ +package com.baeldung.tesseract; + +import java.awt.Rectangle; +import java.io.File; + +import net.sourceforge.tess4j.Tesseract; +import net.sourceforge.tess4j.TesseractException; + +public class Tess4JExample { + + public static void main(String[] args) { + String result = null; + try { + File image = new File("src/main/resources/images/baeldung.png"); + Tesseract tesseract = new Tesseract(); + tesseract.setLanguage("spa"); + tesseract.setPageSegMode(1); + tesseract.setOcrEngineMode(1); + tesseract.setHocr(true); + tesseract.setDatapath("src/main/resources/tessdata"); + result = tesseract.doOCR(image, new Rectangle(1200, 200)); + } catch (TesseractException e) { + e.printStackTrace(); + } + System.out.println(result); + } + +} diff --git a/image-processing/src/main/java/com/baeldung/tesseract/TesseractPlatformExample.java b/image-processing/src/main/java/com/baeldung/tesseract/TesseractPlatformExample.java new file mode 100644 index 0000000000..61a2e39f2a --- /dev/null +++ b/image-processing/src/main/java/com/baeldung/tesseract/TesseractPlatformExample.java @@ -0,0 +1,26 @@ +package com.baeldung.tesseract; + +import org.bytedeco.javacpp.BytePointer; +import org.bytedeco.leptonica.PIX; +import org.bytedeco.tesseract.TessBaseAPI; + +public class TesseractPlatformExample { + + @SuppressWarnings("resource") + public static void main(String[] args) { + try { + TessBaseAPI tessApi = new TessBaseAPI(); + tessApi.Init("src/main/resources/tessdata", "eng", 3); + tessApi.SetPageSegMode(1); + PIX image = org.bytedeco.leptonica.global.lept.pixRead("src/main/resources/images/baeldung.png"); + tessApi.SetImage(image); + + BytePointer outText = tessApi.GetUTF8Text(); + System.out.println(outText.getString()); + tessApi.End(); + } catch(Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/image-processing/src/main/resources/haarcascades/haarcascade_frontalface_alt.xml b/image-processing/src/main/resources/haarcascades/haarcascade_frontalface_alt.xml new file mode 100644 index 0000000000..be36d2b85f --- /dev/null +++ b/image-processing/src/main/resources/haarcascades/haarcascade_frontalface_alt.xml @@ -0,0 +1,24350 @@ + + + + BOOST + HAAR + 20 + 20 + + 213 + + 0 + 22 + + <_> + 3 + 8.2268941402435303e-01 + + <_> + + 0 -1 0 4.0141958743333817e-03 + + 3.3794190734624863e-02 8.3781069517135620e-01 + <_> + + 0 -1 1 1.5151339583098888e-02 + + 1.5141320228576660e-01 7.4888122081756592e-01 + <_> + + 0 -1 2 4.2109931819140911e-03 + + 9.0049281716346741e-02 6.3748198747634888e-01 + <_> + 16 + 6.9566087722778320e+00 + + <_> + + 0 -1 3 1.6227109590545297e-03 + + 6.9308586418628693e-02 7.1109461784362793e-01 + <_> + + 0 -1 4 2.2906649392098188e-03 + + 1.7958030104637146e-01 6.6686922311782837e-01 + <_> + + 0 -1 5 5.0025708042085171e-03 + + 1.6936729848384857e-01 6.5540069341659546e-01 + <_> + + 0 -1 6 7.9659894108772278e-03 + + 5.8663320541381836e-01 9.1414518654346466e-02 + <_> + + 0 -1 7 -3.5227010957896709e-03 + + 1.4131669700145721e-01 6.0318958759307861e-01 + <_> + + 0 -1 8 3.6667689681053162e-02 + + 3.6756721138954163e-01 7.9203182458877563e-01 + <_> + + 0 -1 9 9.3361474573612213e-03 + + 6.1613857746124268e-01 2.0885099470615387e-01 + <_> + + 0 -1 10 8.6961314082145691e-03 + + 2.8362309932708740e-01 6.3602739572525024e-01 + <_> + + 0 -1 11 1.1488880263641477e-03 + + 2.2235809266567230e-01 5.8007007837295532e-01 + <_> + + 0 -1 12 -2.1484689787030220e-03 + + 2.4064640700817108e-01 5.7870548963546753e-01 + <_> + + 0 -1 13 2.1219060290604830e-03 + + 5.5596548318862915e-01 1.3622370362281799e-01 + <_> + + 0 -1 14 -9.3949146568775177e-02 + + 8.5027372837066650e-01 4.7177401185035706e-01 + <_> + + 0 -1 15 1.3777789426967502e-03 + + 5.9936738014221191e-01 2.8345298767089844e-01 + <_> + + 0 -1 16 7.3063157498836517e-02 + + 4.3418860435485840e-01 7.0600342750549316e-01 + <_> + + 0 -1 17 3.6767389974556863e-04 + + 3.0278879404067993e-01 6.0515749454498291e-01 + <_> + + 0 -1 18 -6.0479710809886456e-03 + + 1.7984339594841003e-01 5.6752568483352661e-01 + <_> + 21 + 9.4985427856445312e+00 + + <_> + + 0 -1 19 -1.6510689631104469e-02 + + 6.6442251205444336e-01 1.4248579740524292e-01 + <_> + + 0 -1 20 2.7052499353885651e-03 + + 6.3253521919250488e-01 1.2884770333766937e-01 + <_> + + 0 -1 21 2.8069869149476290e-03 + + 1.2402880191802979e-01 6.1931931972503662e-01 + <_> + + 0 -1 22 -1.5402400167658925e-03 + + 1.4321430027484894e-01 5.6700158119201660e-01 + <_> + + 0 -1 23 -5.6386279175058007e-04 + + 1.6574330627918243e-01 5.9052079916000366e-01 + <_> + + 0 -1 24 1.9253729842603207e-03 + + 2.6955071091651917e-01 5.7388240098953247e-01 + <_> + + 0 -1 25 -5.0214841030538082e-03 + + 1.8935389816761017e-01 5.7827740907669067e-01 + <_> + + 0 -1 26 2.6365420781075954e-03 + + 2.3093290627002716e-01 5.6954258680343628e-01 + <_> + + 0 -1 27 -1.5127769438549876e-03 + + 2.7596020698547363e-01 5.9566420316696167e-01 + <_> + + 0 -1 28 -1.0157439857721329e-02 + + 1.7325380444526672e-01 5.5220472812652588e-01 + <_> + + 0 -1 29 -1.1953660286962986e-02 + + 1.3394099473953247e-01 5.5590140819549561e-01 + <_> + + 0 -1 30 4.8859491944313049e-03 + + 3.6287039518356323e-01 6.1888492107391357e-01 + <_> + + 0 -1 31 -8.0132916569709778e-02 + + 9.1211050748825073e-02 5.4759448766708374e-01 + <_> + + 0 -1 32 1.0643280111253262e-03 + + 3.7151429057121277e-01 5.7113999128341675e-01 + <_> + + 0 -1 33 -1.3419450260698795e-03 + + 5.9533137083053589e-01 3.3180978894233704e-01 + <_> + + 0 -1 34 -5.4601140320301056e-02 + + 1.8440659344196320e-01 5.6028461456298828e-01 + <_> + + 0 -1 35 2.9071690514683723e-03 + + 3.5942441225051880e-01 6.1317151784896851e-01 + <_> + + 0 -1 36 7.4718717951327562e-04 + + 5.9943532943725586e-01 3.4595629572868347e-01 + <_> + + 0 -1 37 4.3013808317482471e-03 + + 4.1726520657539368e-01 6.9908452033996582e-01 + <_> + + 0 -1 38 4.5017572119832039e-03 + + 4.5097151398658752e-01 7.8014570474624634e-01 + <_> + + 0 -1 39 2.4138500913977623e-02 + + 5.4382127523422241e-01 1.3198269903659821e-01 + <_> + 39 + 1.8412969589233398e+01 + + <_> + + 0 -1 40 1.9212230108678341e-03 + + 1.4152669906616211e-01 6.1998707056045532e-01 + <_> + + 0 -1 41 -1.2748669541906565e-04 + + 6.1910742521286011e-01 1.8849289417266846e-01 + <_> + + 0 -1 42 5.1409931620582938e-04 + + 1.4873969554901123e-01 5.8579277992248535e-01 + <_> + + 0 -1 43 4.1878609918057919e-03 + + 2.7469098567962646e-01 6.3592398166656494e-01 + <_> + + 0 -1 44 5.1015717908740044e-03 + + 5.8708512783050537e-01 2.1756289899349213e-01 + <_> + + 0 -1 45 -2.1448440384119749e-03 + + 5.8809447288513184e-01 2.9795908927917480e-01 + <_> + + 0 -1 46 -2.8977119363844395e-03 + + 2.3733270168304443e-01 5.8766472339630127e-01 + <_> + + 0 -1 47 -2.1610679104924202e-02 + + 1.2206549942493439e-01 5.1942020654678345e-01 + <_> + + 0 -1 48 -4.6299318782985210e-03 + + 2.6312309503555298e-01 5.8174091577529907e-01 + <_> + + 0 -1 49 5.9393711853772402e-04 + + 3.6386200785636902e-01 5.6985449790954590e-01 + <_> + + 0 -1 50 5.3878661245107651e-02 + + 4.3035310506820679e-01 7.5593662261962891e-01 + <_> + + 0 -1 51 1.8887349870055914e-03 + + 2.1226030588150024e-01 5.6134271621704102e-01 + <_> + + 0 -1 52 -2.3635339457541704e-03 + + 5.6318491697311401e-01 2.6427671313285828e-01 + <_> + + 0 -1 53 2.4017799645662308e-02 + + 5.7971078157424927e-01 2.7517059445381165e-01 + <_> + + 0 -1 54 2.0543030404951423e-04 + + 2.7052420377731323e-01 5.7525688409805298e-01 + <_> + + 0 -1 55 8.4790197433903813e-04 + + 5.4356247186660767e-01 2.3348769545555115e-01 + <_> + + 0 -1 56 1.4091329649090767e-03 + + 5.3194248676300049e-01 2.0631550252437592e-01 + <_> + + 0 -1 57 1.4642629539594054e-03 + + 5.4189807176589966e-01 3.0688610672950745e-01 + <_> + + 0 -1 58 1.6352549428120255e-03 + + 3.6953729391098022e-01 6.1128681898117065e-01 + <_> + + 0 -1 59 8.3172752056270838e-04 + + 3.5650369524955750e-01 6.0252362489700317e-01 + <_> + + 0 -1 60 -2.0998890977352858e-03 + + 1.9139820337295532e-01 5.3628271818161011e-01 + <_> + + 0 -1 61 -7.4213981861248612e-04 + + 3.8355550169944763e-01 5.5293101072311401e-01 + <_> + + 0 -1 62 3.2655049581080675e-03 + + 4.3128961324691772e-01 7.1018958091735840e-01 + <_> + + 0 -1 63 8.9134991867467761e-04 + + 3.9848309755325317e-01 6.3919639587402344e-01 + <_> + + 0 -1 64 -1.5284179709851742e-02 + + 2.3667329549789429e-01 5.4337137937545776e-01 + <_> + + 0 -1 65 4.8381411470472813e-03 + + 5.8175009489059448e-01 3.2391890883445740e-01 + <_> + + 0 -1 66 -9.1093179071322083e-04 + + 5.5405938625335693e-01 2.9118689894676208e-01 + <_> + + 0 -1 67 -6.1275060288608074e-03 + + 1.7752550542354584e-01 5.1966291666030884e-01 + <_> + + 0 -1 68 -4.4576259097084403e-04 + + 3.0241701006889343e-01 5.5335938930511475e-01 + <_> + + 0 -1 69 2.2646540775895119e-02 + + 4.4149309396743774e-01 6.9753772020339966e-01 + <_> + + 0 -1 70 -1.8804960418492556e-03 + + 2.7913948893547058e-01 5.4979521036148071e-01 + <_> + + 0 -1 71 7.0889107882976532e-03 + + 5.2631992101669312e-01 2.3855470120906830e-01 + <_> + + 0 -1 72 1.7318050377070904e-03 + + 4.3193790316581726e-01 6.9836008548736572e-01 + <_> + + 0 -1 73 -6.8482700735330582e-03 + + 3.0820429325103760e-01 5.3909200429916382e-01 + <_> + + 0 -1 74 -1.5062530110299122e-05 + + 5.5219221115112305e-01 3.1203660368919373e-01 + <_> + + 0 -1 75 2.9475569725036621e-02 + + 5.4013228416442871e-01 1.7706030607223511e-01 + <_> + + 0 -1 76 8.1387329846620560e-03 + + 5.1786178350448608e-01 1.2110190093517303e-01 + <_> + + 0 -1 77 2.0942950621247292e-02 + + 5.2902942895889282e-01 3.3112218976020813e-01 + <_> + + 0 -1 78 -9.5665529370307922e-03 + + 7.4719941616058350e-01 4.4519689679145813e-01 + <_> + 33 + 1.5324139595031738e+01 + + <_> + + 0 -1 79 -2.8206960996612906e-04 + + 2.0640860497951508e-01 6.0767322778701782e-01 + <_> + + 0 -1 80 1.6790600493550301e-03 + + 5.8519971370697021e-01 1.2553839385509491e-01 + <_> + + 0 -1 81 6.9827912375330925e-04 + + 9.4018429517745972e-02 5.7289612293243408e-01 + <_> + + 0 -1 82 7.8959012171253562e-04 + + 1.7819879949092865e-01 5.6943088769912720e-01 + <_> + + 0 -1 83 -2.8560499195009470e-03 + + 1.6383990645408630e-01 5.7886648178100586e-01 + <_> + + 0 -1 84 -3.8122469559311867e-03 + + 2.0854400098323822e-01 5.5085647106170654e-01 + <_> + + 0 -1 85 1.5896620461717248e-03 + + 5.7027608156204224e-01 1.8572150170803070e-01 + <_> + + 0 -1 86 1.0078339837491512e-02 + + 5.1169431209564209e-01 2.1897700428962708e-01 + <_> + + 0 -1 87 -6.3526302576065063e-02 + + 7.1313798427581787e-01 4.0438130497932434e-01 + <_> + + 0 -1 88 -9.1031491756439209e-03 + + 2.5671818852424622e-01 5.4639732837677002e-01 + <_> + + 0 -1 89 -2.4035000242292881e-03 + + 1.7006659507751465e-01 5.5909740924835205e-01 + <_> + + 0 -1 90 1.5226360410451889e-03 + + 5.4105567932128906e-01 2.6190540194511414e-01 + <_> + + 0 -1 91 1.7997439950704575e-02 + + 3.7324368953704834e-01 6.5352207422256470e-01 + <_> + + 0 -1 92 -6.4538191072642803e-03 + + 2.6264819502830505e-01 5.5374461412429810e-01 + <_> + + 0 -1 93 -1.1880760081112385e-02 + + 2.0037539303302765e-01 5.5447459220886230e-01 + <_> + + 0 -1 94 1.2713660253211856e-03 + + 5.5919027328491211e-01 3.0319759249687195e-01 + <_> + + 0 -1 95 1.1376109905540943e-03 + + 2.7304071187973022e-01 5.6465089321136475e-01 + <_> + + 0 -1 96 -4.2651998810470104e-03 + + 1.4059090614318848e-01 5.4618209600448608e-01 + <_> + + 0 -1 97 -2.9602861031889915e-03 + + 1.7950350046157837e-01 5.4592901468276978e-01 + <_> + + 0 -1 98 -8.8448226451873779e-03 + + 5.7367831468582153e-01 2.8092199563980103e-01 + <_> + + 0 -1 99 -6.6430689767003059e-03 + + 2.3706759512424469e-01 5.5038261413574219e-01 + <_> + + 0 -1 100 3.9997808635234833e-03 + + 5.6081998348236084e-01 3.3042821288108826e-01 + <_> + + 0 -1 101 -4.1221720166504383e-03 + + 1.6401059925556183e-01 5.3789931535720825e-01 + <_> + + 0 -1 102 1.5624909661710262e-02 + + 5.2276492118835449e-01 2.2886039316654205e-01 + <_> + + 0 -1 103 -1.0356419719755650e-02 + + 7.0161938667297363e-01 4.2529278993606567e-01 + <_> + + 0 -1 104 -8.7960809469223022e-03 + + 2.7673470973968506e-01 5.3558301925659180e-01 + <_> + + 0 -1 105 1.6226939857006073e-01 + + 4.3422400951385498e-01 7.4425792694091797e-01 + <_> + + 0 -1 106 4.5542530715465546e-03 + + 5.7264858484268188e-01 2.5821250677108765e-01 + <_> + + 0 -1 107 -2.1309209987521172e-03 + + 2.1068480610847473e-01 5.3610187768936157e-01 + <_> + + 0 -1 108 -1.3208420015871525e-02 + + 7.5937908887863159e-01 4.5524680614471436e-01 + <_> + + 0 -1 109 -6.5996676683425903e-02 + + 1.2524759769439697e-01 5.3440397977828979e-01 + <_> + + 0 -1 110 7.9142656177282333e-03 + + 3.3153840899467468e-01 5.6010431051254272e-01 + <_> + + 0 -1 111 2.0894279703497887e-02 + + 5.5060499906539917e-01 2.7688381075859070e-01 + <_> + 44 + 2.1010639190673828e+01 + + <_> + + 0 -1 112 1.1961159761995077e-03 + + 1.7626909911632538e-01 6.1562412977218628e-01 + <_> + + 0 -1 113 -1.8679830245673656e-03 + + 6.1181068420410156e-01 1.8323999643325806e-01 + <_> + + 0 -1 114 -1.9579799845814705e-04 + + 9.9044263362884521e-02 5.7238161563873291e-01 + <_> + + 0 -1 115 -8.0255657667294145e-04 + + 5.5798798799514771e-01 2.3772829771041870e-01 + <_> + + 0 -1 116 -2.4510810617357492e-03 + + 2.2314579784870148e-01 5.8589351177215576e-01 + <_> + + 0 -1 117 5.0361850298941135e-04 + + 2.6539939641952515e-01 5.7941037416458130e-01 + <_> + + 0 -1 118 4.0293349884450436e-03 + + 5.8038270473480225e-01 2.4848650395870209e-01 + <_> + + 0 -1 119 -1.4451709575951099e-02 + + 1.8303519487380981e-01 5.4842048883438110e-01 + <_> + + 0 -1 120 2.0380979403853416e-03 + + 3.3635589480400085e-01 6.0510927438735962e-01 + <_> + + 0 -1 121 -1.6155190533027053e-03 + + 2.2866420447826385e-01 5.4412460327148438e-01 + <_> + + 0 -1 122 3.3458340913057327e-03 + + 5.6259131431579590e-01 2.3923380672931671e-01 + <_> + + 0 -1 123 1.6379579901695251e-03 + + 3.9069938659667969e-01 5.9646219015121460e-01 + <_> + + 0 -1 124 3.0251210555434227e-02 + + 5.2484822273254395e-01 1.5757469832897186e-01 + <_> + + 0 -1 125 3.7251990288496017e-02 + + 4.1943109035491943e-01 6.7484188079833984e-01 + <_> + + 0 -1 126 -2.5109790265560150e-02 + + 1.8825499713420868e-01 5.4734510183334351e-01 + <_> + + 0 -1 127 -5.3099058568477631e-03 + + 1.3399730622768402e-01 5.2271109819412231e-01 + <_> + + 0 -1 128 1.2086479691788554e-03 + + 3.7620881199836731e-01 6.1096358299255371e-01 + <_> + + 0 -1 129 -2.1907679736614227e-02 + + 2.6631429791450500e-01 5.4040068387985229e-01 + <_> + + 0 -1 130 5.4116579703986645e-03 + + 5.3635787963867188e-01 2.2322730720043182e-01 + <_> + + 0 -1 131 6.9946326315402985e-02 + + 5.3582328557968140e-01 2.4536980688571930e-01 + <_> + + 0 -1 132 3.4520021290518343e-04 + + 2.4096719920635223e-01 5.3769302368164062e-01 + <_> + + 0 -1 133 1.2627709656953812e-03 + + 5.4258567094802856e-01 3.1556931138038635e-01 + <_> + + 0 -1 134 2.2719509899616241e-02 + + 4.1584059596061707e-01 6.5978652238845825e-01 + <_> + + 0 -1 135 -1.8111000536009669e-03 + + 2.8112530708312988e-01 5.5052447319030762e-01 + <_> + + 0 -1 136 3.3469670452177525e-03 + + 5.2600282430648804e-01 1.8914650380611420e-01 + <_> + + 0 -1 137 4.0791751234792173e-04 + + 5.6735092401504517e-01 3.3442100882530212e-01 + <_> + + 0 -1 138 1.2734799645841122e-02 + + 5.3435921669006348e-01 2.3956120014190674e-01 + <_> + + 0 -1 139 -7.3119727894663811e-03 + + 6.0108900070190430e-01 4.0222078561782837e-01 + <_> + + 0 -1 140 -5.6948751211166382e-02 + + 8.1991511583328247e-01 4.5431908965110779e-01 + <_> + + 0 -1 141 -5.0116591155529022e-03 + + 2.2002810239791870e-01 5.3577107191085815e-01 + <_> + + 0 -1 142 6.0334368608891964e-03 + + 4.4130811095237732e-01 7.1817511320114136e-01 + <_> + + 0 -1 143 3.9437441155314445e-03 + + 5.4788607358932495e-01 2.7917331457138062e-01 + <_> + + 0 -1 144 -3.6591119132936001e-03 + + 6.3578677177429199e-01 3.9897239208221436e-01 + <_> + + 0 -1 145 -3.8456181064248085e-03 + + 3.4936860203742981e-01 5.3006649017333984e-01 + <_> + + 0 -1 146 -7.1926261298358440e-03 + + 1.1196149885654449e-01 5.2296727895736694e-01 + <_> + + 0 -1 147 -5.2798941731452942e-02 + + 2.3871029913425446e-01 5.4534512758255005e-01 + <_> + + 0 -1 148 -7.9537667334079742e-03 + + 7.5869178771972656e-01 4.4393768906593323e-01 + <_> + + 0 -1 149 -2.7344180271029472e-03 + + 2.5654768943786621e-01 5.4893219470977783e-01 + <_> + + 0 -1 150 -1.8507939530536532e-03 + + 6.7343479394912720e-01 4.2524749040603638e-01 + <_> + + 0 -1 151 1.5918919816613197e-02 + + 5.4883527755737305e-01 2.2926619648933411e-01 + <_> + + 0 -1 152 -1.2687679845839739e-03 + + 6.1043310165405273e-01 4.0223899483680725e-01 + <_> + + 0 -1 153 6.2883910723030567e-03 + + 5.3108531236648560e-01 1.5361930429935455e-01 + <_> + + 0 -1 154 -6.2259892001748085e-03 + + 1.7291119694709778e-01 5.2416062355041504e-01 + <_> + + 0 -1 155 -1.2132599949836731e-02 + + 6.5977597236633301e-01 4.3251821398735046e-01 + <_> + 50 + 2.3918790817260742e+01 + + <_> + + 0 -1 156 -3.9184908382594585e-03 + + 6.1034351587295532e-01 1.4693309366703033e-01 + <_> + + 0 -1 157 1.5971299726516008e-03 + + 2.6323631405830383e-01 5.8964669704437256e-01 + <_> + + 0 -1 158 1.7780110239982605e-02 + + 5.8728742599487305e-01 1.7603619396686554e-01 + <_> + + 0 -1 159 6.5334769897162914e-04 + + 1.5678019821643829e-01 5.5960661172866821e-01 + <_> + + 0 -1 160 -2.8353091329336166e-04 + + 1.9131539762020111e-01 5.7320362329483032e-01 + <_> + + 0 -1 161 1.6104689566418529e-03 + + 2.9149138927459717e-01 5.6230807304382324e-01 + <_> + + 0 -1 162 -9.7750619053840637e-02 + + 1.9434769451618195e-01 5.6482332944869995e-01 + <_> + + 0 -1 163 5.5182358482852578e-04 + + 3.1346169114112854e-01 5.5046397447586060e-01 + <_> + + 0 -1 164 -1.2858220376074314e-02 + + 2.5364819169044495e-01 5.7601428031921387e-01 + <_> + + 0 -1 165 4.1530239395797253e-03 + + 5.7677221298217773e-01 3.6597740650177002e-01 + <_> + + 0 -1 166 1.7092459602281451e-03 + + 2.8431910276412964e-01 5.9189391136169434e-01 + <_> + + 0 -1 167 7.5217359699308872e-03 + + 4.0524271130561829e-01 6.1831092834472656e-01 + <_> + + 0 -1 168 2.2479810286313295e-03 + + 5.7837551832199097e-01 3.1354010105133057e-01 + <_> + + 0 -1 169 5.2006211131811142e-02 + + 5.5413120985031128e-01 1.9166369736194611e-01 + <_> + + 0 -1 170 1.2085529975593090e-02 + + 4.0326559543609619e-01 6.6445910930633545e-01 + <_> + + 0 -1 171 1.4687820112158079e-05 + + 3.5359779000282288e-01 5.7093828916549683e-01 + <_> + + 0 -1 172 7.1395188570022583e-06 + + 3.0374449491500854e-01 5.6102699041366577e-01 + <_> + + 0 -1 173 -4.6001640148460865e-03 + + 7.1810871362686157e-01 4.5803260803222656e-01 + <_> + + 0 -1 174 2.0058949012309313e-03 + + 5.6219518184661865e-01 2.9536840319633484e-01 + <_> + + 0 -1 175 4.5050270855426788e-03 + + 4.6153879165649414e-01 7.6190179586410522e-01 + <_> + + 0 -1 176 1.1746830306947231e-02 + + 5.3438371419906616e-01 1.7725290358066559e-01 + <_> + + 0 -1 177 -5.8316338807344437e-02 + + 1.6862459480762482e-01 5.3407722711563110e-01 + <_> + + 0 -1 178 2.3629379575140774e-04 + + 3.7920561432838440e-01 6.0268038511276245e-01 + <_> + + 0 -1 179 -7.8156180679798126e-03 + + 1.5128670632839203e-01 5.3243237733840942e-01 + <_> + + 0 -1 180 -1.0876160115003586e-02 + + 2.0818220078945160e-01 5.3199452161788940e-01 + <_> + + 0 -1 181 -2.7745519764721394e-03 + + 4.0982469916343689e-01 5.2103281021118164e-01 + <_> + + 0 -1 182 -7.8276381827890873e-04 + + 5.6932741403579712e-01 3.4788420796394348e-01 + <_> + + 0 -1 183 1.3870409689843655e-02 + + 5.3267508745193481e-01 2.2576980292797089e-01 + <_> + + 0 -1 184 -2.3674910888075829e-02 + + 1.5513050556182861e-01 5.2007079124450684e-01 + <_> + + 0 -1 185 -1.4879409718560055e-05 + + 5.5005669593811035e-01 3.8201761245727539e-01 + <_> + + 0 -1 186 3.6190641112625599e-03 + + 4.2386838793754578e-01 6.6397482156753540e-01 + <_> + + 0 -1 187 -1.9817110151052475e-02 + + 2.1500380337238312e-01 5.3823578357696533e-01 + <_> + + 0 -1 188 -3.8154039066284895e-03 + + 6.6757112741470337e-01 4.2152971029281616e-01 + <_> + + 0 -1 189 -4.9775829538702965e-03 + + 2.2672890126705170e-01 5.3863281011581421e-01 + <_> + + 0 -1 190 2.2441020701080561e-03 + + 4.3086910247802734e-01 6.8557357788085938e-01 + <_> + + 0 -1 191 1.2282459996640682e-02 + + 5.8366149663925171e-01 3.4674790501594543e-01 + <_> + + 0 -1 192 -2.8548699337989092e-03 + + 7.0169448852539062e-01 4.3114539980888367e-01 + <_> + + 0 -1 193 -3.7875669077038765e-03 + + 2.8953450918197632e-01 5.2249461412429810e-01 + <_> + + 0 -1 194 -1.2201230274513364e-03 + + 2.9755708575248718e-01 5.4816448688507080e-01 + <_> + + 0 -1 195 1.0160599835216999e-02 + + 4.8888179659843445e-01 8.1826978921890259e-01 + <_> + + 0 -1 196 -1.6174569725990295e-02 + + 1.4814929664134979e-01 5.2399927377700806e-01 + <_> + + 0 -1 197 1.9292460754513741e-02 + + 4.7863098978996277e-01 7.3781907558441162e-01 + <_> + + 0 -1 198 -3.2479539513587952e-03 + + 7.3742228746414185e-01 4.4706439971923828e-01 + <_> + + 0 -1 199 -9.3803480267524719e-03 + + 3.4891548752784729e-01 5.5379962921142578e-01 + <_> + + 0 -1 200 -1.2606129981577396e-02 + + 2.3796869814395905e-01 5.3154432773590088e-01 + <_> + + 0 -1 201 -2.5621930137276649e-02 + + 1.9646880030632019e-01 5.1387697458267212e-01 + <_> + + 0 -1 202 -7.5741496402770281e-05 + + 5.5905228853225708e-01 3.3658531308174133e-01 + <_> + + 0 -1 203 -8.9210882782936096e-02 + + 6.3404656946659088e-02 5.1626348495483398e-01 + <_> + + 0 -1 204 -2.7670480776578188e-03 + + 7.3234677314758301e-01 4.4907060265541077e-01 + <_> + + 0 -1 205 2.7152578695677221e-04 + + 4.1148349642753601e-01 5.9855180978775024e-01 + <_> + 51 + 2.4527879714965820e+01 + + <_> + + 0 -1 206 1.4786219689995050e-03 + + 2.6635450124740601e-01 6.6433167457580566e-01 + <_> + + 0 -1 207 -1.8741659587249160e-03 + + 6.1438488960266113e-01 2.5185129046440125e-01 + <_> + + 0 -1 208 -1.7151009524241090e-03 + + 5.7663410902023315e-01 2.3974630236625671e-01 + <_> + + 0 -1 209 -1.8939269939437509e-03 + + 5.6820458173751831e-01 2.5291448831558228e-01 + <_> + + 0 -1 210 -5.3006052039563656e-03 + + 1.6406759619712830e-01 5.5560797452926636e-01 + <_> + + 0 -1 211 -4.6662531793117523e-02 + + 6.1231541633605957e-01 4.7628301382064819e-01 + <_> + + 0 -1 212 -7.9431332414969802e-04 + + 5.7078588008880615e-01 2.8394040465354919e-01 + <_> + + 0 -1 213 1.4891670085489750e-02 + + 4.0896728634834290e-01 6.0063672065734863e-01 + <_> + + 0 -1 214 -1.2046529445797205e-03 + + 5.7124507427215576e-01 2.7052891254425049e-01 + <_> + + 0 -1 215 6.0619381256401539e-03 + + 5.2625042200088501e-01 3.2622259855270386e-01 + <_> + + 0 -1 216 -2.5286648888140917e-03 + + 6.8538308143615723e-01 4.1992568969726562e-01 + <_> + + 0 -1 217 -5.9010218828916550e-03 + + 3.2662820816040039e-01 5.4348129034042358e-01 + <_> + + 0 -1 218 5.6702760048210621e-03 + + 5.4684108495712280e-01 2.3190039396286011e-01 + <_> + + 0 -1 219 -3.0304100364446640e-03 + + 5.5706679821014404e-01 2.7082380652427673e-01 + <_> + + 0 -1 220 2.9803649522364140e-03 + + 3.7005689740180969e-01 5.8906257152557373e-01 + <_> + + 0 -1 221 -7.5840510427951813e-02 + + 2.1400700509548187e-01 5.4199481010437012e-01 + <_> + + 0 -1 222 1.9262539222836494e-02 + + 5.5267721414566040e-01 2.7265900373458862e-01 + <_> + + 0 -1 223 1.8888259364757687e-04 + + 3.9580118656158447e-01 6.0172098875045776e-01 + <_> + + 0 -1 224 2.9369549825787544e-02 + + 5.2413737773895264e-01 1.4357580244541168e-01 + <_> + + 0 -1 225 1.0417619487270713e-03 + + 3.3854091167449951e-01 5.9299832582473755e-01 + <_> + + 0 -1 226 2.6125640142709017e-03 + + 5.4853779077529907e-01 3.0215978622436523e-01 + <_> + + 0 -1 227 9.6977467183023691e-04 + + 3.3752760291099548e-01 5.5320328474044800e-01 + <_> + + 0 -1 228 5.9512659208849072e-04 + + 5.6317430734634399e-01 3.3593991398811340e-01 + <_> + + 0 -1 229 -1.0156559944152832e-01 + + 6.3735038042068481e-02 5.2304250001907349e-01 + <_> + + 0 -1 230 3.6156699061393738e-02 + + 5.1369631290435791e-01 1.0295289754867554e-01 + <_> + + 0 -1 231 3.4624140243977308e-03 + + 3.8793200254440308e-01 5.5582892894744873e-01 + <_> + + 0 -1 232 1.9554980099201202e-02 + + 5.2500867843627930e-01 1.8758599460124969e-01 + <_> + + 0 -1 233 -2.3121440317481756e-03 + + 6.6720288991928101e-01 4.6796411275863647e-01 + <_> + + 0 -1 234 -1.8605289515107870e-03 + + 7.1633791923522949e-01 4.3346709012985229e-01 + <_> + + 0 -1 235 -9.4026362057775259e-04 + + 3.0213609337806702e-01 5.6502032279968262e-01 + <_> + + 0 -1 236 -5.2418331615626812e-03 + + 1.8200090527534485e-01 5.2502560615539551e-01 + <_> + + 0 -1 237 1.1729019752237946e-04 + + 3.3891880512237549e-01 5.4459732770919800e-01 + <_> + + 0 -1 238 1.1878840159624815e-03 + + 4.0853491425514221e-01 6.2535631656646729e-01 + <_> + + 0 -1 239 -1.0881359688937664e-02 + + 3.3783990144729614e-01 5.7000827789306641e-01 + <_> + + 0 -1 240 1.7354859737679362e-03 + + 4.2046359181404114e-01 6.5230387449264526e-01 + <_> + + 0 -1 241 -6.5119052305817604e-03 + + 2.5952160358428955e-01 5.4281437397003174e-01 + <_> + + 0 -1 242 -1.2136430013924837e-03 + + 6.1651438474655151e-01 3.9778938889503479e-01 + <_> + + 0 -1 243 -1.0354240424931049e-02 + + 1.6280280053615570e-01 5.2195048332214355e-01 + <_> + + 0 -1 244 5.5858830455690622e-04 + + 3.1996509432792664e-01 5.5035740137100220e-01 + <_> + + 0 -1 245 1.5299649909138680e-02 + + 4.1039940714836121e-01 6.1223882436752319e-01 + <_> + + 0 -1 246 -2.1588210016489029e-02 + + 1.0349129885435104e-01 5.1973849534988403e-01 + <_> + + 0 -1 247 -1.2834629416465759e-01 + + 8.4938651323318481e-01 4.8931029438972473e-01 + <_> + + 0 -1 248 -2.2927189711481333e-03 + + 3.1301578879356384e-01 5.4715752601623535e-01 + <_> + + 0 -1 249 7.9915106296539307e-02 + + 4.8563209176063538e-01 6.0739892721176147e-01 + <_> + + 0 -1 250 -7.9441092908382416e-02 + + 8.3946740627288818e-01 4.6245330572128296e-01 + <_> + + 0 -1 251 -5.2800010889768600e-03 + + 1.8816959857940674e-01 5.3066980838775635e-01 + <_> + + 0 -1 252 1.0463109938427806e-03 + + 5.2712291479110718e-01 2.5830659270286560e-01 + <_> + + 0 -1 253 2.6317298761568964e-04 + + 4.2353048920631409e-01 5.7354408502578735e-01 + <_> + + 0 -1 254 -3.6173160187900066e-03 + + 6.9343960285186768e-01 4.4954448938369751e-01 + <_> + + 0 -1 255 1.1421879753470421e-02 + + 5.9009212255477905e-01 4.1381931304931641e-01 + <_> + + 0 -1 256 -1.9963278900831938e-03 + + 6.4663827419281006e-01 4.3272399902343750e-01 + <_> + 56 + 2.7153350830078125e+01 + + <_> + + 0 -1 257 -9.9691245704889297e-03 + + 6.1423242092132568e-01 2.4822120368480682e-01 + <_> + + 0 -1 258 7.3073059320449829e-04 + + 5.7049518823623657e-01 2.3219659924507141e-01 + <_> + + 0 -1 259 6.4045301405712962e-04 + + 2.1122519671916962e-01 5.8149331808090210e-01 + <_> + + 0 -1 260 4.5424019917845726e-03 + + 2.9504820704460144e-01 5.8663117885589600e-01 + <_> + + 0 -1 261 9.2477443104144186e-05 + + 2.9909908771514893e-01 5.7913267612457275e-01 + <_> + + 0 -1 262 -8.6603146046400070e-03 + + 2.8130298852920532e-01 5.6355422735214233e-01 + <_> + + 0 -1 263 8.0515816807746887e-03 + + 3.5353690385818481e-01 6.0547572374343872e-01 + <_> + + 0 -1 264 4.3835240649059415e-04 + + 5.5965322256088257e-01 2.7315109968185425e-01 + <_> + + 0 -1 265 -9.8168973636347800e-05 + + 5.9780317544937134e-01 3.6385610699653625e-01 + <_> + + 0 -1 266 -1.1298790341243148e-03 + + 2.7552521228790283e-01 5.4327291250228882e-01 + <_> + + 0 -1 267 6.4356150105595589e-03 + + 4.3056419491767883e-01 7.0698332786560059e-01 + <_> + + 0 -1 268 -5.6829329580068588e-02 + + 2.4952429533004761e-01 5.2949970960617065e-01 + <_> + + 0 -1 269 4.0668169967830181e-03 + + 5.4785531759262085e-01 2.4977239966392517e-01 + <_> + + 0 -1 270 4.8164798499783501e-05 + + 3.9386010169982910e-01 5.7063561677932739e-01 + <_> + + 0 -1 271 6.1795017682015896e-03 + + 4.4076061248779297e-01 7.3947668075561523e-01 + <_> + + 0 -1 272 6.4985752105712891e-03 + + 5.4452431201934814e-01 2.4791529774665833e-01 + <_> + + 0 -1 273 -1.0211090557277203e-03 + + 2.5447669625282288e-01 5.3389710187911987e-01 + <_> + + 0 -1 274 -5.4247528314590454e-03 + + 2.7188581228256226e-01 5.3240692615509033e-01 + <_> + + 0 -1 275 -1.0559899965301156e-03 + + 3.1782880425453186e-01 5.5345088243484497e-01 + <_> + + 0 -1 276 6.6465808777138591e-04 + + 4.2842191457748413e-01 6.5581941604614258e-01 + <_> + + 0 -1 277 -2.7524109464138746e-04 + + 5.9028607606887817e-01 3.8102629780769348e-01 + <_> + + 0 -1 278 4.2293202131986618e-03 + + 3.8164898753166199e-01 5.7093858718872070e-01 + <_> + + 0 -1 279 -3.2868210691958666e-03 + + 1.7477439343929291e-01 5.2595442533493042e-01 + <_> + + 0 -1 280 1.5611879643984139e-04 + + 3.6017221212387085e-01 5.7256120443344116e-01 + <_> + + 0 -1 281 -7.3621381488919724e-06 + + 5.4018580913543701e-01 3.0444970726966858e-01 + <_> + + 0 -1 282 -1.4767250046133995e-02 + + 3.2207700610160828e-01 5.5734348297119141e-01 + <_> + + 0 -1 283 2.4489590898156166e-02 + + 4.3015280365943909e-01 6.5188127756118774e-01 + <_> + + 0 -1 284 -3.7652091123163700e-04 + + 3.5645830631256104e-01 5.5982369184494019e-01 + <_> + + 0 -1 285 7.3657688517414499e-06 + + 3.4907829761505127e-01 5.5618977546691895e-01 + <_> + + 0 -1 286 -1.5099939890205860e-02 + + 1.7762720584869385e-01 5.3352999687194824e-01 + <_> + + 0 -1 287 -3.8316650316119194e-03 + + 6.1496877670288086e-01 4.2213940620422363e-01 + <_> + + 0 -1 288 1.6925400123000145e-02 + + 5.4130148887634277e-01 2.1665850281715393e-01 + <_> + + 0 -1 289 -3.0477850232273340e-03 + + 6.4494907855987549e-01 4.3546178936958313e-01 + <_> + + 0 -1 290 3.2140589319169521e-03 + + 5.4001551866531372e-01 3.5232171416282654e-01 + <_> + + 0 -1 291 -4.0023201145231724e-03 + + 2.7745240926742554e-01 5.3384172916412354e-01 + <_> + + 0 -1 292 7.4182129465043545e-03 + + 5.6767392158508301e-01 3.7028178572654724e-01 + <_> + + 0 -1 293 -8.8764587417244911e-03 + + 7.7492219209671021e-01 4.5836889743804932e-01 + <_> + + 0 -1 294 2.7311739977449179e-03 + + 5.3387218713760376e-01 3.9966610074043274e-01 + <_> + + 0 -1 295 -2.5082379579544067e-03 + + 5.6119632720947266e-01 3.7774989008903503e-01 + <_> + + 0 -1 296 -8.0541074275970459e-03 + + 2.9152289032936096e-01 5.1791828870773315e-01 + <_> + + 0 -1 297 -9.7938813269138336e-04 + + 5.5364328622817993e-01 3.7001928687095642e-01 + <_> + + 0 -1 298 -5.8745909482240677e-03 + + 3.7543910741806030e-01 5.6793761253356934e-01 + <_> + + 0 -1 299 -4.4936719350516796e-03 + + 7.0196992158889771e-01 4.4809499382972717e-01 + <_> + + 0 -1 300 -5.4389229044318199e-03 + + 2.3103649914264679e-01 5.3133869171142578e-01 + <_> + + 0 -1 301 -7.5094640487805009e-04 + + 5.8648687601089478e-01 4.1293430328369141e-01 + <_> + + 0 -1 302 1.4528800420521293e-05 + + 3.7324070930480957e-01 5.6196212768554688e-01 + <_> + + 0 -1 303 4.0758069604635239e-02 + + 5.3120911121368408e-01 2.7205219864845276e-01 + <_> + + 0 -1 304 6.6505931317806244e-03 + + 4.7100159525871277e-01 6.6934937238693237e-01 + <_> + + 0 -1 305 4.5759351924061775e-03 + + 5.1678192615509033e-01 1.6372759640216827e-01 + <_> + + 0 -1 306 6.5269311890006065e-03 + + 5.3976088762283325e-01 2.9385319352149963e-01 + <_> + + 0 -1 307 -1.3660379685461521e-02 + + 7.0864880084991455e-01 4.5322000980377197e-01 + <_> + + 0 -1 308 2.7358869090676308e-02 + + 5.2064812183380127e-01 3.5892319679260254e-01 + <_> + + 0 -1 309 6.2197551596909761e-04 + + 3.5070759057998657e-01 5.4411232471466064e-01 + <_> + + 0 -1 310 -3.3077080734074116e-03 + + 5.8595228195190430e-01 4.0248918533325195e-01 + <_> + + 0 -1 311 -1.0631109587848186e-02 + + 6.7432671785354614e-01 4.4226029515266418e-01 + <_> + + 0 -1 312 1.9441649317741394e-02 + + 5.2827161550521851e-01 1.7979049682617188e-01 + <_> + 71 + 3.4554111480712891e+01 + + <_> + + 0 -1 313 -5.5052167735993862e-03 + + 5.9147310256958008e-01 2.6265591382980347e-01 + <_> + + 0 -1 314 1.9562279339879751e-03 + + 2.3125819861888885e-01 5.7416272163391113e-01 + <_> + + 0 -1 315 -8.8924784213304520e-03 + + 1.6565300524234772e-01 5.6266540288925171e-01 + <_> + + 0 -1 316 8.3638377487659454e-02 + + 5.4234498739242554e-01 1.9572949409484863e-01 + <_> + + 0 -1 317 1.2282270472496748e-03 + + 3.4179040789604187e-01 5.9925037622451782e-01 + <_> + + 0 -1 318 5.7629169896245003e-03 + + 3.7195819616317749e-01 6.0799038410186768e-01 + <_> + + 0 -1 319 -1.6417410224676132e-03 + + 2.5774860382080078e-01 5.5769157409667969e-01 + <_> + + 0 -1 320 3.4113149158656597e-03 + + 2.9507490992546082e-01 5.5141717195510864e-01 + <_> + + 0 -1 321 -1.1069320142269135e-02 + + 7.5693589448928833e-01 4.4770789146423340e-01 + <_> + + 0 -1 322 3.4865971654653549e-02 + + 5.5837088823318481e-01 2.6696211099624634e-01 + <_> + + 0 -1 323 6.5701099811121821e-04 + + 5.6273132562637329e-01 2.9888901114463806e-01 + <_> + + 0 -1 324 -2.4339130148291588e-02 + + 2.7711850404739380e-01 5.1088631153106689e-01 + <_> + + 0 -1 325 5.9435202274471521e-04 + + 5.5806517601013184e-01 3.1203418970108032e-01 + <_> + + 0 -1 326 2.2971509024500847e-03 + + 3.3302500844001770e-01 5.6790757179260254e-01 + <_> + + 0 -1 327 -3.7801829166710377e-03 + + 2.9905349016189575e-01 5.3448081016540527e-01 + <_> + + 0 -1 328 -1.3420669734477997e-01 + + 1.4638589322566986e-01 5.3925681114196777e-01 + <_> + + 0 -1 329 7.5224548345431685e-04 + + 3.7469539046287537e-01 5.6927347183227539e-01 + <_> + + 0 -1 330 -4.0545541793107986e-02 + + 2.7547478675842285e-01 5.4842978715896606e-01 + <_> + + 0 -1 331 1.2572970008477569e-03 + + 3.7445840239524841e-01 5.7560759782791138e-01 + <_> + + 0 -1 332 -7.4249948374927044e-03 + + 7.5138592720031738e-01 4.7282311320304871e-01 + <_> + + 0 -1 333 5.0908129196614027e-04 + + 5.4048967361450195e-01 2.9323211312294006e-01 + <_> + + 0 -1 334 -1.2808450264856219e-03 + + 6.1697798967361450e-01 4.2733490467071533e-01 + <_> + + 0 -1 335 -1.8348860321566463e-03 + + 2.0484960079193115e-01 5.2064722776412964e-01 + <_> + + 0 -1 336 2.7484869584441185e-02 + + 5.2529847621917725e-01 1.6755220293998718e-01 + <_> + + 0 -1 337 2.2372419480234385e-03 + + 5.2677828073501587e-01 2.7776581048965454e-01 + <_> + + 0 -1 338 -8.8635291904211044e-03 + + 6.9545578956604004e-01 4.8120489716529846e-01 + <_> + + 0 -1 339 4.1753971017897129e-03 + + 4.2918878793716431e-01 6.3491958379745483e-01 + <_> + + 0 -1 340 -1.7098189564421773e-03 + + 2.9305368661880493e-01 5.3612488508224487e-01 + <_> + + 0 -1 341 6.5328548662364483e-03 + + 4.4953250885009766e-01 7.4096941947937012e-01 + <_> + + 0 -1 342 -9.5372907817363739e-03 + + 3.1491199135780334e-01 5.4165017604827881e-01 + <_> + + 0 -1 343 2.5310989469289780e-02 + + 5.1218920946121216e-01 1.3117079436779022e-01 + <_> + + 0 -1 344 3.6460969597101212e-02 + + 5.1759117841720581e-01 2.5913399457931519e-01 + <_> + + 0 -1 345 2.0854329690337181e-02 + + 5.1371401548385620e-01 1.5823160111904144e-01 + <_> + + 0 -1 346 -8.7207747856155038e-04 + + 5.5743098258972168e-01 4.3989789485931396e-01 + <_> + + 0 -1 347 -1.5227000403683633e-05 + + 5.5489408969879150e-01 3.7080699205398560e-01 + <_> + + 0 -1 348 -8.4316509310156107e-04 + + 3.3874198794364929e-01 5.5542111396789551e-01 + <_> + + 0 -1 349 3.6037859972566366e-03 + + 5.3580617904663086e-01 3.4111711382865906e-01 + <_> + + 0 -1 350 -6.8057891912758350e-03 + + 6.1252027750015259e-01 4.3458628654479980e-01 + <_> + + 0 -1 351 -4.7021660953760147e-02 + + 2.3581659793853760e-01 5.1937389373779297e-01 + <_> + + 0 -1 352 -3.6954108625650406e-02 + + 7.3231112957000732e-01 4.7609439492225647e-01 + <_> + + 0 -1 353 1.0439479956403375e-03 + + 5.4194551706314087e-01 3.4113308787345886e-01 + <_> + + 0 -1 354 -2.1050689974799752e-04 + + 2.8216940164566040e-01 5.5549472570419312e-01 + <_> + + 0 -1 355 -8.0831587314605713e-02 + + 9.1299301385879517e-01 4.6974349021911621e-01 + <_> + + 0 -1 356 -3.6579059087671340e-04 + + 6.0226702690124512e-01 3.9782929420471191e-01 + <_> + + 0 -1 357 -1.2545920617412776e-04 + + 5.6132131814956665e-01 3.8455399870872498e-01 + <_> + + 0 -1 358 -6.8786486983299255e-02 + + 2.2616119682788849e-01 5.3004968166351318e-01 + <_> + + 0 -1 359 1.2415789999067783e-02 + + 4.0756919980049133e-01 5.8288121223449707e-01 + <_> + + 0 -1 360 -4.7174817882478237e-03 + + 2.8272539377212524e-01 5.2677577733993530e-01 + <_> + + 0 -1 361 3.8136858493089676e-02 + + 5.0747412443161011e-01 1.0236159712076187e-01 + <_> + + 0 -1 362 -2.8168049175292253e-03 + + 6.1690068244934082e-01 4.3596929311752319e-01 + <_> + + 0 -1 363 8.1303603947162628e-03 + + 4.5244330167770386e-01 7.6060950756072998e-01 + <_> + + 0 -1 364 6.0056019574403763e-03 + + 5.2404087781906128e-01 1.8597120046615601e-01 + <_> + + 0 -1 365 1.9139319658279419e-02 + + 5.2093791961669922e-01 2.3320719599723816e-01 + <_> + + 0 -1 366 1.6445759683847427e-02 + + 5.4507029056549072e-01 3.2642349600791931e-01 + <_> + + 0 -1 367 -3.7356890738010406e-02 + + 6.9990468025207520e-01 4.5332419872283936e-01 + <_> + + 0 -1 368 -1.9727900624275208e-02 + + 2.6536649465560913e-01 5.4128098487854004e-01 + <_> + + 0 -1 369 6.6972579807043076e-03 + + 4.4805660843849182e-01 7.1386522054672241e-01 + <_> + + 0 -1 370 7.4457528535276651e-04 + + 4.2313501238822937e-01 5.4713201522827148e-01 + <_> + + 0 -1 371 1.1790640419349074e-03 + + 5.3417021036148071e-01 3.1304550170898438e-01 + <_> + + 0 -1 372 3.4980610013008118e-02 + + 5.1186597347259521e-01 3.4305301308631897e-01 + <_> + + 0 -1 373 5.6859792675822973e-04 + + 3.5321870446205139e-01 5.4686397314071655e-01 + <_> + + 0 -1 374 -1.1340649798512459e-02 + + 2.8423538804054260e-01 5.3487008810043335e-01 + <_> + + 0 -1 375 -6.6228108480572701e-03 + + 6.8836402893066406e-01 4.4926649332046509e-01 + <_> + + 0 -1 376 -8.0160330981016159e-03 + + 1.7098939418792725e-01 5.2243089675903320e-01 + <_> + + 0 -1 377 1.4206819469109178e-03 + + 5.2908462285995483e-01 2.9933831095695496e-01 + <_> + + 0 -1 378 -2.7801711112260818e-03 + + 6.4988541603088379e-01 4.4604998826980591e-01 + <_> + + 0 -1 379 -1.4747589593753219e-03 + + 3.2604381442070007e-01 5.3881132602691650e-01 + <_> + + 0 -1 380 -2.3830339312553406e-02 + + 7.5289410352706909e-01 4.8012199997901917e-01 + <_> + + 0 -1 381 6.9369790144264698e-03 + + 5.3351658582687378e-01 3.2614278793334961e-01 + <_> + + 0 -1 382 8.2806255668401718e-03 + + 4.5803940296173096e-01 5.7378298044204712e-01 + <_> + + 0 -1 383 -1.0439500212669373e-02 + + 2.5923201441764832e-01 5.2338278293609619e-01 + <_> + 80 + 3.9107288360595703e+01 + + <_> + + 0 -1 384 7.2006587870419025e-03 + + 3.2588860392570496e-01 6.8498080968856812e-01 + <_> + + 0 -1 385 -2.8593589086085558e-03 + + 5.8388811349868774e-01 2.5378298759460449e-01 + <_> + + 0 -1 386 6.8580528022721410e-04 + + 5.7080817222595215e-01 2.8124240040779114e-01 + <_> + + 0 -1 387 7.9580191522836685e-03 + + 2.5010511279106140e-01 5.5442607402801514e-01 + <_> + + 0 -1 388 -1.2124150525778532e-03 + + 2.3853680491447449e-01 5.4333502054214478e-01 + <_> + + 0 -1 389 7.9426132142543793e-03 + + 3.9550709724426270e-01 6.2207579612731934e-01 + <_> + + 0 -1 390 2.4630590341985226e-03 + + 5.6397080421447754e-01 2.9923579096794128e-01 + <_> + + 0 -1 391 -6.0396599583327770e-03 + + 2.1865129470825195e-01 5.4116767644882202e-01 + <_> + + 0 -1 392 -1.2988339876756072e-03 + + 2.3507060110569000e-01 5.3645849227905273e-01 + <_> + + 0 -1 393 2.2299369447864592e-04 + + 3.8041129708290100e-01 5.7296061515808105e-01 + <_> + + 0 -1 394 1.4654280385002494e-03 + + 2.5101679563522339e-01 5.2582687139511108e-01 + <_> + + 0 -1 395 -8.1210042117163539e-04 + + 5.9928238391876221e-01 3.8511589169502258e-01 + <_> + + 0 -1 396 -1.3836020370945334e-03 + + 5.6813961267471313e-01 3.6365869641304016e-01 + <_> + + 0 -1 397 -2.7936449274420738e-02 + + 1.4913170039653778e-01 5.3775602579116821e-01 + <_> + + 0 -1 398 -4.6919551095925272e-04 + + 3.6924299597740173e-01 5.5724847316741943e-01 + <_> + + 0 -1 399 -4.9829659983515739e-03 + + 6.7585092782974243e-01 4.5325040817260742e-01 + <_> + + 0 -1 400 1.8815309740602970e-03 + + 5.3680229187011719e-01 2.9325398802757263e-01 + <_> + + 0 -1 401 -1.9067550078034401e-02 + + 1.6493770480155945e-01 5.3300672769546509e-01 + <_> + + 0 -1 402 -4.6906559728085995e-03 + + 1.9639259576797485e-01 5.1193618774414062e-01 + <_> + + 0 -1 403 5.9777139686048031e-03 + + 4.6711719036102295e-01 7.0083981752395630e-01 + <_> + + 0 -1 404 -3.3303130418062210e-02 + + 1.1554169654846191e-01 5.1041620969772339e-01 + <_> + + 0 -1 405 9.0744107961654663e-02 + + 5.1496601104736328e-01 1.3061730563640594e-01 + <_> + + 0 -1 406 9.3555898638442159e-04 + + 3.6054810881614685e-01 5.4398590326309204e-01 + <_> + + 0 -1 407 1.4901650138199329e-02 + + 4.8862120509147644e-01 7.6875698566436768e-01 + <_> + + 0 -1 408 6.1594118596985936e-04 + + 5.3568130731582642e-01 3.2409390807151794e-01 + <_> + + 0 -1 409 -5.0670988857746124e-02 + + 1.8486219644546509e-01 5.2304041385650635e-01 + <_> + + 0 -1 410 6.8665749859064817e-04 + + 3.8405799865722656e-01 5.5179458856582642e-01 + <_> + + 0 -1 411 8.3712432533502579e-03 + + 4.2885640263557434e-01 6.1317539215087891e-01 + <_> + + 0 -1 412 -1.2953069526702166e-03 + + 2.9136741161346436e-01 5.2807378768920898e-01 + <_> + + 0 -1 413 -4.1941680014133453e-02 + + 7.5547999143600464e-01 4.8560309410095215e-01 + <_> + + 0 -1 414 -2.3529380559921265e-02 + + 2.8382799029350281e-01 5.2560812234878540e-01 + <_> + + 0 -1 415 4.0857449173927307e-02 + + 4.8709350824356079e-01 6.2772971391677856e-01 + <_> + + 0 -1 416 -2.5406869128346443e-02 + + 7.0997077226638794e-01 4.5750290155410767e-01 + <_> + + 0 -1 417 -4.1415440500713885e-04 + + 4.0308868885040283e-01 5.4694122076034546e-01 + <_> + + 0 -1 418 2.1824119612574577e-02 + + 4.5020240545272827e-01 6.7687010765075684e-01 + <_> + + 0 -1 419 1.4114039950072765e-02 + + 5.4428607225418091e-01 3.7917000055313110e-01 + <_> + + 0 -1 420 6.7214590671937913e-05 + + 4.2004638910293579e-01 5.8734762668609619e-01 + <_> + + 0 -1 421 -7.9417638480663300e-03 + + 3.7925618886947632e-01 5.5852657556533813e-01 + <_> + + 0 -1 422 -7.2144409641623497e-03 + + 7.2531038522720337e-01 4.6035489439964294e-01 + <_> + + 0 -1 423 2.5817339774221182e-03 + + 4.6933019161224365e-01 5.9002387523651123e-01 + <_> + + 0 -1 424 1.3409319519996643e-01 + + 5.1492130756378174e-01 1.8088449537754059e-01 + <_> + + 0 -1 425 2.2962710354477167e-03 + + 5.3997439146041870e-01 3.7178671360015869e-01 + <_> + + 0 -1 426 -2.1575849968940020e-03 + + 2.4084959924221039e-01 5.1488637924194336e-01 + <_> + + 0 -1 427 -4.9196188338100910e-03 + + 6.5735882520675659e-01 4.7387400269508362e-01 + <_> + + 0 -1 428 1.6267469618469477e-03 + + 4.1928219795227051e-01 6.3031142950057983e-01 + <_> + + 0 -1 429 3.3413388882763684e-04 + + 5.5402982234954834e-01 3.7021011114120483e-01 + <_> + + 0 -1 430 -2.6698080822825432e-02 + + 1.7109179496765137e-01 5.1014107465744019e-01 + <_> + + 0 -1 431 -3.0561879277229309e-02 + + 1.9042180478572845e-01 5.1687937974929810e-01 + <_> + + 0 -1 432 2.8511548880487680e-03 + + 4.4475069642066956e-01 6.3138538599014282e-01 + <_> + + 0 -1 433 -3.6211479455232620e-02 + + 2.4907270073890686e-01 5.3773492574691772e-01 + <_> + + 0 -1 434 -2.4115189444273710e-03 + + 5.3812432289123535e-01 3.6642369627952576e-01 + <_> + + 0 -1 435 -7.7253201743587852e-04 + + 5.5302321910858154e-01 3.5415500402450562e-01 + <_> + + 0 -1 436 2.9481729143299162e-04 + + 4.1326990723609924e-01 5.6672430038452148e-01 + <_> + + 0 -1 437 -6.2334560789167881e-03 + + 9.8787233233451843e-02 5.1986688375473022e-01 + <_> + + 0 -1 438 -2.6274729520082474e-02 + + 9.1127492487430573e-02 5.0281071662902832e-01 + <_> + + 0 -1 439 5.3212260827422142e-03 + + 4.7266489267349243e-01 6.2227207422256470e-01 + <_> + + 0 -1 440 -4.1129058226943016e-03 + + 2.1574570238590240e-01 5.1378047466278076e-01 + <_> + + 0 -1 441 3.2457809429615736e-03 + + 5.4107707738876343e-01 3.7217769026756287e-01 + <_> + + 0 -1 442 -1.6359709203243256e-02 + + 7.7878749370574951e-01 4.6852919459342957e-01 + <_> + + 0 -1 443 3.2166109303943813e-04 + + 5.4789870977401733e-01 4.2403739690780640e-01 + <_> + + 0 -1 444 6.4452440710738301e-04 + + 5.3305608034133911e-01 3.5013249516487122e-01 + <_> + + 0 -1 445 -7.8909732401371002e-03 + + 6.9235211610794067e-01 4.7265690565109253e-01 + <_> + + 0 -1 446 4.8336211591959000e-02 + + 5.0559002161026001e-01 7.5749203562736511e-02 + <_> + + 0 -1 447 -7.5178127735853195e-04 + + 3.7837418913841248e-01 5.5385738611221313e-01 + <_> + + 0 -1 448 -2.4953910615295172e-03 + + 3.0816510319709778e-01 5.3596121072769165e-01 + <_> + + 0 -1 449 -2.2385010961443186e-03 + + 6.6339588165283203e-01 4.6493428945541382e-01 + <_> + + 0 -1 450 -1.7988430336117744e-03 + + 6.5968447923660278e-01 4.3471878767013550e-01 + <_> + + 0 -1 451 8.7860915809869766e-03 + + 5.2318328619003296e-01 2.3155799508094788e-01 + <_> + + 0 -1 452 3.6715380847454071e-03 + + 5.2042502164840698e-01 2.9773768782615662e-01 + <_> + + 0 -1 453 -3.5336449742317200e-02 + + 7.2388780117034912e-01 4.8615050315856934e-01 + <_> + + 0 -1 454 -6.9189240457490087e-04 + + 3.1050220131874084e-01 5.2298247814178467e-01 + <_> + + 0 -1 455 -3.3946109469980001e-03 + + 3.1389680504798889e-01 5.2101737260818481e-01 + <_> + + 0 -1 456 9.8569283727556467e-04 + + 4.5365801453590393e-01 6.5850979089736938e-01 + <_> + + 0 -1 457 -5.0163101404905319e-02 + + 1.8044540286064148e-01 5.1989167928695679e-01 + <_> + + 0 -1 458 -2.2367259953171015e-03 + + 7.2557020187377930e-01 4.6513590216636658e-01 + <_> + + 0 -1 459 7.4326287722215056e-04 + + 4.4129210710525513e-01 5.8985459804534912e-01 + <_> + + 0 -1 460 -9.3485182151198387e-04 + + 3.5000529885292053e-01 5.3660178184509277e-01 + <_> + + 0 -1 461 1.7497939988970757e-02 + + 4.9121949076652527e-01 8.3152848482131958e-01 + <_> + + 0 -1 462 -1.5200000489130616e-03 + + 3.5702759027481079e-01 5.3705602884292603e-01 + <_> + + 0 -1 463 7.8003940870985389e-04 + + 4.3537721037864685e-01 5.9673351049423218e-01 + <_> + 103 + 5.0610481262207031e+01 + + <_> + + 0 -1 464 -9.9945552647113800e-03 + + 6.1625832319259644e-01 3.0545330047607422e-01 + <_> + + 0 -1 465 -1.1085229925811291e-03 + + 5.8182948827743530e-01 3.1555780768394470e-01 + <_> + + 0 -1 466 1.0364380432292819e-03 + + 2.5520521402359009e-01 5.6929117441177368e-01 + <_> + + 0 -1 467 6.8211311008781195e-04 + + 3.6850899457931519e-01 5.9349310398101807e-01 + <_> + + 0 -1 468 -6.8057340104132891e-04 + + 2.3323920369148254e-01 5.4747921228408813e-01 + <_> + + 0 -1 469 2.6068789884448051e-04 + + 3.2574570178985596e-01 5.6675457954406738e-01 + <_> + + 0 -1 470 5.1607372006401420e-04 + + 3.7447169423103333e-01 5.8454728126525879e-01 + <_> + + 0 -1 471 8.5007521556690335e-04 + + 3.4203711152076721e-01 5.5228072404861450e-01 + <_> + + 0 -1 472 -1.8607829697430134e-03 + + 2.8044199943542480e-01 5.3754240274429321e-01 + <_> + + 0 -1 473 -1.5033970121294260e-03 + + 2.5790509581565857e-01 5.4989522695541382e-01 + <_> + + 0 -1 474 2.3478909861296415e-03 + + 4.1751560568809509e-01 6.3137108087539673e-01 + <_> + + 0 -1 475 -2.8880240279249847e-04 + + 5.8651697635650635e-01 4.0526661276817322e-01 + <_> + + 0 -1 476 8.9405477046966553e-03 + + 5.2111411094665527e-01 2.3186540603637695e-01 + <_> + + 0 -1 477 -1.9327739253640175e-02 + + 2.7534329891204834e-01 5.2415257692337036e-01 + <_> + + 0 -1 478 -2.0202060113660991e-04 + + 5.7229787111282349e-01 3.6771959066390991e-01 + <_> + + 0 -1 479 2.1179069299250841e-03 + + 4.4661080837249756e-01 5.5424308776855469e-01 + <_> + + 0 -1 480 -1.7743760254234076e-03 + + 2.8132531046867371e-01 5.3009599447250366e-01 + <_> + + 0 -1 481 4.2234458960592747e-03 + + 4.3997099995613098e-01 5.7954281568527222e-01 + <_> + + 0 -1 482 -1.4375220052897930e-02 + + 2.9811179637908936e-01 5.2920591831207275e-01 + <_> + + 0 -1 483 -1.5349180437624454e-02 + + 7.7052152156829834e-01 4.7481718659400940e-01 + <_> + + 0 -1 484 1.5152279956964776e-05 + + 3.7188440561294556e-01 5.5768972635269165e-01 + <_> + + 0 -1 485 -9.1293919831514359e-03 + + 3.6151960492134094e-01 5.2867668867111206e-01 + <_> + + 0 -1 486 2.2512159775942564e-03 + + 5.3647047281265259e-01 3.4862980246543884e-01 + <_> + + 0 -1 487 -4.9696918576955795e-03 + + 6.9276517629623413e-01 4.6768361330032349e-01 + <_> + + 0 -1 488 -1.2829010374844074e-02 + + 7.7121537923812866e-01 4.6607351303100586e-01 + <_> + + 0 -1 489 -9.3660065904259682e-03 + + 3.3749839663505554e-01 5.3512877225875854e-01 + <_> + + 0 -1 490 3.2452319283038378e-03 + + 5.3251898288726807e-01 3.2896101474761963e-01 + <_> + + 0 -1 491 -1.1723560281097889e-02 + + 6.8376529216766357e-01 4.7543001174926758e-01 + <_> + + 0 -1 492 2.9257940695970319e-05 + + 3.5720878839492798e-01 5.3605020046234131e-01 + <_> + + 0 -1 493 -2.2244219508138485e-05 + + 5.5414271354675293e-01 3.5520640015602112e-01 + <_> + + 0 -1 494 5.0881509669125080e-03 + + 5.0708442926406860e-01 1.2564620375633240e-01 + <_> + + 0 -1 495 2.7429679408669472e-02 + + 5.2695602178573608e-01 1.6258180141448975e-01 + <_> + + 0 -1 496 -6.4142867922782898e-03 + + 7.1455889940261841e-01 4.5841971039772034e-01 + <_> + + 0 -1 497 3.3479959238320589e-03 + + 5.3986120223999023e-01 3.4946969151496887e-01 + <_> + + 0 -1 498 -8.2635492086410522e-02 + + 2.4391929805278778e-01 5.1602262258529663e-01 + <_> + + 0 -1 499 1.0261740535497665e-03 + + 3.8868919014930725e-01 5.7679080963134766e-01 + <_> + + 0 -1 500 -1.6307090409100056e-03 + + 3.3894580602645874e-01 5.3477007150650024e-01 + <_> + + 0 -1 501 2.4546680506318808e-03 + + 4.6014139056205750e-01 6.3872468471527100e-01 + <_> + + 0 -1 502 -9.9476519972085953e-04 + + 5.7698792219161987e-01 4.1203960776329041e-01 + <_> + + 0 -1 503 1.5409190207719803e-02 + + 4.8787090182304382e-01 7.0898222923278809e-01 + <_> + + 0 -1 504 1.1784400558099151e-03 + + 5.2635532617568970e-01 2.8952449560165405e-01 + <_> + + 0 -1 505 -2.7701919898390770e-02 + + 1.4988289773464203e-01 5.2196067571640015e-01 + <_> + + 0 -1 506 -2.9505399987101555e-02 + + 2.4893319234251976e-02 4.9998161196708679e-01 + <_> + + 0 -1 507 4.5159430010244250e-04 + + 5.4646229743957520e-01 4.0296629071235657e-01 + <_> + + 0 -1 508 7.1772639639675617e-03 + + 4.2710569500923157e-01 5.8662968873977661e-01 + <_> + + 0 -1 509 -7.4182048439979553e-02 + + 6.8741792440414429e-01 4.9190279841423035e-01 + <_> + + 0 -1 510 -1.7254160717129707e-02 + + 3.3706760406494141e-01 5.3487390279769897e-01 + <_> + + 0 -1 511 1.4851559884846210e-02 + + 4.6267929673194885e-01 6.1299049854278564e-01 + <_> + + 0 -1 512 1.0002000257372856e-02 + + 5.3461229801177979e-01 3.4234538674354553e-01 + <_> + + 0 -1 513 2.0138120744377375e-03 + + 4.6438300609588623e-01 5.8243042230606079e-01 + <_> + + 0 -1 514 1.5135470312088728e-03 + + 5.1963961124420166e-01 2.8561499714851379e-01 + <_> + + 0 -1 515 3.1381431035697460e-03 + + 4.8381629586219788e-01 5.9585297107696533e-01 + <_> + + 0 -1 516 -5.1450440660119057e-03 + + 8.9203029870986938e-01 4.7414121031761169e-01 + <_> + + 0 -1 517 -4.4736708514392376e-03 + + 2.0339429378509521e-01 5.3372788429260254e-01 + <_> + + 0 -1 518 1.9628470763564110e-03 + + 4.5716339349746704e-01 6.7258632183074951e-01 + <_> + + 0 -1 519 5.4260450415313244e-03 + + 5.2711081504821777e-01 2.8456708788871765e-01 + <_> + + 0 -1 520 4.9611460417509079e-04 + + 4.1383129358291626e-01 5.7185977697372437e-01 + <_> + + 0 -1 521 9.3728788197040558e-03 + + 5.2251511812210083e-01 2.8048470616340637e-01 + <_> + + 0 -1 522 6.0500897234305739e-04 + + 5.2367687225341797e-01 3.3145239949226379e-01 + <_> + + 0 -1 523 5.6792551185935736e-04 + + 4.5310598611831665e-01 6.2769711017608643e-01 + <_> + + 0 -1 524 2.4644339457154274e-02 + + 5.1308518648147583e-01 2.0171439647674561e-01 + <_> + + 0 -1 525 -1.0290450416505337e-02 + + 7.7865952253341675e-01 4.8766410350799561e-01 + <_> + + 0 -1 526 2.0629419013857841e-03 + + 4.2885988950729370e-01 5.8812642097473145e-01 + <_> + + 0 -1 527 -5.0519481301307678e-03 + + 3.5239779949188232e-01 5.2860087156295776e-01 + <_> + + 0 -1 528 -5.7692620903253555e-03 + + 6.8410861492156982e-01 4.5880940556526184e-01 + <_> + + 0 -1 529 -4.5789941214025021e-04 + + 3.5655200481414795e-01 5.4859781265258789e-01 + <_> + + 0 -1 530 -7.5918837683275342e-04 + + 3.3687931299209595e-01 5.2541971206665039e-01 + <_> + + 0 -1 531 -1.7737259622663260e-03 + + 3.4221610426902771e-01 5.4540151357650757e-01 + <_> + + 0 -1 532 -8.5610467940568924e-03 + + 6.5336120128631592e-01 4.4858568906784058e-01 + <_> + + 0 -1 533 1.7277270089834929e-03 + + 5.3075802326202393e-01 3.9253529906272888e-01 + <_> + + 0 -1 534 -2.8199609369039536e-02 + + 6.8574589490890503e-01 4.5885840058326721e-01 + <_> + + 0 -1 535 -1.7781109781935811e-03 + + 4.0378510951995850e-01 5.3698569536209106e-01 + <_> + + 0 -1 536 3.3177141449414194e-04 + + 5.3997987508773804e-01 3.7057501077651978e-01 + <_> + + 0 -1 537 2.6385399978607893e-03 + + 4.6654370427131653e-01 6.4527308940887451e-01 + <_> + + 0 -1 538 -2.1183069329708815e-03 + + 5.9147810935974121e-01 4.0646770596504211e-01 + <_> + + 0 -1 539 -1.4773289673030376e-02 + + 3.6420381069183350e-01 5.2947628498077393e-01 + <_> + + 0 -1 540 -1.6815440729260445e-02 + + 2.6642319560050964e-01 5.1449728012084961e-01 + <_> + + 0 -1 541 -6.3370140269398689e-03 + + 6.7795312404632568e-01 4.8520979285240173e-01 + <_> + + 0 -1 542 -4.4560048991115764e-05 + + 5.6139647960662842e-01 4.1530540585517883e-01 + <_> + + 0 -1 543 -1.0240620467811823e-03 + + 5.9644782543182373e-01 4.5663040876388550e-01 + <_> + + 0 -1 544 -2.3161689750850201e-03 + + 2.9761150479316711e-01 5.1881599426269531e-01 + <_> + + 0 -1 545 5.3217571973800659e-01 + + 5.1878392696380615e-01 2.2026319801807404e-01 + <_> + + 0 -1 546 -1.6643050312995911e-01 + + 1.8660229444503784e-01 5.0603431463241577e-01 + <_> + + 0 -1 547 1.1253529787063599e-01 + + 5.2121251821517944e-01 1.1850229650735855e-01 + <_> + + 0 -1 548 9.3046864494681358e-03 + + 4.5899370312690735e-01 6.8261492252349854e-01 + <_> + + 0 -1 549 -4.6255099587142467e-03 + + 3.0799409747123718e-01 5.2250087261199951e-01 + <_> + + 0 -1 550 -1.1116469651460648e-01 + + 2.1010440587997437e-01 5.0808018445968628e-01 + <_> + + 0 -1 551 -1.0888439603149891e-02 + + 5.7653552293777466e-01 4.7904640436172485e-01 + <_> + + 0 -1 552 5.8564301580190659e-03 + + 5.0651001930236816e-01 1.5635989606380463e-01 + <_> + + 0 -1 553 5.4854389280080795e-02 + + 4.9669149518013000e-01 7.2305107116699219e-01 + <_> + + 0 -1 554 -1.1197339743375778e-02 + + 2.1949790418148041e-01 5.0987982749938965e-01 + <_> + + 0 -1 555 4.4069071300327778e-03 + + 4.7784018516540527e-01 6.7709028720855713e-01 + <_> + + 0 -1 556 -6.3665293157100677e-02 + + 1.9363629817962646e-01 5.0810241699218750e-01 + <_> + + 0 -1 557 -9.8081491887569427e-03 + + 5.9990632534027100e-01 4.8103410005569458e-01 + <_> + + 0 -1 558 -2.1717099007219076e-03 + + 3.3383339643478394e-01 5.2354729175567627e-01 + <_> + + 0 -1 559 -1.3315520249307156e-02 + + 6.6170698404312134e-01 4.9192130565643311e-01 + <_> + + 0 -1 560 2.5442079640924931e-03 + + 4.4887441396713257e-01 6.0821849107742310e-01 + <_> + + 0 -1 561 1.2037839740514755e-02 + + 5.4093921184539795e-01 3.2924321293830872e-01 + <_> + + 0 -1 562 -2.0701050758361816e-02 + + 6.8191200494766235e-01 4.5949959754943848e-01 + <_> + + 0 -1 563 2.7608279138803482e-02 + + 4.6307921409606934e-01 5.7672828435897827e-01 + <_> + + 0 -1 564 1.2370620388537645e-03 + + 5.1653790473937988e-01 2.6350161433219910e-01 + <_> + + 0 -1 565 -3.7669338285923004e-02 + + 2.5363931059837341e-01 5.2789801359176636e-01 + <_> + + 0 -1 566 -1.8057259730994701e-03 + + 3.9851561188697815e-01 5.5175000429153442e-01 + <_> + 111 + 5.4620071411132812e+01 + + <_> + + 0 -1 567 4.4299028813838959e-03 + + 2.8910180926322937e-01 6.3352262973785400e-01 + <_> + + 0 -1 568 -2.3813319858163595e-03 + + 6.2117892503738403e-01 3.4774878621101379e-01 + <_> + + 0 -1 569 2.2915711160749197e-03 + + 2.2544120252132416e-01 5.5821180343627930e-01 + <_> + + 0 -1 570 9.9457940086722374e-04 + + 3.7117108702659607e-01 5.9300708770751953e-01 + <_> + + 0 -1 571 7.7164667891338468e-04 + + 5.6517201662063599e-01 3.3479958772659302e-01 + <_> + + 0 -1 572 -1.1386410333216190e-03 + + 3.0691260099411011e-01 5.5086308717727661e-01 + <_> + + 0 -1 573 -1.6403039626311511e-04 + + 5.7628279924392700e-01 3.6990478634834290e-01 + <_> + + 0 -1 574 2.9793529392918572e-05 + + 2.6442441344261169e-01 5.4379111528396606e-01 + <_> + + 0 -1 575 8.5774902254343033e-03 + + 5.0511389970779419e-01 1.7957249283790588e-01 + <_> + + 0 -1 576 -2.6032689493149519e-04 + + 5.8269691467285156e-01 4.4468268752098083e-01 + <_> + + 0 -1 577 -6.1404630541801453e-03 + + 3.1138521432876587e-01 5.3469717502593994e-01 + <_> + + 0 -1 578 -2.3086950182914734e-02 + + 3.2779461145401001e-01 5.3311979770660400e-01 + <_> + + 0 -1 579 -1.4243650250136852e-02 + + 7.3817098140716553e-01 4.5880630612373352e-01 + <_> + + 0 -1 580 1.9487129524350166e-02 + + 5.2566307783126831e-01 2.2744719684123993e-01 + <_> + + 0 -1 581 -9.6681108698248863e-04 + + 5.5112308263778687e-01 3.8150069117546082e-01 + <_> + + 0 -1 582 3.1474709976464510e-03 + + 5.4256367683410645e-01 2.5437268614768982e-01 + <_> + + 0 -1 583 -1.8026070029009134e-04 + + 5.3801918029785156e-01 3.4063041210174561e-01 + <_> + + 0 -1 584 -6.0266260989010334e-03 + + 3.0358019471168518e-01 5.4205721616744995e-01 + <_> + + 0 -1 585 4.4462960795499384e-04 + + 3.9909970760345459e-01 5.6601101160049438e-01 + <_> + + 0 -1 586 2.2609760053455830e-03 + + 5.5628067255020142e-01 3.9406880736351013e-01 + <_> + + 0 -1 587 5.1133058965206146e-02 + + 4.6096539497375488e-01 7.1185618638992310e-01 + <_> + + 0 -1 588 -1.7786309123039246e-02 + + 2.3161660134792328e-01 5.3221440315246582e-01 + <_> + + 0 -1 589 -4.9679628573358059e-03 + + 2.3307719826698303e-01 5.1220291852951050e-01 + <_> + + 0 -1 590 2.0667689386755228e-03 + + 4.6574440598487854e-01 6.4554882049560547e-01 + <_> + + 0 -1 591 7.4413768015801907e-03 + + 5.1543921232223511e-01 2.3616339266300201e-01 + <_> + + 0 -1 592 -3.6277279723435640e-03 + + 6.2197732925415039e-01 4.4766610860824585e-01 + <_> + + 0 -1 593 -5.3530759178102016e-03 + + 1.8373550474643707e-01 5.1022082567214966e-01 + <_> + + 0 -1 594 1.4530919492244720e-01 + + 5.1459872722625732e-01 1.5359309315681458e-01 + <_> + + 0 -1 595 2.4394490756094456e-03 + + 5.3436601161956787e-01 3.6246618628501892e-01 + <_> + + 0 -1 596 -3.1283390708267689e-03 + + 6.2150079011917114e-01 4.8455920815467834e-01 + <_> + + 0 -1 597 1.7940260004252195e-03 + + 4.2992618680000305e-01 5.8241981267929077e-01 + <_> + + 0 -1 598 3.6253821104764938e-02 + + 5.2603340148925781e-01 1.4394679665565491e-01 + <_> + + 0 -1 599 -5.1746722310781479e-03 + + 3.5065388679504395e-01 5.2870452404022217e-01 + <_> + + 0 -1 600 6.5383297624066472e-04 + + 4.8096409440040588e-01 6.1220401525497437e-01 + <_> + + 0 -1 601 -2.6480229571461678e-02 + + 1.1393620073795319e-01 5.0455862283706665e-01 + <_> + + 0 -1 602 -3.0440660193562508e-03 + + 6.3520950078964233e-01 4.7947341203689575e-01 + <_> + + 0 -1 603 3.6993520334362984e-03 + + 5.1311182975769043e-01 2.4985109269618988e-01 + <_> + + 0 -1 604 -3.6762931267730892e-04 + + 5.4213947057723999e-01 3.7095320224761963e-01 + <_> + + 0 -1 605 -4.1382260620594025e-02 + + 1.8949599564075470e-01 5.0816917419433594e-01 + <_> + + 0 -1 606 -1.0532729793339968e-03 + + 6.4543670415878296e-01 4.7836089134216309e-01 + <_> + + 0 -1 607 -2.1648600231856108e-03 + + 6.2150311470031738e-01 4.4998261332511902e-01 + <_> + + 0 -1 608 -5.6747748749330640e-04 + + 3.7126109004020691e-01 5.4193347692489624e-01 + <_> + + 0 -1 609 1.7375840246677399e-01 + + 5.0236439704895020e-01 1.2157420068979263e-01 + <_> + + 0 -1 610 -2.9049699660390615e-03 + + 3.2402679324150085e-01 5.3818839788436890e-01 + <_> + + 0 -1 611 1.2299539521336555e-03 + + 4.1655078530311584e-01 5.7034862041473389e-01 + <_> + + 0 -1 612 -5.4329237900674343e-04 + + 3.8540428876876831e-01 5.5475491285324097e-01 + <_> + + 0 -1 613 -8.3297258242964745e-03 + + 2.2044940292835236e-01 5.0970828533172607e-01 + <_> + + 0 -1 614 -1.0417630255687982e-04 + + 5.6070661544799805e-01 4.3030360341072083e-01 + <_> + + 0 -1 615 3.1204700469970703e-02 + + 4.6216571331024170e-01 6.9820040464401245e-01 + <_> + + 0 -1 616 7.8943502157926559e-03 + + 5.2695941925048828e-01 2.2690680623054504e-01 + <_> + + 0 -1 617 -4.3645310215651989e-03 + + 6.3592231273651123e-01 4.5379561185836792e-01 + <_> + + 0 -1 618 7.6793059706687927e-03 + + 5.2747678756713867e-01 2.7404838800430298e-01 + <_> + + 0 -1 619 -2.5431139394640923e-02 + + 2.0385199785232544e-01 5.0717329978942871e-01 + <_> + + 0 -1 620 8.2000601105391979e-04 + + 4.5874550938606262e-01 6.1198681592941284e-01 + <_> + + 0 -1 621 2.9284600168466568e-03 + + 5.0712740421295166e-01 2.0282049477100372e-01 + <_> + + 0 -1 622 4.5256470912136137e-05 + + 4.8121041059494019e-01 5.4308217763900757e-01 + <_> + + 0 -1 623 1.3158309739083052e-03 + + 4.6258139610290527e-01 6.7793232202529907e-01 + <_> + + 0 -1 624 1.5870389761403203e-03 + + 5.3862917423248291e-01 3.4314650297164917e-01 + <_> + + 0 -1 625 -2.1539660170674324e-02 + + 2.5942500680685043e-02 5.0032228231430054e-01 + <_> + + 0 -1 626 1.4334480278193951e-02 + + 5.2028447389602661e-01 1.5906329452991486e-01 + <_> + + 0 -1 627 -8.3881383761763573e-03 + + 7.2824811935424805e-01 4.6480441093444824e-01 + <_> + + 0 -1 628 9.1906841844320297e-03 + + 5.5623567104339600e-01 3.9231911301612854e-01 + <_> + + 0 -1 629 -5.8453059755265713e-03 + + 6.8033927679061890e-01 4.6291279792785645e-01 + <_> + + 0 -1 630 -5.4707799106836319e-02 + + 2.5616711378097534e-01 5.2061259746551514e-01 + <_> + + 0 -1 631 9.1142775490880013e-03 + + 5.1896202564239502e-01 3.0538770556449890e-01 + <_> + + 0 -1 632 -1.5575000084936619e-02 + + 1.2950749695301056e-01 5.1690948009490967e-01 + <_> + + 0 -1 633 -1.2050600344082341e-04 + + 5.7350981235504150e-01 4.2308250069618225e-01 + <_> + + 0 -1 634 1.2273970060050488e-03 + + 5.2898782491683960e-01 4.0797919034957886e-01 + <_> + + 0 -1 635 -1.2186600361019373e-03 + + 6.5756398439407349e-01 4.5744091272354126e-01 + <_> + + 0 -1 636 -3.3256649039685726e-03 + + 3.6280471086502075e-01 5.1950198411941528e-01 + <_> + + 0 -1 637 -1.3288309797644615e-02 + + 1.2842659652233124e-01 5.0434887409210205e-01 + <_> + + 0 -1 638 -3.3839771058410406e-03 + + 6.2922400236129761e-01 4.7575059533119202e-01 + <_> + + 0 -1 639 -2.1954220533370972e-01 + + 1.4877319335937500e-01 5.0650137662887573e-01 + <_> + + 0 -1 640 4.9111708067357540e-03 + + 4.2561021447181702e-01 5.6658387184143066e-01 + <_> + + 0 -1 641 -1.8744950648397207e-04 + + 4.0041440725326538e-01 5.5868571996688843e-01 + <_> + + 0 -1 642 -5.2178641781210899e-03 + + 6.0091161727905273e-01 4.8127061128616333e-01 + <_> + + 0 -1 643 -1.1111519997939467e-03 + + 3.5149338841438293e-01 5.2870899438858032e-01 + <_> + + 0 -1 644 4.4036400504410267e-03 + + 4.6422758698463440e-01 5.9240859746932983e-01 + <_> + + 0 -1 645 1.2299499660730362e-01 + + 5.0255292654037476e-01 6.9152481853961945e-02 + <_> + + 0 -1 646 -1.2313510291278362e-02 + + 5.8845919370651245e-01 4.9340128898620605e-01 + <_> + + 0 -1 647 4.1471039876341820e-03 + + 4.3722391128540039e-01 5.8934777975082397e-01 + <_> + + 0 -1 648 -3.5502649843692780e-03 + + 4.3275511264801025e-01 5.3962701559066772e-01 + <_> + + 0 -1 649 -1.9224269315600395e-02 + + 1.9131340086460114e-01 5.0683307647705078e-01 + <_> + + 0 -1 650 1.4395059552043676e-03 + + 5.3081780672073364e-01 4.2435330152511597e-01 + <_> + + 0 -1 651 -6.7751999013125896e-03 + + 6.3653957843780518e-01 4.5400860905647278e-01 + <_> + + 0 -1 652 7.0119630545377731e-03 + + 5.1898342370986938e-01 3.0261999368667603e-01 + <_> + + 0 -1 653 5.4014651104807854e-03 + + 5.1050621271133423e-01 2.5576829910278320e-01 + <_> + + 0 -1 654 9.0274988906458020e-04 + + 4.6969148516654968e-01 5.8618277311325073e-01 + <_> + + 0 -1 655 1.1474450118839741e-02 + + 5.0536459684371948e-01 1.5271779894828796e-01 + <_> + + 0 -1 656 -6.7023430019617081e-03 + + 6.5089809894561768e-01 4.8906040191650391e-01 + <_> + + 0 -1 657 -2.0462959073483944e-03 + + 6.2418168783187866e-01 4.5146000385284424e-01 + <_> + + 0 -1 658 -9.9951568990945816e-03 + + 3.4327811002731323e-01 5.4009538888931274e-01 + <_> + + 0 -1 659 -3.5700708627700806e-02 + + 1.8780590593814850e-01 5.0740778446197510e-01 + <_> + + 0 -1 660 4.5584561303257942e-04 + + 3.8052770495414734e-01 5.4025697708129883e-01 + <_> + + 0 -1 661 -5.4260600358247757e-02 + + 6.8437147140502930e-01 4.5950970053672791e-01 + <_> + + 0 -1 662 6.0600461438298225e-03 + + 5.5029052495956421e-01 4.5005279779434204e-01 + <_> + + 0 -1 663 -6.4791832119226456e-03 + + 3.3688580989837646e-01 5.3107571601867676e-01 + <_> + + 0 -1 664 -1.4939469983801246e-03 + + 6.4876401424407959e-01 4.7561758756637573e-01 + <_> + + 0 -1 665 1.4610530342906713e-05 + + 4.0345790982246399e-01 5.4510641098022461e-01 + <_> + + 0 -1 666 -7.2321938350796700e-03 + + 6.3868737220764160e-01 4.8247399926185608e-01 + <_> + + 0 -1 667 -4.0645818226039410e-03 + + 2.9864218831062317e-01 5.1573359966278076e-01 + <_> + + 0 -1 668 3.0463080853223801e-02 + + 5.0221997499465942e-01 7.1599560976028442e-01 + <_> + + 0 -1 669 -8.0544911324977875e-03 + + 6.4924520254135132e-01 4.6192750334739685e-01 + <_> + + 0 -1 670 3.9505138993263245e-02 + + 5.1505708694458008e-01 2.4506139755249023e-01 + <_> + + 0 -1 671 8.4530208259820938e-03 + + 4.5736691355705261e-01 6.3940370082855225e-01 + <_> + + 0 -1 672 -1.1688120430335402e-03 + + 3.8655120134353638e-01 5.4836612939834595e-01 + <_> + + 0 -1 673 2.8070670086890459e-03 + + 5.1285791397094727e-01 2.7014800906181335e-01 + <_> + + 0 -1 674 4.7365209320560098e-04 + + 4.0515819191932678e-01 5.3874611854553223e-01 + <_> + + 0 -1 675 1.1741080321371555e-02 + + 5.2959501743316650e-01 3.7194138765335083e-01 + <_> + + 0 -1 676 3.1833238899707794e-03 + + 4.7894069552421570e-01 6.8951261043548584e-01 + <_> + + 0 -1 677 7.0241501089185476e-04 + + 5.3844892978668213e-01 3.9180809259414673e-01 + <_> + 102 + 5.0169731140136719e+01 + + <_> + + 0 -1 678 1.7059929668903351e-02 + + 3.9485278725624084e-01 7.1425348520278931e-01 + <_> + + 0 -1 679 2.1840840578079224e-02 + + 3.3703160285949707e-01 6.0900169610977173e-01 + <_> + + 0 -1 680 2.4520049919374287e-04 + + 3.5005760192871094e-01 5.9879022836685181e-01 + <_> + + 0 -1 681 8.3272606134414673e-03 + + 3.2675281167030334e-01 5.6972408294677734e-01 + <_> + + 0 -1 682 5.7148298947140574e-04 + + 3.0445998907089233e-01 5.5316567420959473e-01 + <_> + + 0 -1 683 6.7373987985774875e-04 + + 3.6500120162963867e-01 5.6726312637329102e-01 + <_> + + 0 -1 684 3.4681590477703139e-05 + + 3.3135411143302917e-01 5.3887271881103516e-01 + <_> + + 0 -1 685 -5.8563398197293282e-03 + + 2.6979428529739380e-01 5.4987788200378418e-01 + <_> + + 0 -1 686 8.5102273151278496e-03 + + 5.2693581581115723e-01 2.7628791332244873e-01 + <_> + + 0 -1 687 -6.9817207753658295e-02 + + 2.9096031188964844e-01 5.2592468261718750e-01 + <_> + + 0 -1 688 -8.6113670840859413e-04 + + 5.8925771713256836e-01 4.0736979246139526e-01 + <_> + + 0 -1 689 9.7149249631911516e-04 + + 3.5235640406608582e-01 5.4158622026443481e-01 + <_> + + 0 -1 690 -1.4727490452060010e-05 + + 5.4230177402496338e-01 3.5031560063362122e-01 + <_> + + 0 -1 691 4.8420291393995285e-02 + + 5.1939457654953003e-01 3.4111958742141724e-01 + <_> + + 0 -1 692 1.3257140526548028e-03 + + 3.1577691435813904e-01 5.3353762626647949e-01 + <_> + + 0 -1 693 1.4922149603080470e-05 + + 4.4512999057769775e-01 5.5365538597106934e-01 + <_> + + 0 -1 694 -2.7173398993909359e-03 + + 3.0317419767379761e-01 5.2480888366699219e-01 + <_> + + 0 -1 695 2.9219500720500946e-03 + + 4.7814530134201050e-01 6.6060417890548706e-01 + <_> + + 0 -1 696 -1.9804988987743855e-03 + + 3.1863081455230713e-01 5.2876251935958862e-01 + <_> + + 0 -1 697 -4.0012109093368053e-03 + + 6.4135968685150146e-01 4.7499281167984009e-01 + <_> + + 0 -1 698 -4.3491991236805916e-03 + + 1.5074980258941650e-01 5.0989967584609985e-01 + <_> + + 0 -1 699 1.3490889687091112e-03 + + 4.3161588907241821e-01 5.8811670541763306e-01 + <_> + + 0 -1 700 1.8597070127725601e-02 + + 4.7355538606643677e-01 9.0897941589355469e-01 + <_> + + 0 -1 701 -1.8562379991635680e-03 + + 3.5531890392303467e-01 5.5778372287750244e-01 + <_> + + 0 -1 702 2.2940430790185928e-03 + + 4.5000949501991272e-01 6.5808779001235962e-01 + <_> + + 0 -1 703 2.9982850537635386e-04 + + 5.6292420625686646e-01 3.9758789539337158e-01 + <_> + + 0 -1 704 3.5455459728837013e-03 + + 5.3815472126007080e-01 3.6054858565330505e-01 + <_> + + 0 -1 705 9.6104722470045090e-03 + + 5.2559971809387207e-01 1.7967459559440613e-01 + <_> + + 0 -1 706 -6.2783220782876015e-03 + + 2.2728569805622101e-01 5.1140302419662476e-01 + <_> + + 0 -1 707 3.4598479978740215e-03 + + 4.6263080835342407e-01 6.6082191467285156e-01 + <_> + + 0 -1 708 -1.3112019514665008e-03 + + 6.3175398111343384e-01 4.4368579983711243e-01 + <_> + + 0 -1 709 2.6876179035753012e-03 + + 5.4211097955703735e-01 4.0540221333503723e-01 + <_> + + 0 -1 710 3.9118169806897640e-03 + + 5.3584778308868408e-01 3.2734549045562744e-01 + <_> + + 0 -1 711 -1.4206450432538986e-02 + + 7.7935767173767090e-01 4.9757811427116394e-01 + <_> + + 0 -1 712 7.1705528534948826e-04 + + 5.2973198890686035e-01 3.5609039664268494e-01 + <_> + + 0 -1 713 1.6635019565001130e-03 + + 4.6780940890312195e-01 5.8164817094802856e-01 + <_> + + 0 -1 714 3.3686188980937004e-03 + + 5.2767342329025269e-01 3.4464201331138611e-01 + <_> + + 0 -1 715 1.2799530290067196e-02 + + 4.8346799612045288e-01 7.4721592664718628e-01 + <_> + + 0 -1 716 3.3901201095432043e-03 + + 4.5118591189384460e-01 6.4017212390899658e-01 + <_> + + 0 -1 717 4.7070779837667942e-03 + + 5.3356587886810303e-01 3.5552209615707397e-01 + <_> + + 0 -1 718 1.4819339849054813e-03 + + 4.2507070302963257e-01 5.7727241516113281e-01 + <_> + + 0 -1 719 -6.9995759986341000e-03 + + 3.0033200979232788e-01 5.2929002046585083e-01 + <_> + + 0 -1 720 1.5939010307192802e-02 + + 5.0673192739486694e-01 1.6755819320678711e-01 + <_> + + 0 -1 721 7.6377349905669689e-03 + + 4.7950699925422668e-01 7.0856010913848877e-01 + <_> + + 0 -1 722 6.7334040068089962e-03 + + 5.1331132650375366e-01 2.1624700725078583e-01 + <_> + + 0 -1 723 -1.2858809903264046e-02 + + 1.9388419389724731e-01 5.2513718605041504e-01 + <_> + + 0 -1 724 -6.2270800117403269e-04 + + 5.6865382194519043e-01 4.1978681087493896e-01 + <_> + + 0 -1 725 -5.2651681471616030e-04 + + 4.2241689562797546e-01 5.4296958446502686e-01 + <_> + + 0 -1 726 1.1075099930167198e-02 + + 5.1137751340866089e-01 2.5145179033279419e-01 + <_> + + 0 -1 727 -3.6728251725435257e-02 + + 7.1946620941162109e-01 4.8496189713478088e-01 + <_> + + 0 -1 728 -2.8207109426148236e-04 + + 3.8402619957923889e-01 5.3944462537765503e-01 + <_> + + 0 -1 729 -2.7489690110087395e-03 + + 5.9370887279510498e-01 4.5691820979118347e-01 + <_> + + 0 -1 730 1.0047519579529762e-02 + + 5.1385760307312012e-01 2.8022980690002441e-01 + <_> + + 0 -1 731 -8.1497840583324432e-03 + + 6.0900372266769409e-01 4.6361210942268372e-01 + <_> + + 0 -1 732 -6.8833888508379459e-03 + + 3.4586110711097717e-01 5.2546602487564087e-01 + <_> + + 0 -1 733 -1.4039360394235700e-05 + + 5.6931042671203613e-01 4.0820831060409546e-01 + <_> + + 0 -1 734 1.5498419525101781e-03 + + 4.3505370616912842e-01 5.8065170049667358e-01 + <_> + + 0 -1 735 -6.7841499112546444e-03 + + 1.4688730239868164e-01 5.1827752590179443e-01 + <_> + + 0 -1 736 2.1705629478674382e-04 + + 5.2935242652893066e-01 3.4561741352081299e-01 + <_> + + 0 -1 737 3.1198898795992136e-04 + + 4.6524509787559509e-01 5.9424138069152832e-01 + <_> + + 0 -1 738 5.4507530294358730e-03 + + 4.6535089612007141e-01 7.0248460769653320e-01 + <_> + + 0 -1 739 -2.5818689027801156e-04 + + 5.4972952604293823e-01 3.7689670920372009e-01 + <_> + + 0 -1 740 -1.7442539334297180e-02 + + 3.9190879464149475e-01 5.4574978351593018e-01 + <_> + + 0 -1 741 -4.5343529433012009e-02 + + 1.6313570737838745e-01 5.1549088954925537e-01 + <_> + + 0 -1 742 1.9190689781680703e-03 + + 5.1458978652954102e-01 2.7918958663940430e-01 + <_> + + 0 -1 743 -6.0177869163453579e-03 + + 6.5176361799240112e-01 4.7563329339027405e-01 + <_> + + 0 -1 744 -4.0720738470554352e-03 + + 5.5146527290344238e-01 4.0926858782768250e-01 + <_> + + 0 -1 745 3.9855059003457427e-04 + + 3.1652408838272095e-01 5.2855509519577026e-01 + <_> + + 0 -1 746 -6.5418570302426815e-03 + + 6.8533778190612793e-01 4.6528089046478271e-01 + <_> + + 0 -1 747 3.4845089539885521e-03 + + 5.4845881462097168e-01 4.5027598738670349e-01 + <_> + + 0 -1 748 -1.3696780428290367e-02 + + 6.3957798480987549e-01 4.5725551247596741e-01 + <_> + + 0 -1 749 -1.7347140237689018e-02 + + 2.7510729432106018e-01 5.1816147565841675e-01 + <_> + + 0 -1 750 -4.0885428898036480e-03 + + 3.3256360888481140e-01 5.1949840784072876e-01 + <_> + + 0 -1 751 -9.4687901437282562e-03 + + 5.9422808885574341e-01 4.8518198728561401e-01 + <_> + + 0 -1 752 1.7084840219467878e-03 + + 4.1671109199523926e-01 5.5198061466217041e-01 + <_> + + 0 -1 753 9.4809094443917274e-03 + + 5.4338949918746948e-01 4.2085149884223938e-01 + <_> + + 0 -1 754 -4.7389650717377663e-03 + + 6.4071899652481079e-01 4.5606550574302673e-01 + <_> + + 0 -1 755 6.5761050209403038e-03 + + 5.2145552635192871e-01 2.2582270205020905e-01 + <_> + + 0 -1 756 -2.1690549328923225e-03 + + 3.1515279412269592e-01 5.1567047834396362e-01 + <_> + + 0 -1 757 1.4660170301795006e-02 + + 4.8708370327949524e-01 6.6899412870407104e-01 + <_> + + 0 -1 758 1.7231999663636088e-04 + + 3.5697489976882935e-01 5.2510780096054077e-01 + <_> + + 0 -1 759 -2.1803760901093483e-02 + + 8.8259208202362061e-01 4.9663299322128296e-01 + <_> + + 0 -1 760 -9.4736106693744659e-02 + + 1.4461620151996613e-01 5.0611138343811035e-01 + <_> + + 0 -1 761 5.5825551971793175e-03 + + 5.3964787721633911e-01 4.2380660772323608e-01 + <_> + + 0 -1 762 1.9517090404406190e-03 + + 4.1704109311103821e-01 5.4977869987487793e-01 + <_> + + 0 -1 763 1.2149900197982788e-02 + + 4.6983671188354492e-01 5.6642740964889526e-01 + <_> + + 0 -1 764 -7.5169620104134083e-03 + + 6.2677729129791260e-01 4.4631358981132507e-01 + <_> + + 0 -1 765 -7.1667909622192383e-02 + + 3.0970111489295959e-01 5.2210032939910889e-01 + <_> + + 0 -1 766 -8.8292419910430908e-02 + + 8.1123888492584229e-02 5.0063651800155640e-01 + <_> + + 0 -1 767 3.1063079833984375e-02 + + 5.1555037498474121e-01 1.2822559475898743e-01 + <_> + + 0 -1 768 4.6621840447187424e-02 + + 4.6997779607772827e-01 7.3639607429504395e-01 + <_> + + 0 -1 769 -1.2189489789307117e-02 + + 3.9205300807952881e-01 5.5189967155456543e-01 + <_> + + 0 -1 770 1.3016110286116600e-02 + + 5.2606582641601562e-01 3.6851361393928528e-01 + <_> + + 0 -1 771 -3.4952899441123009e-03 + + 6.3392949104309082e-01 4.7162809967994690e-01 + <_> + + 0 -1 772 -4.4015039748046547e-05 + + 5.3330272436141968e-01 3.7761849164962769e-01 + <_> + + 0 -1 773 -1.0966490209102631e-01 + + 1.7653420567512512e-01 5.1983469724655151e-01 + <_> + + 0 -1 774 -9.0279558207839727e-04 + + 5.3241598606109619e-01 3.8389080762863159e-01 + <_> + + 0 -1 775 7.1126641705632210e-04 + + 4.6479299664497375e-01 5.7552242279052734e-01 + <_> + + 0 -1 776 -3.1250279862433672e-03 + + 3.2367089390754700e-01 5.1667708158493042e-01 + <_> + + 0 -1 777 2.4144679773598909e-03 + + 4.7874391078948975e-01 6.4597177505493164e-01 + <_> + + 0 -1 778 4.4391240226104856e-04 + + 4.4093081355094910e-01 6.0102558135986328e-01 + <_> + + 0 -1 779 -2.2611189342569560e-04 + + 4.0381139516830444e-01 5.4932558536529541e-01 + <_> + 135 + 6.6669120788574219e+01 + + <_> + + 0 -1 780 -4.6901289373636246e-02 + + 6.6001719236373901e-01 3.7438011169433594e-01 + <_> + + 0 -1 781 -1.4568349579349160e-03 + + 5.7839912176132202e-01 3.4377971291542053e-01 + <_> + + 0 -1 782 5.5598369799554348e-03 + + 3.6222669482231140e-01 5.9082162380218506e-01 + <_> + + 0 -1 783 7.3170487303286791e-04 + + 5.5004191398620605e-01 2.8735581040382385e-01 + <_> + + 0 -1 784 1.3318009441718459e-03 + + 2.6731699705123901e-01 5.4310190677642822e-01 + <_> + + 0 -1 785 2.4347059661522508e-04 + + 3.8550278544425964e-01 5.7413887977600098e-01 + <_> + + 0 -1 786 -3.0512469820678234e-03 + + 5.5032098293304443e-01 3.4628450870513916e-01 + <_> + + 0 -1 787 -6.8657199153676629e-04 + + 3.2912218570709229e-01 5.4295092821121216e-01 + <_> + + 0 -1 788 1.4668200165033340e-03 + + 3.5883820056915283e-01 5.3518110513687134e-01 + <_> + + 0 -1 789 3.2021870720200241e-04 + + 4.2968419194221497e-01 5.7002341747283936e-01 + <_> + + 0 -1 790 7.4122188379988074e-04 + + 5.2821648120880127e-01 3.3668708801269531e-01 + <_> + + 0 -1 791 3.8330298848450184e-03 + + 4.5595678687095642e-01 6.2573361396789551e-01 + <_> + + 0 -1 792 -1.5456439927220345e-02 + + 2.3501169681549072e-01 5.1294529438018799e-01 + <_> + + 0 -1 793 2.6796779129654169e-03 + + 5.3294152021408081e-01 4.1550621390342712e-01 + <_> + + 0 -1 794 2.8296569362282753e-03 + + 4.2730879783630371e-01 5.8045381307601929e-01 + <_> + + 0 -1 795 -3.9444249123334885e-03 + + 2.9126119613647461e-01 5.2026861906051636e-01 + <_> + + 0 -1 796 2.7179559692740440e-03 + + 5.3076881170272827e-01 3.5856771469116211e-01 + <_> + + 0 -1 797 5.9077627956867218e-03 + + 4.7037750482559204e-01 5.9415858983993530e-01 + <_> + + 0 -1 798 -4.2240349575877190e-03 + + 2.1415670216083527e-01 5.0887960195541382e-01 + <_> + + 0 -1 799 4.0725888684391975e-03 + + 4.7664138674736023e-01 6.8410611152648926e-01 + <_> + + 0 -1 800 1.0149530135095119e-02 + + 5.3607988357543945e-01 3.7484970688819885e-01 + <_> + + 0 -1 801 -1.8864999583456665e-04 + + 5.7201302051544189e-01 3.8538050651550293e-01 + <_> + + 0 -1 802 -4.8864358104765415e-03 + + 3.6931228637695312e-01 5.3409588336944580e-01 + <_> + + 0 -1 803 2.6158479973673820e-02 + + 4.9623748660087585e-01 6.0599899291992188e-01 + <_> + + 0 -1 804 4.8560759751126170e-04 + + 4.4389459490776062e-01 6.0124689340591431e-01 + <_> + + 0 -1 805 1.1268709786236286e-02 + + 5.2442502975463867e-01 1.8403880298137665e-01 + <_> + + 0 -1 806 -2.8114619199186563e-03 + + 6.0602837800979614e-01 4.4098970293998718e-01 + <_> + + 0 -1 807 -5.6112729944288731e-03 + + 3.8911709189414978e-01 5.5892372131347656e-01 + <_> + + 0 -1 808 8.5680093616247177e-03 + + 5.0693458318710327e-01 2.0626190304756165e-01 + <_> + + 0 -1 809 -3.8172779022715986e-04 + + 5.8822017908096313e-01 4.1926109790802002e-01 + <_> + + 0 -1 810 -1.7680290329735726e-04 + + 5.5336058139801025e-01 4.0033689141273499e-01 + <_> + + 0 -1 811 6.5112537704408169e-03 + + 3.3101469278335571e-01 5.4441910982131958e-01 + <_> + + 0 -1 812 -6.5948683186434209e-05 + + 5.4338318109512329e-01 3.9449059963226318e-01 + <_> + + 0 -1 813 6.9939051754772663e-03 + + 5.6003582477569580e-01 4.1927140951156616e-01 + <_> + + 0 -1 814 -4.6744439750909805e-03 + + 6.6854667663574219e-01 4.6049609780311584e-01 + <_> + + 0 -1 815 1.1589850299060345e-02 + + 5.3571212291717529e-01 2.9268300533294678e-01 + <_> + + 0 -1 816 1.3007840141654015e-02 + + 4.6798178553581238e-01 7.3074632883071899e-01 + <_> + + 0 -1 817 -1.1008579749614000e-03 + + 3.9375010132789612e-01 5.4150652885437012e-01 + <_> + + 0 -1 818 6.0472649056464434e-04 + + 4.2423760890960693e-01 5.6040412187576294e-01 + <_> + + 0 -1 819 -1.4494840055704117e-02 + + 3.6312100291252136e-01 5.2931827306747437e-01 + <_> + + 0 -1 820 -5.3056948818266392e-03 + + 6.8604522943496704e-01 4.6218210458755493e-01 + <_> + + 0 -1 821 -8.1829127157106996e-04 + + 3.9440968632698059e-01 5.4204392433166504e-01 + <_> + + 0 -1 822 -1.9077520817518234e-02 + + 1.9626219570636749e-01 5.0378918647766113e-01 + <_> + + 0 -1 823 3.5549470339901745e-04 + + 4.0862590074539185e-01 5.6139731407165527e-01 + <_> + + 0 -1 824 1.9679730758070946e-03 + + 4.4891211390495300e-01 5.9261232614517212e-01 + <_> + + 0 -1 825 6.9189141504466534e-03 + + 5.3359258174896240e-01 3.7283858656883240e-01 + <_> + + 0 -1 826 2.9872779268771410e-03 + + 5.1113212108612061e-01 2.9756438732147217e-01 + <_> + + 0 -1 827 -6.2264618463814259e-03 + + 5.5414897203445435e-01 4.8245379328727722e-01 + <_> + + 0 -1 828 1.3353300280869007e-02 + + 4.5864239335060120e-01 6.4147979021072388e-01 + <_> + + 0 -1 829 3.3505238592624664e-02 + + 5.3924250602722168e-01 3.4299948811531067e-01 + <_> + + 0 -1 830 -2.5294460356235504e-03 + + 1.7037139832973480e-01 5.0133150815963745e-01 + <_> + + 0 -1 831 -1.2801629491150379e-03 + + 5.3054618835449219e-01 4.6974050998687744e-01 + <_> + + 0 -1 832 7.0687388069927692e-03 + + 4.6155458688735962e-01 6.4365047216415405e-01 + <_> + + 0 -1 833 9.6880499040707946e-04 + + 4.8335990309715271e-01 6.0438942909240723e-01 + <_> + + 0 -1 834 3.9647659286856651e-03 + + 5.1876372098922729e-01 3.2318168878555298e-01 + <_> + + 0 -1 835 -2.2057730704545975e-02 + + 4.0792569518089294e-01 5.2009809017181396e-01 + <_> + + 0 -1 836 -6.6906312713399529e-04 + + 5.3316092491149902e-01 3.8156008720397949e-01 + <_> + + 0 -1 837 -6.7009328631684184e-04 + + 5.6554222106933594e-01 4.6889019012451172e-01 + <_> + + 0 -1 838 7.4284552829340100e-04 + + 4.5343810319900513e-01 6.2874001264572144e-01 + <_> + + 0 -1 839 2.2227810695767403e-03 + + 5.3506332635879517e-01 3.3036559820175171e-01 + <_> + + 0 -1 840 -5.4130521602928638e-03 + + 1.1136870086193085e-01 5.0054347515106201e-01 + <_> + + 0 -1 841 -1.4520040167553816e-05 + + 5.6287378072738647e-01 4.3251338601112366e-01 + <_> + + 0 -1 842 2.3369169502984732e-04 + + 4.1658350825309753e-01 5.4477912187576294e-01 + <_> + + 0 -1 843 4.2894547805190086e-03 + + 4.8603910207748413e-01 6.7786490917205811e-01 + <_> + + 0 -1 844 5.9103150852024555e-03 + + 5.2623051404953003e-01 3.6121138930320740e-01 + <_> + + 0 -1 845 1.2900539673864841e-02 + + 5.3193771839141846e-01 3.2502880692481995e-01 + <_> + + 0 -1 846 4.6982979401946068e-03 + + 4.6182450652122498e-01 6.6659259796142578e-01 + <_> + + 0 -1 847 1.0439859703183174e-02 + + 5.5056709051132202e-01 3.8836041092872620e-01 + <_> + + 0 -1 848 3.0443191062659025e-03 + + 4.6978530287742615e-01 7.3018449544906616e-01 + <_> + + 0 -1 849 -6.1593751888722181e-04 + + 3.8308390974998474e-01 5.4649841785430908e-01 + <_> + + 0 -1 850 -3.4247159492224455e-03 + + 2.5663000345230103e-01 5.0895309448242188e-01 + <_> + + 0 -1 851 -9.3538565561175346e-03 + + 6.4699661731719971e-01 4.9407958984375000e-01 + <_> + + 0 -1 852 5.2338998764753342e-02 + + 4.7459828853607178e-01 7.8787708282470703e-01 + <_> + + 0 -1 853 3.5765620414167643e-03 + + 5.3066647052764893e-01 2.7484980225563049e-01 + <_> + + 0 -1 854 7.1555317845195532e-04 + + 5.4131257534027100e-01 4.0419089794158936e-01 + <_> + + 0 -1 855 -1.0516679845750332e-02 + + 6.1585122346878052e-01 4.8152831196784973e-01 + <_> + + 0 -1 856 7.7347927726805210e-03 + + 4.6958059072494507e-01 7.0289808511734009e-01 + <_> + + 0 -1 857 -4.3226778507232666e-03 + + 2.8495660424232483e-01 5.3046840429306030e-01 + <_> + + 0 -1 858 -2.5534399319440126e-03 + + 7.0569849014282227e-01 4.6888920664787292e-01 + <_> + + 0 -1 859 1.0268510231981054e-04 + + 3.9029321074485779e-01 5.5734640359878540e-01 + <_> + + 0 -1 860 7.1395188570022583e-06 + + 3.6842319369316101e-01 5.2639877796173096e-01 + <_> + + 0 -1 861 -1.6711989883333445e-03 + + 3.8491758704185486e-01 5.3872710466384888e-01 + <_> + + 0 -1 862 4.9260449595749378e-03 + + 4.7297719120979309e-01 7.4472510814666748e-01 + <_> + + 0 -1 863 4.3908702209591866e-03 + + 4.8091810941696167e-01 5.5919218063354492e-01 + <_> + + 0 -1 864 -1.7793629318475723e-02 + + 6.9036781787872314e-01 4.6769270300865173e-01 + <_> + + 0 -1 865 2.0469669252634048e-03 + + 5.3706902265548706e-01 3.3081620931625366e-01 + <_> + + 0 -1 866 2.9891489073634148e-02 + + 5.1398652791976929e-01 3.3090591430664062e-01 + <_> + + 0 -1 867 1.5494900289922953e-03 + + 4.6602371335029602e-01 6.0783427953720093e-01 + <_> + + 0 -1 868 1.4956969534978271e-03 + + 4.4048359990119934e-01 5.8639198541641235e-01 + <_> + + 0 -1 869 9.5885928021743894e-04 + + 5.4359710216522217e-01 4.2085230350494385e-01 + <_> + + 0 -1 870 4.9643701640889049e-04 + + 5.3705781698226929e-01 4.0006220340728760e-01 + <_> + + 0 -1 871 -2.7280810754746199e-03 + + 5.6594127416610718e-01 4.2596429586410522e-01 + <_> + + 0 -1 872 2.3026480339467525e-03 + + 5.1616579294204712e-01 3.3508691191673279e-01 + <_> + + 0 -1 873 2.5151631236076355e-01 + + 4.8696619272232056e-01 7.1473097801208496e-01 + <_> + + 0 -1 874 -4.6328022144734859e-03 + + 2.7274489402770996e-01 5.0837898254394531e-01 + <_> + + 0 -1 875 -4.0434490889310837e-02 + + 6.8514388799667358e-01 5.0217670202255249e-01 + <_> + + 0 -1 876 1.4972220014897175e-05 + + 4.2844650149345398e-01 5.5225551128387451e-01 + <_> + + 0 -1 877 -2.4050309730228037e-04 + + 4.2261189222335815e-01 5.3900748491287231e-01 + <_> + + 0 -1 878 2.3657839745283127e-02 + + 4.7446319460868835e-01 7.5043660402297974e-01 + <_> + + 0 -1 879 -8.1449104472994804e-03 + + 4.2450588941574097e-01 5.5383628606796265e-01 + <_> + + 0 -1 880 -3.6992130335420370e-03 + + 5.9523570537567139e-01 4.5297130942344666e-01 + <_> + + 0 -1 881 -6.7718601785600185e-03 + + 4.1377940773963928e-01 5.4733997583389282e-01 + <_> + + 0 -1 882 4.2669530957937241e-03 + + 4.4841149449348450e-01 5.7979941368103027e-01 + <_> + + 0 -1 883 1.7791989957913756e-03 + + 5.6248587369918823e-01 4.4324448704719543e-01 + <_> + + 0 -1 884 1.6774770338088274e-03 + + 4.6377518773078918e-01 6.3642418384552002e-01 + <_> + + 0 -1 885 1.1732629500329494e-03 + + 4.5445030927658081e-01 5.9144157171249390e-01 + <_> + + 0 -1 886 8.6998171173036098e-04 + + 5.3347527980804443e-01 3.8859179615974426e-01 + <_> + + 0 -1 887 7.6378340600058436e-04 + + 5.3985852003097534e-01 3.7449419498443604e-01 + <_> + + 0 -1 888 1.5684569370932877e-04 + + 4.3178731203079224e-01 5.6146162748336792e-01 + <_> + + 0 -1 889 -2.1511370316147804e-02 + + 1.7859250307083130e-01 5.1855427026748657e-01 + <_> + + 0 -1 890 1.3081369979772717e-04 + + 4.3424990773200989e-01 5.6828498840332031e-01 + <_> + + 0 -1 891 2.1992040798068047e-02 + + 5.1617169380187988e-01 2.3793940246105194e-01 + <_> + + 0 -1 892 -8.0136500764638186e-04 + + 5.9867632389068604e-01 4.4664269685745239e-01 + <_> + + 0 -1 893 -8.2736099138855934e-03 + + 4.1082179546356201e-01 5.2510571479797363e-01 + <_> + + 0 -1 894 3.6831789184361696e-03 + + 5.1738142967224121e-01 3.3975180983543396e-01 + <_> + + 0 -1 895 -7.9525681212544441e-03 + + 6.8889832496643066e-01 4.8459240794181824e-01 + <_> + + 0 -1 896 1.5382299898192286e-03 + + 5.1785671710968018e-01 3.4541139006614685e-01 + <_> + + 0 -1 897 -1.4043530449271202e-02 + + 1.6784210503101349e-01 5.1886677742004395e-01 + <_> + + 0 -1 898 1.4315890148282051e-03 + + 4.3682569265365601e-01 5.6557738780975342e-01 + <_> + + 0 -1 899 -3.4014228731393814e-02 + + 7.8022962808609009e-01 4.9592170119285583e-01 + <_> + + 0 -1 900 -1.2027299962937832e-02 + + 1.5851010382175446e-01 5.0322318077087402e-01 + <_> + + 0 -1 901 1.3316619396209717e-01 + + 5.1633048057556152e-01 2.7551281452178955e-01 + <_> + + 0 -1 902 -1.5221949433907866e-03 + + 3.7283179163932800e-01 5.2145522832870483e-01 + <_> + + 0 -1 903 -9.3929271679371595e-04 + + 5.8383792638778687e-01 4.5111650228500366e-01 + <_> + + 0 -1 904 2.7719739824533463e-02 + + 4.7282868623733521e-01 7.3315447568893433e-01 + <_> + + 0 -1 905 3.1030150130391121e-03 + + 5.3022021055221558e-01 4.1015630960464478e-01 + <_> + + 0 -1 906 7.7861219644546509e-02 + + 4.9983340501785278e-01 1.2729619443416595e-01 + <_> + + 0 -1 907 -1.5854939818382263e-02 + + 5.0833359360694885e-02 5.1656562089920044e-01 + <_> + + 0 -1 908 -4.9725300632417202e-03 + + 6.7981338500976562e-01 4.6842318773269653e-01 + <_> + + 0 -1 909 -9.7676506265997887e-04 + + 6.0107719898223877e-01 4.7889319062232971e-01 + <_> + + 0 -1 910 -2.4647710379213095e-03 + + 3.3933979272842407e-01 5.2205038070678711e-01 + <_> + + 0 -1 911 -6.7937700077891350e-03 + + 4.3651369214057922e-01 5.2396631240844727e-01 + <_> + + 0 -1 912 3.2608021050691605e-02 + + 5.0527238845825195e-01 2.4252149462699890e-01 + <_> + + 0 -1 913 -5.8514421107247472e-04 + + 5.7339739799499512e-01 4.7585740685462952e-01 + <_> + + 0 -1 914 -2.9632600024342537e-02 + + 3.8922891020774841e-01 5.2635979652404785e-01 + <_> + 137 + 6.7698921203613281e+01 + + <_> + + 0 -1 915 4.6550851315259933e-02 + + 3.2769501209259033e-01 6.2405228614807129e-01 + <_> + + 0 -1 916 7.9537127166986465e-03 + + 4.2564851045608521e-01 6.9429391622543335e-01 + <_> + + 0 -1 917 6.8221561377868056e-04 + + 3.7114870548248291e-01 5.9007328748703003e-01 + <_> + + 0 -1 918 -1.9348249770700932e-04 + + 2.0411339402198792e-01 5.3005450963973999e-01 + <_> + + 0 -1 919 -2.6710508973337710e-04 + + 5.4161262512207031e-01 3.1031790375709534e-01 + <_> + + 0 -1 920 2.7818060480058193e-03 + + 5.2778327465057373e-01 3.4670698642730713e-01 + <_> + + 0 -1 921 -4.6779078547842801e-04 + + 5.3082311153411865e-01 3.2944920659065247e-01 + <_> + + 0 -1 922 -3.0335160772665404e-05 + + 5.7738727331161499e-01 3.8520970940589905e-01 + <_> + + 0 -1 923 7.8038009814918041e-04 + + 4.3174389004707336e-01 6.1500579118728638e-01 + <_> + + 0 -1 924 -4.2553851380944252e-03 + + 2.9339039325714111e-01 5.3242927789688110e-01 + <_> + + 0 -1 925 -2.4735610350035131e-04 + + 5.4688447713851929e-01 3.8430300354957581e-01 + <_> + + 0 -1 926 -1.4724259381182492e-04 + + 4.2815428972244263e-01 5.7555872201919556e-01 + <_> + + 0 -1 927 1.1864770203828812e-03 + + 3.7473011016845703e-01 5.4714661836624146e-01 + <_> + + 0 -1 928 2.3936580400913954e-03 + + 4.5377838611602783e-01 6.1115288734436035e-01 + <_> + + 0 -1 929 -1.5390539774671197e-03 + + 2.9713419079780579e-01 5.1895380020141602e-01 + <_> + + 0 -1 930 -7.1968790143728256e-03 + + 6.6990667581558228e-01 4.7264769673347473e-01 + <_> + + 0 -1 931 -4.1499789222143590e-04 + + 3.3849540352821350e-01 5.2603179216384888e-01 + <_> + + 0 -1 932 4.4359830208122730e-03 + + 5.3991222381591797e-01 3.9201408624649048e-01 + <_> + + 0 -1 933 2.6606200262904167e-03 + + 4.4825780391693115e-01 6.1196178197860718e-01 + <_> + + 0 -1 934 -1.5287200221791863e-03 + + 3.7112379074096680e-01 5.3402662277221680e-01 + <_> + + 0 -1 935 -4.7397250309586525e-03 + + 6.0310882329940796e-01 4.4551450014114380e-01 + <_> + + 0 -1 936 -1.4829129911959171e-02 + + 2.8387540578842163e-01 5.3418618440628052e-01 + <_> + + 0 -1 937 9.2275557108223438e-04 + + 5.2095472812652588e-01 3.3616539835929871e-01 + <_> + + 0 -1 938 8.3529807627201080e-02 + + 5.1199698448181152e-01 8.1164449453353882e-02 + <_> + + 0 -1 939 -7.5633148662745953e-04 + + 3.3171200752258301e-01 5.1898312568664551e-01 + <_> + + 0 -1 940 9.8403859883546829e-03 + + 5.2475982904434204e-01 2.3349590599536896e-01 + <_> + + 0 -1 941 -1.5953830443322659e-03 + + 5.7500940561294556e-01 4.2956221103668213e-01 + <_> + + 0 -1 942 3.4766020689858124e-05 + + 4.3424451351165771e-01 5.5640292167663574e-01 + <_> + + 0 -1 943 2.9862910509109497e-02 + + 4.5791471004486084e-01 6.5791881084442139e-01 + <_> + + 0 -1 944 1.1325590312480927e-02 + + 5.2743119001388550e-01 3.6738881468772888e-01 + <_> + + 0 -1 945 -8.7828645482659340e-03 + + 7.1003687381744385e-01 4.6421670913696289e-01 + <_> + + 0 -1 946 4.3639959767460823e-03 + + 5.2792161703109741e-01 2.7058771252632141e-01 + <_> + + 0 -1 947 4.1804728098213673e-03 + + 5.0725251436233521e-01 2.4490830302238464e-01 + <_> + + 0 -1 948 -4.5668511302210391e-04 + + 4.2831051349639893e-01 5.5486911535263062e-01 + <_> + + 0 -1 949 -3.7140368949621916e-03 + + 5.5193877220153809e-01 4.1036531329154968e-01 + <_> + + 0 -1 950 -2.5304289534687996e-02 + + 6.8670022487640381e-01 4.8698890209197998e-01 + <_> + + 0 -1 951 -3.4454080741852522e-04 + + 3.7288740277290344e-01 5.2876931428909302e-01 + <_> + + 0 -1 952 -8.3935231668874621e-04 + + 6.0601520538330078e-01 4.6160620450973511e-01 + <_> + + 0 -1 953 1.7280049622058868e-02 + + 5.0496357679367065e-01 1.8198239803314209e-01 + <_> + + 0 -1 954 -6.3595077954232693e-03 + + 1.6312399506568909e-01 5.2327787876129150e-01 + <_> + + 0 -1 955 1.0298109846189618e-03 + + 4.4632780551910400e-01 6.1765491962432861e-01 + <_> + + 0 -1 956 1.0117109632119536e-03 + + 5.4733848571777344e-01 4.3006989359855652e-01 + <_> + + 0 -1 957 -1.0308800265192986e-02 + + 1.1669850349426270e-01 5.0008672475814819e-01 + <_> + + 0 -1 958 5.4682018235325813e-03 + + 4.7692871093750000e-01 6.7192137241363525e-01 + <_> + + 0 -1 959 -9.1696460731327534e-04 + + 3.4710898995399475e-01 5.1781648397445679e-01 + <_> + + 0 -1 960 2.3922820109874010e-03 + + 4.7852361202239990e-01 6.2163108587265015e-01 + <_> + + 0 -1 961 -7.5573818758130074e-03 + + 5.8147960901260376e-01 4.4100850820541382e-01 + <_> + + 0 -1 962 -7.7024032361805439e-04 + + 3.8780000805854797e-01 5.4657220840454102e-01 + <_> + + 0 -1 963 -8.7125990539789200e-03 + + 1.6600510478019714e-01 4.9958360195159912e-01 + <_> + + 0 -1 964 -1.0306320153176785e-02 + + 4.0933910012245178e-01 5.2742338180541992e-01 + <_> + + 0 -1 965 -2.0940979011356831e-03 + + 6.2061947584152222e-01 4.5722800493240356e-01 + <_> + + 0 -1 966 6.8099051713943481e-03 + + 5.5677592754364014e-01 4.1556000709533691e-01 + <_> + + 0 -1 967 -1.0746059706434608e-03 + + 5.6389278173446655e-01 4.3530249595642090e-01 + <_> + + 0 -1 968 2.1550289820879698e-03 + + 4.8262658715248108e-01 6.7497581243515015e-01 + <_> + + 0 -1 969 3.1742319464683533e-02 + + 5.0483798980712891e-01 1.8832489848136902e-01 + <_> + + 0 -1 970 -7.8382723033428192e-02 + + 2.3695489764213562e-01 5.2601581811904907e-01 + <_> + + 0 -1 971 5.7415119372308254e-03 + + 5.0488287210464478e-01 2.7764698863029480e-01 + <_> + + 0 -1 972 -2.9014600440859795e-03 + + 6.2386047840118408e-01 4.6933171153068542e-01 + <_> + + 0 -1 973 -2.6427931152284145e-03 + + 3.3141419291496277e-01 5.1697772741317749e-01 + <_> + + 0 -1 974 -1.0949660092592239e-01 + + 2.3800450563430786e-01 5.1834410429000854e-01 + <_> + + 0 -1 975 7.4075913289561868e-05 + + 4.0696358680725098e-01 5.3621500730514526e-01 + <_> + + 0 -1 976 -5.0593802006915212e-04 + + 5.5067062377929688e-01 4.3745940923690796e-01 + <_> + + 0 -1 977 -8.2131777890026569e-04 + + 5.5257099866867065e-01 4.2093759775161743e-01 + <_> + + 0 -1 978 -6.0276539443293586e-05 + + 5.4554748535156250e-01 4.7482660412788391e-01 + <_> + + 0 -1 979 6.8065142259001732e-03 + + 5.1579958200454712e-01 3.4245771169662476e-01 + <_> + + 0 -1 980 1.7202789895236492e-03 + + 5.0132077932357788e-01 6.3312637805938721e-01 + <_> + + 0 -1 981 -1.3016929733566940e-04 + + 5.5397182703018188e-01 4.2268699407577515e-01 + <_> + + 0 -1 982 -4.8016388900578022e-03 + + 4.4250950217247009e-01 5.4307800531387329e-01 + <_> + + 0 -1 983 -2.5399310979992151e-03 + + 7.1457821130752563e-01 4.6976050734519958e-01 + <_> + + 0 -1 984 -1.4278929447755218e-03 + + 4.0704450011253357e-01 5.3996050357818604e-01 + <_> + + 0 -1 985 -2.5142550468444824e-02 + + 7.8846907615661621e-01 4.7473520040512085e-01 + <_> + + 0 -1 986 -3.8899609353393316e-03 + + 4.2961919307708740e-01 5.5771100521087646e-01 + <_> + + 0 -1 987 4.3947459198534489e-03 + + 4.6931621432304382e-01 7.0239442586898804e-01 + <_> + + 0 -1 988 2.4678420275449753e-02 + + 5.2423220872879028e-01 3.8125100731849670e-01 + <_> + + 0 -1 989 3.8047678768634796e-02 + + 5.0117397308349609e-01 1.6878280043601990e-01 + <_> + + 0 -1 990 7.9424865543842316e-03 + + 4.8285821080207825e-01 6.3695681095123291e-01 + <_> + + 0 -1 991 -1.5110049862414598e-03 + + 5.9064859151840210e-01 4.4876679778099060e-01 + <_> + + 0 -1 992 6.4201741479337215e-03 + + 5.2410978078842163e-01 2.9905700683593750e-01 + <_> + + 0 -1 993 -2.9802159406244755e-03 + + 3.0414658784866333e-01 5.0784897804260254e-01 + <_> + + 0 -1 994 -7.4580078944563866e-04 + + 4.1281390190124512e-01 5.2568262815475464e-01 + <_> + + 0 -1 995 -1.0470950044691563e-02 + + 5.8083951473236084e-01 4.4942960143089294e-01 + <_> + + 0 -1 996 9.3369204550981522e-03 + + 5.2465528249740601e-01 2.6589488983154297e-01 + <_> + + 0 -1 997 2.7936900034546852e-02 + + 4.6749550104141235e-01 7.0872569084167480e-01 + <_> + + 0 -1 998 7.4277678504586220e-03 + + 5.4094868898391724e-01 3.7585180997848511e-01 + <_> + + 0 -1 999 -2.3584509268403053e-02 + + 3.7586399912834167e-01 5.2385509014129639e-01 + <_> + + 0 -1 1000 1.1452640173956752e-03 + + 4.3295788764953613e-01 5.8042472600936890e-01 + <_> + + 0 -1 1001 -4.3468660442158580e-04 + + 5.2806180715560913e-01 3.8730698823928833e-01 + <_> + + 0 -1 1002 1.0648540221154690e-02 + + 4.9021130800247192e-01 5.6812518835067749e-01 + <_> + + 0 -1 1003 -3.9418050437234342e-04 + + 5.5708801746368408e-01 4.3182510137557983e-01 + <_> + + 0 -1 1004 -1.3270479394122958e-04 + + 5.6584399938583374e-01 4.3435549736022949e-01 + <_> + + 0 -1 1005 -2.0125510636717081e-03 + + 6.0567390918731689e-01 4.5375239849090576e-01 + <_> + + 0 -1 1006 2.4854319635778666e-03 + + 5.3904771804809570e-01 4.1380101442337036e-01 + <_> + + 0 -1 1007 1.8237880431115627e-03 + + 4.3548288941383362e-01 5.7171887159347534e-01 + <_> + + 0 -1 1008 -1.6656659543514252e-02 + + 3.0109131336212158e-01 5.2161228656768799e-01 + <_> + + 0 -1 1009 8.0349558265879750e-04 + + 5.3001511096954346e-01 3.8183969259262085e-01 + <_> + + 0 -1 1010 3.4170378930866718e-03 + + 5.3280287981033325e-01 4.2414000630378723e-01 + <_> + + 0 -1 1011 -3.6222729249857366e-04 + + 5.4917281866073608e-01 4.1869771480560303e-01 + <_> + + 0 -1 1012 -1.1630020290613174e-01 + + 1.4407220482826233e-01 5.2264511585235596e-01 + <_> + + 0 -1 1013 -1.4695010147988796e-02 + + 7.7477252483367920e-01 4.7157171368598938e-01 + <_> + + 0 -1 1014 2.1972130052745342e-03 + + 5.3554338216781616e-01 3.3156448602676392e-01 + <_> + + 0 -1 1015 -4.6965209185145795e-04 + + 5.7672351598739624e-01 4.4581368565559387e-01 + <_> + + 0 -1 1016 6.5144998952746391e-03 + + 5.2156740427017212e-01 3.6478888988494873e-01 + <_> + + 0 -1 1017 2.1300060674548149e-02 + + 4.9942049384117126e-01 1.5679509937763214e-01 + <_> + + 0 -1 1018 3.1881409231573343e-03 + + 4.7422000765800476e-01 6.2872701883316040e-01 + <_> + + 0 -1 1019 9.0019777417182922e-04 + + 5.3479540348052979e-01 3.9437520503997803e-01 + <_> + + 0 -1 1020 -5.1772277802228928e-03 + + 6.7271918058395386e-01 5.0131380558013916e-01 + <_> + + 0 -1 1021 -4.3764649890363216e-03 + + 3.1066751480102539e-01 5.1287931203842163e-01 + <_> + + 0 -1 1022 2.6299960445612669e-03 + + 4.8863101005554199e-01 5.7552158832550049e-01 + <_> + + 0 -1 1023 -2.0458688959479332e-03 + + 6.0257941484451294e-01 4.5580768585205078e-01 + <_> + + 0 -1 1024 6.9482706487178802e-02 + + 5.2407479286193848e-01 2.1852590143680573e-01 + <_> + + 0 -1 1025 2.4048939347267151e-02 + + 5.0118672847747803e-01 2.0906220376491547e-01 + <_> + + 0 -1 1026 3.1095340382307768e-03 + + 4.8667120933532715e-01 7.1085482835769653e-01 + <_> + + 0 -1 1027 -1.2503260513767600e-03 + + 3.4078910946846008e-01 5.1561951637268066e-01 + <_> + + 0 -1 1028 -1.0281190043315291e-03 + + 5.5755722522735596e-01 4.4394320249557495e-01 + <_> + + 0 -1 1029 -8.8893622159957886e-03 + + 6.4020007848739624e-01 4.6204420924186707e-01 + <_> + + 0 -1 1030 -6.1094801640138030e-04 + + 3.7664419412612915e-01 5.4488998651504517e-01 + <_> + + 0 -1 1031 -5.7686357758939266e-03 + + 3.3186489343643188e-01 5.1336771249771118e-01 + <_> + + 0 -1 1032 1.8506490159779787e-03 + + 4.9035701155662537e-01 6.4069348573684692e-01 + <_> + + 0 -1 1033 -9.9799469113349915e-02 + + 1.5360510349273682e-01 5.0155621767044067e-01 + <_> + + 0 -1 1034 -3.5128349065780640e-01 + + 5.8823131024837494e-02 5.1743787527084351e-01 + <_> + + 0 -1 1035 -4.5244570821523666e-02 + + 6.9614887237548828e-01 4.6778729557991028e-01 + <_> + + 0 -1 1036 7.1481578052043915e-02 + + 5.1679861545562744e-01 1.0380929708480835e-01 + <_> + + 0 -1 1037 2.1895780228078365e-03 + + 4.2730781435966492e-01 5.5320608615875244e-01 + <_> + + 0 -1 1038 -5.9242651332169771e-04 + + 4.6389439702033997e-01 5.2763891220092773e-01 + <_> + + 0 -1 1039 1.6788389766588807e-03 + + 5.3016489744186401e-01 3.9320349693298340e-01 + <_> + + 0 -1 1040 -2.2163488902151585e-03 + + 5.6306940317153931e-01 4.7570338845252991e-01 + <_> + + 0 -1 1041 1.1568699846975505e-04 + + 4.3075358867645264e-01 5.5357027053833008e-01 + <_> + + 0 -1 1042 -7.2017288766801357e-03 + + 1.4448820054531097e-01 5.1930642127990723e-01 + <_> + + 0 -1 1043 8.9081272017210722e-04 + + 4.3844321370124817e-01 5.5936211347579956e-01 + <_> + + 0 -1 1044 1.9605009583756328e-04 + + 5.3404158353805542e-01 4.7059568762779236e-01 + <_> + + 0 -1 1045 5.2022142335772514e-04 + + 5.2138561010360718e-01 3.8100790977478027e-01 + <_> + + 0 -1 1046 9.4588572392240167e-04 + + 4.7694149613380432e-01 6.1307388544082642e-01 + <_> + + 0 -1 1047 9.1698471806012094e-05 + + 4.2450091242790222e-01 5.4293632507324219e-01 + <_> + + 0 -1 1048 2.1833200007677078e-03 + + 5.4577308893203735e-01 4.1910758614540100e-01 + <_> + + 0 -1 1049 -8.6039671441540122e-04 + + 5.7645887136459351e-01 4.4716599583625793e-01 + <_> + + 0 -1 1050 -1.3236239552497864e-02 + + 6.3728231191635132e-01 4.6950098872184753e-01 + <_> + + 0 -1 1051 4.3376701069064438e-04 + + 5.3178739547729492e-01 3.9458298683166504e-01 + <_> + 140 + 6.9229873657226562e+01 + + <_> + + 0 -1 1052 -2.4847149848937988e-02 + + 6.5555167198181152e-01 3.8733118772506714e-01 + <_> + + 0 -1 1053 6.1348611488938332e-03 + + 3.7480720877647400e-01 5.9739977121353149e-01 + <_> + + 0 -1 1054 6.4498498104512691e-03 + + 5.4254919290542603e-01 2.5488111376762390e-01 + <_> + + 0 -1 1055 6.3491211039945483e-04 + + 2.4624420702457428e-01 5.3872537612915039e-01 + <_> + + 0 -1 1056 1.4023890253156424e-03 + + 5.5943220853805542e-01 3.5286578536033630e-01 + <_> + + 0 -1 1057 3.0044000595808029e-04 + + 3.9585039019584656e-01 5.7659381628036499e-01 + <_> + + 0 -1 1058 1.0042409849120304e-04 + + 3.6989969015121460e-01 5.5349981784820557e-01 + <_> + + 0 -1 1059 -5.0841490738093853e-03 + + 3.7110909819602966e-01 5.5478000640869141e-01 + <_> + + 0 -1 1060 -1.9537260755896568e-02 + + 7.4927550554275513e-01 4.5792970061302185e-01 + <_> + + 0 -1 1061 -7.4532740654831287e-06 + + 5.6497871875762939e-01 3.9040699601173401e-01 + <_> + + 0 -1 1062 -3.6079459823668003e-03 + + 3.3810880780220032e-01 5.2678012847900391e-01 + <_> + + 0 -1 1063 2.0697501022368670e-03 + + 5.5192911624908447e-01 3.7143889069557190e-01 + <_> + + 0 -1 1064 -4.6463840408250690e-04 + + 5.6082147359848022e-01 4.1135668754577637e-01 + <_> + + 0 -1 1065 7.5490452582016587e-04 + + 3.5592061281204224e-01 5.3293561935424805e-01 + <_> + + 0 -1 1066 -9.8322238773107529e-04 + + 5.4147958755493164e-01 3.7632051110267639e-01 + <_> + + 0 -1 1067 -1.9940640777349472e-02 + + 6.3479030132293701e-01 4.7052991390228271e-01 + <_> + + 0 -1 1068 3.7680300883948803e-03 + + 3.9134898781776428e-01 5.5637162923812866e-01 + <_> + + 0 -1 1069 -9.4528505578637123e-03 + + 2.5548928976058960e-01 5.2151167392730713e-01 + <_> + + 0 -1 1070 2.9560849070549011e-03 + + 5.1746791601181030e-01 3.0639201402664185e-01 + <_> + + 0 -1 1071 9.1078737750649452e-03 + + 5.3884482383728027e-01 2.8859630227088928e-01 + <_> + + 0 -1 1072 1.8219229532405734e-03 + + 4.3360430002212524e-01 5.8521968126296997e-01 + <_> + + 0 -1 1073 1.4688739553093910e-02 + + 5.2873617410659790e-01 2.8700059652328491e-01 + <_> + + 0 -1 1074 -1.4387990348041058e-02 + + 7.0194488763809204e-01 4.6473708748817444e-01 + <_> + + 0 -1 1075 -1.8986649811267853e-02 + + 2.9865521192550659e-01 5.2470117807388306e-01 + <_> + + 0 -1 1076 1.1527639580890536e-03 + + 4.3234738707542419e-01 5.9316617250442505e-01 + <_> + + 0 -1 1077 1.0933670215308666e-02 + + 5.2868640422821045e-01 3.1303191184997559e-01 + <_> + + 0 -1 1078 -1.4932730235159397e-02 + + 2.6584190130233765e-01 5.0840771198272705e-01 + <_> + + 0 -1 1079 -2.9970539617352188e-04 + + 5.4635268449783325e-01 3.7407240271568298e-01 + <_> + + 0 -1 1080 4.1677621193230152e-03 + + 4.7034969925880432e-01 7.4357217550277710e-01 + <_> + + 0 -1 1081 -6.3905320130288601e-03 + + 2.0692589879035950e-01 5.2805382013320923e-01 + <_> + + 0 -1 1082 4.5029609464108944e-03 + + 5.1826488971710205e-01 3.4835430979728699e-01 + <_> + + 0 -1 1083 -9.2040365561842918e-03 + + 6.8037772178649902e-01 4.9323600530624390e-01 + <_> + + 0 -1 1084 8.1327259540557861e-02 + + 5.0583988428115845e-01 2.2530519962310791e-01 + <_> + + 0 -1 1085 -1.5079280734062195e-01 + + 2.9634249210357666e-01 5.2646797895431519e-01 + <_> + + 0 -1 1086 3.3179009333252907e-03 + + 4.6554958820343018e-01 7.0729321241378784e-01 + <_> + + 0 -1 1087 7.7402801252901554e-04 + + 4.7803479433059692e-01 5.6682378053665161e-01 + <_> + + 0 -1 1088 6.8199541419744492e-04 + + 4.2869961261749268e-01 5.7221567630767822e-01 + <_> + + 0 -1 1089 5.3671570494771004e-03 + + 5.2993071079254150e-01 3.1146219372749329e-01 + <_> + + 0 -1 1090 9.7018666565418243e-05 + + 3.6746388673782349e-01 5.2694618701934814e-01 + <_> + + 0 -1 1091 -1.2534089386463165e-01 + + 2.3514920473098755e-01 5.2457910776138306e-01 + <_> + + 0 -1 1092 -5.2516269497573376e-03 + + 7.1159368753433228e-01 4.6937671303749084e-01 + <_> + + 0 -1 1093 -7.8342109918594360e-03 + + 4.4626510143280029e-01 5.4090857505798340e-01 + <_> + + 0 -1 1094 -1.1310069821774960e-03 + + 5.9456187486648560e-01 4.4176620244979858e-01 + <_> + + 0 -1 1095 1.7601120052859187e-03 + + 5.3532499074935913e-01 3.9734530448913574e-01 + <_> + + 0 -1 1096 -8.1581249833106995e-04 + + 3.7602680921554565e-01 5.2647268772125244e-01 + <_> + + 0 -1 1097 -3.8687589112669230e-03 + + 6.3099128007888794e-01 4.7498199343681335e-01 + <_> + + 0 -1 1098 1.5207129763439298e-03 + + 5.2301818132400513e-01 3.3612239360809326e-01 + <_> + + 0 -1 1099 5.4586738348007202e-01 + + 5.1671397686004639e-01 1.1726350337266922e-01 + <_> + + 0 -1 1100 1.5650190412998199e-02 + + 4.9794390797615051e-01 1.3932949304580688e-01 + <_> + + 0 -1 1101 -1.1731860227882862e-02 + + 7.1296507120132446e-01 4.9211961030960083e-01 + <_> + + 0 -1 1102 -6.1765122227370739e-03 + + 2.2881029546260834e-01 5.0497019290924072e-01 + <_> + + 0 -1 1103 2.2457661107182503e-03 + + 4.6324339509010315e-01 6.0487258434295654e-01 + <_> + + 0 -1 1104 -5.1915869116783142e-03 + + 6.4674210548400879e-01 4.6021929383277893e-01 + <_> + + 0 -1 1105 -2.3827880620956421e-02 + + 1.4820009469985962e-01 5.2260792255401611e-01 + <_> + + 0 -1 1106 1.0284580057486892e-03 + + 5.1354891061782837e-01 3.3759570121765137e-01 + <_> + + 0 -1 1107 -1.0078850202262402e-02 + + 2.7405610680580139e-01 5.3035670518875122e-01 + <_> + + 0 -1 1108 2.6168930344283581e-03 + + 5.3326708078384399e-01 3.9724540710449219e-01 + <_> + + 0 -1 1109 5.4385367548093200e-04 + + 5.3656041622161865e-01 4.0634119510650635e-01 + <_> + + 0 -1 1110 5.3510512225329876e-03 + + 4.6537590026855469e-01 6.8890458345413208e-01 + <_> + + 0 -1 1111 -1.5274790348485112e-03 + + 5.4495012760162354e-01 3.6247238516807556e-01 + <_> + + 0 -1 1112 -8.0624416470527649e-02 + + 1.6560870409011841e-01 5.0002872943878174e-01 + <_> + + 0 -1 1113 2.2192029282450676e-02 + + 5.1327311992645264e-01 2.0028080046176910e-01 + <_> + + 0 -1 1114 7.3100631125271320e-03 + + 4.6179479360580444e-01 6.3665360212326050e-01 + <_> + + 0 -1 1115 -6.4063072204589844e-03 + + 5.9162509441375732e-01 4.8678609728813171e-01 + <_> + + 0 -1 1116 -7.6415040530264378e-04 + + 3.8884091377258301e-01 5.3157979249954224e-01 + <_> + + 0 -1 1117 7.6734489994123578e-04 + + 4.1590648889541626e-01 5.6052798032760620e-01 + <_> + + 0 -1 1118 6.1474501853808761e-04 + + 3.0890220403671265e-01 5.1201480627059937e-01 + <_> + + 0 -1 1119 -5.0105270929634571e-03 + + 3.9721998572349548e-01 5.2073061466217041e-01 + <_> + + 0 -1 1120 -8.6909132078289986e-03 + + 6.2574082612991333e-01 4.6085759997367859e-01 + <_> + + 0 -1 1121 -1.6391459852457047e-02 + + 2.0852099359035492e-01 5.2422660589218140e-01 + <_> + + 0 -1 1122 4.0973909199237823e-04 + + 5.2224272489547729e-01 3.7803208827972412e-01 + <_> + + 0 -1 1123 -2.5242289993911982e-03 + + 5.8039271831512451e-01 4.6118900179862976e-01 + <_> + + 0 -1 1124 5.0945312250405550e-04 + + 4.4012719392776489e-01 5.8460158109664917e-01 + <_> + + 0 -1 1125 1.9656419754028320e-03 + + 5.3223252296447754e-01 4.1845908761024475e-01 + <_> + + 0 -1 1126 5.6298897834494710e-04 + + 3.7418448925018311e-01 5.2345657348632812e-01 + <_> + + 0 -1 1127 -6.7946797935292125e-04 + + 4.6310418844223022e-01 5.3564780950546265e-01 + <_> + + 0 -1 1128 7.2856349870562553e-03 + + 5.0446701049804688e-01 2.3775640130043030e-01 + <_> + + 0 -1 1129 -1.7459489405155182e-02 + + 7.2891211509704590e-01 5.0504350662231445e-01 + <_> + + 0 -1 1130 -2.5421749800443649e-02 + + 6.6671347618103027e-01 4.6781000494956970e-01 + <_> + + 0 -1 1131 -1.5647639520466328e-03 + + 4.3917590379714966e-01 5.3236269950866699e-01 + <_> + + 0 -1 1132 1.1444360017776489e-02 + + 4.3464401364326477e-01 5.6800121068954468e-01 + <_> + + 0 -1 1133 -6.7352550104260445e-04 + + 4.4771409034729004e-01 5.2968120574951172e-01 + <_> + + 0 -1 1134 9.3194209039211273e-03 + + 4.7402000427246094e-01 7.4626070261001587e-01 + <_> + + 0 -1 1135 1.3328490604180843e-04 + + 5.3650617599487305e-01 4.7521349787712097e-01 + <_> + + 0 -1 1136 -7.8815799206495285e-03 + + 1.7522190511226654e-01 5.0152552127838135e-01 + <_> + + 0 -1 1137 -5.7985680177807808e-03 + + 7.2712367773056030e-01 4.8962008953094482e-01 + <_> + + 0 -1 1138 -3.8922499516047537e-04 + + 4.0039089322090149e-01 5.3449410200119019e-01 + <_> + + 0 -1 1139 -1.9288610201328993e-03 + + 5.6056129932403564e-01 4.8039558529853821e-01 + <_> + + 0 -1 1140 8.4214154630899429e-03 + + 4.7532469034194946e-01 7.6236087083816528e-01 + <_> + + 0 -1 1141 8.1655876711010933e-03 + + 5.3932619094848633e-01 4.1916438937187195e-01 + <_> + + 0 -1 1142 4.8280550981871784e-04 + + 4.2408001422882080e-01 5.3998219966888428e-01 + <_> + + 0 -1 1143 -2.7186630759388208e-03 + + 4.2445999383926392e-01 5.4249238967895508e-01 + <_> + + 0 -1 1144 -1.2507230043411255e-02 + + 5.8958417177200317e-01 4.5504111051559448e-01 + <_> + + 0 -1 1145 -2.4286519736051559e-02 + + 2.6471349596977234e-01 5.1891797780990601e-01 + <_> + + 0 -1 1146 -2.9676330741494894e-03 + + 7.3476827144622803e-01 4.7497498989105225e-01 + <_> + + 0 -1 1147 -1.2528999708592892e-02 + + 2.7560499310493469e-01 5.1775997877120972e-01 + <_> + + 0 -1 1148 -1.0104000102728605e-03 + + 3.5105609893798828e-01 5.1447242498397827e-01 + <_> + + 0 -1 1149 -2.1348530426621437e-03 + + 5.6379258632659912e-01 4.6673199534416199e-01 + <_> + + 0 -1 1150 1.9564259797334671e-02 + + 4.6145731210708618e-01 6.1376398801803589e-01 + <_> + + 0 -1 1151 -9.7146347165107727e-02 + + 2.9983788728713989e-01 5.1935559511184692e-01 + <_> + + 0 -1 1152 4.5014568604528904e-03 + + 5.0778847932815552e-01 3.0457559227943420e-01 + <_> + + 0 -1 1153 6.3706971704959869e-03 + + 4.8610189557075500e-01 6.8875008821487427e-01 + <_> + + 0 -1 1154 -9.0721528977155685e-03 + + 1.6733959317207336e-01 5.0175631046295166e-01 + <_> + + 0 -1 1155 -5.3537208586931229e-03 + + 2.6927569508552551e-01 5.2426332235336304e-01 + <_> + + 0 -1 1156 -1.0932840406894684e-02 + + 7.1838641166687012e-01 4.7360289096832275e-01 + <_> + + 0 -1 1157 8.2356072962284088e-03 + + 5.2239668369293213e-01 2.3898629844188690e-01 + <_> + + 0 -1 1158 -1.0038160253316164e-03 + + 5.7193559408187866e-01 4.4339430332183838e-01 + <_> + + 0 -1 1159 4.0859128348529339e-03 + + 5.4728418588638306e-01 4.1488361358642578e-01 + <_> + + 0 -1 1160 1.5485419332981110e-01 + + 4.9738121032714844e-01 6.1061598360538483e-02 + <_> + + 0 -1 1161 2.0897459762636572e-04 + + 4.7091740369796753e-01 5.4238891601562500e-01 + <_> + + 0 -1 1162 3.3316991175524890e-04 + + 4.0896269679069519e-01 5.3009921312332153e-01 + <_> + + 0 -1 1163 -1.0813400149345398e-02 + + 6.1043697595596313e-01 4.9573341012001038e-01 + <_> + + 0 -1 1164 4.5656010508537292e-02 + + 5.0696891546249390e-01 2.8666600584983826e-01 + <_> + + 0 -1 1165 1.2569549726322293e-03 + + 4.8469170928001404e-01 6.3181710243225098e-01 + <_> + + 0 -1 1166 -1.2015070021152496e-01 + + 6.0526140034198761e-02 4.9809598922729492e-01 + <_> + + 0 -1 1167 -1.0533799650147557e-04 + + 5.3631097078323364e-01 4.7080421447753906e-01 + <_> + + 0 -1 1168 -2.0703190565109253e-01 + + 5.9660330414772034e-02 4.9790981411933899e-01 + <_> + + 0 -1 1169 1.2909180077258497e-04 + + 4.7129771113395691e-01 5.3779977560043335e-01 + <_> + + 0 -1 1170 3.8818528992123902e-04 + + 4.3635380268096924e-01 5.5341911315917969e-01 + <_> + + 0 -1 1171 -2.9243610333651304e-03 + + 5.8111858367919922e-01 4.8252159357070923e-01 + <_> + + 0 -1 1172 8.3882332546636462e-04 + + 5.3117001056671143e-01 4.0381389856338501e-01 + <_> + + 0 -1 1173 -1.9061550265178084e-03 + + 3.7707018852233887e-01 5.2600151300430298e-01 + <_> + + 0 -1 1174 8.9514348655939102e-03 + + 4.7661679983139038e-01 7.6821839809417725e-01 + <_> + + 0 -1 1175 1.3083459809422493e-02 + + 5.2644628286361694e-01 3.0622220039367676e-01 + <_> + + 0 -1 1176 -2.1159330010414124e-01 + + 6.7371982336044312e-01 4.6958100795745850e-01 + <_> + + 0 -1 1177 3.1493250280618668e-03 + + 5.6448352336883545e-01 4.3869531154632568e-01 + <_> + + 0 -1 1178 3.9754100725986063e-04 + + 4.5260611176490784e-01 5.8956301212310791e-01 + <_> + + 0 -1 1179 -1.3814480043947697e-03 + + 6.0705822706222534e-01 4.9424138665199280e-01 + <_> + + 0 -1 1180 -5.8122188784182072e-04 + + 5.9982132911682129e-01 4.5082521438598633e-01 + <_> + + 0 -1 1181 -2.3905329871922731e-03 + + 4.2055889964103699e-01 5.2238482236862183e-01 + <_> + + 0 -1 1182 2.7268929407000542e-02 + + 5.2064472436904907e-01 3.5633018612861633e-01 + <_> + + 0 -1 1183 -3.7658358924090862e-03 + + 3.1447041034698486e-01 5.2188140153884888e-01 + <_> + + 0 -1 1184 -1.4903489500284195e-03 + + 3.3801960945129395e-01 5.1244372129440308e-01 + <_> + + 0 -1 1185 -1.7428230494260788e-02 + + 5.8299607038497925e-01 4.9197259545326233e-01 + <_> + + 0 -1 1186 -1.5278030186891556e-02 + + 6.1631447076797485e-01 4.6178871393203735e-01 + <_> + + 0 -1 1187 3.1995609402656555e-02 + + 5.1663571596145630e-01 1.7127640545368195e-01 + <_> + + 0 -1 1188 -3.8256710395216942e-03 + + 3.4080120921134949e-01 5.1313877105712891e-01 + <_> + + 0 -1 1189 -8.5186436772346497e-03 + + 6.1055189371109009e-01 4.9979418516159058e-01 + <_> + + 0 -1 1190 9.0641621500253677e-04 + + 4.3272709846496582e-01 5.5823111534118652e-01 + <_> + + 0 -1 1191 1.0344849899411201e-02 + + 4.8556530475616455e-01 5.4524201154708862e-01 + <_> + 160 + 7.9249076843261719e+01 + + <_> + + 0 -1 1192 7.8981826081871986e-03 + + 3.3325248956680298e-01 5.9464621543884277e-01 + <_> + + 0 -1 1193 1.6170160379260778e-03 + + 3.4906411170959473e-01 5.5778688192367554e-01 + <_> + + 0 -1 1194 -5.5449741194024682e-04 + + 5.5425661802291870e-01 3.2915300130844116e-01 + <_> + + 0 -1 1195 1.5428980113938451e-03 + + 3.6125791072845459e-01 5.5459791421890259e-01 + <_> + + 0 -1 1196 -1.0329450014978647e-03 + + 3.5301390290260315e-01 5.5761402845382690e-01 + <_> + + 0 -1 1197 7.7698158565908670e-04 + + 3.9167788624763489e-01 5.6453210115432739e-01 + <_> + + 0 -1 1198 1.4320300519466400e-01 + + 4.6674820780754089e-01 7.0236331224441528e-01 + <_> + + 0 -1 1199 -7.3866490274667740e-03 + + 3.0736848711967468e-01 5.2892577648162842e-01 + <_> + + 0 -1 1200 -6.2936742324382067e-04 + + 5.6221181154251099e-01 4.0370491147041321e-01 + <_> + + 0 -1 1201 7.8893528552725911e-04 + + 5.2676612138748169e-01 3.5578748583793640e-01 + <_> + + 0 -1 1202 -1.2228050269186497e-02 + + 6.6683208942413330e-01 4.6255499124526978e-01 + <_> + + 0 -1 1203 3.5420239437371492e-03 + + 5.5214381217956543e-01 3.8696730136871338e-01 + <_> + + 0 -1 1204 -1.0585320414975286e-03 + + 3.6286780238151550e-01 5.3209269046783447e-01 + <_> + + 0 -1 1205 1.4935660146875307e-05 + + 4.6324449777603149e-01 5.3633230924606323e-01 + <_> + + 0 -1 1206 5.2537708543241024e-03 + + 5.1322317123413086e-01 3.2657089829444885e-01 + <_> + + 0 -1 1207 -8.2338023930788040e-03 + + 6.6936898231506348e-01 4.7741401195526123e-01 + <_> + + 0 -1 1208 2.1866810129722580e-05 + + 4.0538620948791504e-01 5.4579311609268188e-01 + <_> + + 0 -1 1209 -3.8150229956954718e-03 + + 6.4549958705902100e-01 4.7931781411170959e-01 + <_> + + 0 -1 1210 1.1105879675596952e-03 + + 5.2704071998596191e-01 3.5296788811683655e-01 + <_> + + 0 -1 1211 -5.7707689702510834e-03 + + 3.8035470247268677e-01 5.3529578447341919e-01 + <_> + + 0 -1 1212 -3.0158339068293571e-03 + + 5.3394031524658203e-01 3.8871330022811890e-01 + <_> + + 0 -1 1213 -8.5453689098358154e-04 + + 3.5646161437034607e-01 5.2736037969589233e-01 + <_> + + 0 -1 1214 1.1050510220229626e-02 + + 4.6719071269035339e-01 6.8497377634048462e-01 + <_> + + 0 -1 1215 4.2605839669704437e-02 + + 5.1514732837677002e-01 7.0220090448856354e-02 + <_> + + 0 -1 1216 -3.0781750101596117e-03 + + 3.0416610836982727e-01 5.1526021957397461e-01 + <_> + + 0 -1 1217 -5.4815728217363358e-03 + + 6.4302957057952881e-01 4.8972299695014954e-01 + <_> + + 0 -1 1218 3.1881860923022032e-03 + + 5.3074932098388672e-01 3.8262099027633667e-01 + <_> + + 0 -1 1219 3.5947180003859103e-04 + + 4.6500471234321594e-01 5.4219049215316772e-01 + <_> + + 0 -1 1220 -4.0705031715333462e-03 + + 2.8496798872947693e-01 5.0791162252426147e-01 + <_> + + 0 -1 1221 -1.4594170264899731e-02 + + 2.9716458916664124e-01 5.1284617185592651e-01 + <_> + + 0 -1 1222 -1.1947689927183092e-04 + + 5.6310981512069702e-01 4.3430820107460022e-01 + <_> + + 0 -1 1223 -6.9344649091362953e-04 + + 4.4035780429840088e-01 5.3599590063095093e-01 + <_> + + 0 -1 1224 1.4834799912932795e-05 + + 3.4210088849067688e-01 5.1646977663040161e-01 + <_> + + 0 -1 1225 9.0296985581517220e-03 + + 4.6393430233001709e-01 6.1140751838684082e-01 + <_> + + 0 -1 1226 -8.0640818923711777e-03 + + 2.8201588988304138e-01 5.0754940509796143e-01 + <_> + + 0 -1 1227 2.6062119752168655e-02 + + 5.2089059352874756e-01 2.6887780427932739e-01 + <_> + + 0 -1 1228 1.7314659431576729e-02 + + 4.6637138724327087e-01 6.7385399341583252e-01 + <_> + + 0 -1 1229 2.2666640579700470e-02 + + 5.2093499898910522e-01 2.2127239406108856e-01 + <_> + + 0 -1 1230 -2.1965929772704840e-03 + + 6.0631012916564941e-01 4.5381900668144226e-01 + <_> + + 0 -1 1231 -9.5282476395368576e-03 + + 4.6352049708366394e-01 5.2474308013916016e-01 + <_> + + 0 -1 1232 8.0943619832396507e-03 + + 5.2894401550292969e-01 3.9138820767402649e-01 + <_> + + 0 -1 1233 -7.2877332568168640e-02 + + 7.7520018815994263e-01 4.9902349710464478e-01 + <_> + + 0 -1 1234 -6.9009521976113319e-03 + + 2.4280390143394470e-01 5.0480902194976807e-01 + <_> + + 0 -1 1235 -1.1308239772915840e-02 + + 5.7343649864196777e-01 4.8423761129379272e-01 + <_> + + 0 -1 1236 5.9613201767206192e-02 + + 5.0298362970352173e-01 2.5249770283699036e-01 + <_> + + 0 -1 1237 -2.8624620754271746e-03 + + 6.0730451345443726e-01 4.8984599113464355e-01 + <_> + + 0 -1 1238 4.4781449250876904e-03 + + 5.0152891874313354e-01 2.2203169763088226e-01 + <_> + + 0 -1 1239 -1.7513240454718471e-03 + + 6.6144287586212158e-01 4.9338689446449280e-01 + <_> + + 0 -1 1240 4.0163420140743256e-02 + + 5.1808780431747437e-01 3.7410449981689453e-01 + <_> + + 0 -1 1241 3.4768949262797832e-04 + + 4.7204169631004333e-01 5.8180320262908936e-01 + <_> + + 0 -1 1242 2.6551650371402502e-03 + + 3.8050109148025513e-01 5.2213358879089355e-01 + <_> + + 0 -1 1243 -8.7706279009580612e-03 + + 2.9441660642623901e-01 5.2312952280044556e-01 + <_> + + 0 -1 1244 -5.5122091434895992e-03 + + 7.3461771011352539e-01 4.7228169441223145e-01 + <_> + + 0 -1 1245 6.8672042107209563e-04 + + 5.4528760910034180e-01 4.2424130439758301e-01 + <_> + + 0 -1 1246 5.6019669864326715e-04 + + 4.3988621234893799e-01 5.6012850999832153e-01 + <_> + + 0 -1 1247 2.4143769405782223e-03 + + 4.7416868805885315e-01 6.1366218328475952e-01 + <_> + + 0 -1 1248 -1.5680900542065501e-03 + + 6.0445529222488403e-01 4.5164099335670471e-01 + <_> + + 0 -1 1249 -3.6827491130679846e-03 + + 2.4524590373039246e-01 5.2949821949005127e-01 + <_> + + 0 -1 1250 -2.9409190756268799e-04 + + 3.7328380346298218e-01 5.2514511346817017e-01 + <_> + + 0 -1 1251 4.2847759323194623e-04 + + 5.4988098144531250e-01 4.0655350685119629e-01 + <_> + + 0 -1 1252 -4.8817070201039314e-03 + + 2.1399089694023132e-01 4.9999570846557617e-01 + <_> + + 0 -1 1253 2.7272020815871656e-04 + + 4.6502870321273804e-01 5.8134287595748901e-01 + <_> + + 0 -1 1254 2.0947199664078653e-04 + + 4.3874868750572205e-01 5.5727928876876831e-01 + <_> + + 0 -1 1255 4.8501189798116684e-02 + + 5.2449727058410645e-01 3.2128891348838806e-01 + <_> + + 0 -1 1256 -4.5166411437094212e-03 + + 6.0568130016326904e-01 4.5458820462226868e-01 + <_> + + 0 -1 1257 -1.2291680090129375e-02 + + 2.0409290492534637e-01 5.1522141695022583e-01 + <_> + + 0 -1 1258 4.8549679922871292e-04 + + 5.2376049757003784e-01 3.7395030260086060e-01 + <_> + + 0 -1 1259 3.0556049197912216e-02 + + 4.9605339765548706e-01 5.9382462501525879e-01 + <_> + + 0 -1 1260 -1.5105320198927075e-04 + + 5.3513038158416748e-01 4.1452041268348694e-01 + <_> + + 0 -1 1261 2.4937440175563097e-03 + + 4.6933668851852417e-01 5.5149412155151367e-01 + <_> + + 0 -1 1262 -1.2382130138576031e-02 + + 6.7913967370986938e-01 4.6816679835319519e-01 + <_> + + 0 -1 1263 -5.1333461888134480e-03 + + 3.6087390780448914e-01 5.2291601896286011e-01 + <_> + + 0 -1 1264 5.1919277757406235e-04 + + 5.3000730276107788e-01 3.6336138844490051e-01 + <_> + + 0 -1 1265 1.5060420334339142e-01 + + 5.1573169231414795e-01 2.2117820382118225e-01 + <_> + + 0 -1 1266 7.7144149690866470e-03 + + 4.4104969501495361e-01 5.7766091823577881e-01 + <_> + + 0 -1 1267 9.4443522393703461e-03 + + 5.4018551111221313e-01 3.7566500902175903e-01 + <_> + + 0 -1 1268 2.5006249779835343e-04 + + 4.3682709336280823e-01 5.6073749065399170e-01 + <_> + + 0 -1 1269 -3.3077150583267212e-03 + + 4.2447990179061890e-01 5.5182307958602905e-01 + <_> + + 0 -1 1270 7.4048910755664110e-04 + + 4.4969621300697327e-01 5.9005767107009888e-01 + <_> + + 0 -1 1271 4.4092051684856415e-02 + + 5.2934932708740234e-01 3.1563550233840942e-01 + <_> + + 0 -1 1272 3.3639909233897924e-03 + + 4.4832968711853027e-01 5.8486622571945190e-01 + <_> + + 0 -1 1273 -3.9760079234838486e-03 + + 4.5595070719718933e-01 5.4836392402648926e-01 + <_> + + 0 -1 1274 2.7716930489987135e-03 + + 5.3417861461639404e-01 3.7924841046333313e-01 + <_> + + 0 -1 1275 -2.4123019829858094e-04 + + 5.6671887636184692e-01 4.5769730210304260e-01 + <_> + + 0 -1 1276 4.9425667384639382e-04 + + 4.4212448596954346e-01 5.6287872791290283e-01 + <_> + + 0 -1 1277 -3.8876468897797167e-04 + + 4.2883709073066711e-01 5.3910630941390991e-01 + <_> + + 0 -1 1278 -5.0048898905515671e-02 + + 6.8995130062103271e-01 4.7037428617477417e-01 + <_> + + 0 -1 1279 -3.6635480821132660e-02 + + 2.2177790105342865e-01 5.1918262243270874e-01 + <_> + + 0 -1 1280 2.4273579474538565e-03 + + 5.1362240314483643e-01 3.4973978996276855e-01 + <_> + + 0 -1 1281 1.9558030180633068e-03 + + 4.8261928558349609e-01 6.4083808660507202e-01 + <_> + + 0 -1 1282 -1.7494610510766506e-03 + + 3.9228358864784241e-01 5.2726852893829346e-01 + <_> + + 0 -1 1283 1.3955079950392246e-02 + + 5.0782018899917603e-01 8.4165048599243164e-01 + <_> + + 0 -1 1284 -2.1896739781368524e-04 + + 5.5204898118972778e-01 4.3142348527908325e-01 + <_> + + 0 -1 1285 -1.5131309628486633e-03 + + 3.9346051216125488e-01 5.3825712203979492e-01 + <_> + + 0 -1 1286 -4.3622800149023533e-03 + + 7.3706287145614624e-01 4.7364759445190430e-01 + <_> + + 0 -1 1287 6.5160587430000305e-02 + + 5.1592797040939331e-01 3.2815951108932495e-01 + <_> + + 0 -1 1288 -2.3567399475723505e-03 + + 3.6728268861770630e-01 5.1728862524032593e-01 + <_> + + 0 -1 1289 1.5146659687161446e-02 + + 5.0314939022064209e-01 6.6876041889190674e-01 + <_> + + 0 -1 1290 -2.2850960493087769e-02 + + 6.7675197124481201e-01 4.7095969319343567e-01 + <_> + + 0 -1 1291 4.8867650330066681e-03 + + 5.2579981088638306e-01 4.0598788857460022e-01 + <_> + + 0 -1 1292 1.7619599821045995e-03 + + 4.6962729096412659e-01 6.6882789134979248e-01 + <_> + + 0 -1 1293 -1.2942519970238209e-03 + + 4.3207129836082458e-01 5.3442817926406860e-01 + <_> + + 0 -1 1294 1.0929949581623077e-02 + + 4.9977061152458191e-01 1.6374860703945160e-01 + <_> + + 0 -1 1295 2.9958489903947338e-05 + + 4.2824178934097290e-01 5.6332242488861084e-01 + <_> + + 0 -1 1296 -6.5884361974895000e-03 + + 6.7721211910247803e-01 4.7005268931388855e-01 + <_> + + 0 -1 1297 3.2527779694646597e-03 + + 5.3133970499038696e-01 4.5361489057540894e-01 + <_> + + 0 -1 1298 -4.0435739792883396e-03 + + 5.6600618362426758e-01 4.4133889675140381e-01 + <_> + + 0 -1 1299 -1.2523540062829852e-03 + + 3.7319138646125793e-01 5.3564518690109253e-01 + <_> + + 0 -1 1300 1.9246719602961093e-04 + + 5.1899862289428711e-01 3.7388110160827637e-01 + <_> + + 0 -1 1301 -3.8589671254158020e-02 + + 2.9563739895820618e-01 5.1888108253479004e-01 + <_> + + 0 -1 1302 1.5489870565943420e-04 + + 4.3471351265907288e-01 5.5095332860946655e-01 + <_> + + 0 -1 1303 -3.3763848245143890e-02 + + 3.2303300499916077e-01 5.1954758167266846e-01 + <_> + + 0 -1 1304 -8.2657067105174065e-03 + + 5.9754890203475952e-01 4.5521140098571777e-01 + <_> + + 0 -1 1305 1.4481440302915871e-05 + + 4.7456780076026917e-01 5.4974269866943359e-01 + <_> + + 0 -1 1306 1.4951299817766994e-05 + + 4.3244731426239014e-01 5.4806441068649292e-01 + <_> + + 0 -1 1307 -1.8741799518465996e-02 + + 1.5800529718399048e-01 5.1785331964492798e-01 + <_> + + 0 -1 1308 1.7572239739820361e-03 + + 4.5176368951797485e-01 5.7737642526626587e-01 + <_> + + 0 -1 1309 -3.1391119118779898e-03 + + 4.1496479511260986e-01 5.4608422517776489e-01 + <_> + + 0 -1 1310 6.6656779381446540e-05 + + 4.0390908718109131e-01 5.2930849790573120e-01 + <_> + + 0 -1 1311 6.7743421532213688e-03 + + 4.7676518559455872e-01 6.1219561100006104e-01 + <_> + + 0 -1 1312 -7.3868161998689175e-03 + + 3.5862588882446289e-01 5.1872807741165161e-01 + <_> + + 0 -1 1313 1.4040930196642876e-02 + + 4.7121399641036987e-01 5.5761557817459106e-01 + <_> + + 0 -1 1314 -5.5258329957723618e-03 + + 2.6610270142555237e-01 5.0392812490463257e-01 + <_> + + 0 -1 1315 3.8684239983558655e-01 + + 5.1443397998809814e-01 2.5258991122245789e-01 + <_> + + 0 -1 1316 1.1459240340627730e-04 + + 4.2849949002265930e-01 5.4233711957931519e-01 + <_> + + 0 -1 1317 -1.8467569723725319e-02 + + 3.8858351111412048e-01 5.2130621671676636e-01 + <_> + + 0 -1 1318 -4.5907011372037232e-04 + + 5.4125630855560303e-01 4.2359098792076111e-01 + <_> + + 0 -1 1319 1.2527540093287826e-03 + + 4.8993051052093506e-01 6.6240912675857544e-01 + <_> + + 0 -1 1320 1.4910609461367130e-03 + + 5.2867782115936279e-01 4.0400519967079163e-01 + <_> + + 0 -1 1321 -7.5435562757775187e-04 + + 6.0329902172088623e-01 4.7951200604438782e-01 + <_> + + 0 -1 1322 -6.9478838704526424e-03 + + 4.0844011306762695e-01 5.3735041618347168e-01 + <_> + + 0 -1 1323 2.8092920547351241e-04 + + 4.8460629582405090e-01 5.7593822479248047e-01 + <_> + + 0 -1 1324 9.6073717577382922e-04 + + 5.1647412776947021e-01 3.5549798607826233e-01 + <_> + + 0 -1 1325 -2.6883929967880249e-04 + + 5.6775820255279541e-01 4.7317659854888916e-01 + <_> + + 0 -1 1326 2.1599370520561934e-03 + + 4.7314870357513428e-01 7.0705670118331909e-01 + <_> + + 0 -1 1327 5.6235301308333874e-03 + + 5.2402430772781372e-01 2.7817919850349426e-01 + <_> + + 0 -1 1328 -5.0243991427123547e-03 + + 2.8370139002799988e-01 5.0623041391372681e-01 + <_> + + 0 -1 1329 -9.7611639648675919e-03 + + 7.4007177352905273e-01 4.9345690011978149e-01 + <_> + + 0 -1 1330 4.1515100747346878e-03 + + 5.1191312074661255e-01 3.4070080518722534e-01 + <_> + + 0 -1 1331 6.2465080991387367e-03 + + 4.9237880110740662e-01 6.5790587663650513e-01 + <_> + + 0 -1 1332 -7.0597478188574314e-03 + + 2.4347110092639923e-01 5.0328421592712402e-01 + <_> + + 0 -1 1333 -2.0587709732353687e-03 + + 5.9003108739852905e-01 4.6950870752334595e-01 + <_> + + 0 -1 1334 -2.4146060459315777e-03 + + 3.6473178863525391e-01 5.1892018318176270e-01 + <_> + + 0 -1 1335 -1.4817609917372465e-03 + + 6.0349482297897339e-01 4.9401280283927917e-01 + <_> + + 0 -1 1336 -6.3016400672495365e-03 + + 5.8189898729324341e-01 4.5604279637336731e-01 + <_> + + 0 -1 1337 3.4763428848236799e-03 + + 5.2174758911132812e-01 3.4839931130409241e-01 + <_> + + 0 -1 1338 -2.2250870242714882e-02 + + 2.3607000708580017e-01 5.0320827960968018e-01 + <_> + + 0 -1 1339 -3.0612550675868988e-02 + + 6.4991867542266846e-01 4.9149191379547119e-01 + <_> + + 0 -1 1340 1.3057479634881020e-02 + + 4.4133231043815613e-01 5.6837642192840576e-01 + <_> + + 0 -1 1341 -6.0095742810517550e-04 + + 4.3597310781478882e-01 5.3334832191467285e-01 + <_> + + 0 -1 1342 -4.1514250915497541e-04 + + 5.5040627717971802e-01 4.3260601162910461e-01 + <_> + + 0 -1 1343 -1.3776290230453014e-02 + + 4.0641129016876221e-01 5.2015489339828491e-01 + <_> + + 0 -1 1344 -3.2296508550643921e-02 + + 4.7351971268653870e-02 4.9771949648857117e-01 + <_> + + 0 -1 1345 5.3556978702545166e-02 + + 4.8817330598831177e-01 6.6669392585754395e-01 + <_> + + 0 -1 1346 8.1889545544981956e-03 + + 5.4000371694564819e-01 4.2408201098442078e-01 + <_> + + 0 -1 1347 2.1055320394225419e-04 + + 4.8020479083061218e-01 5.5638527870178223e-01 + <_> + + 0 -1 1348 -2.4382730480283499e-03 + + 7.3877930641174316e-01 4.7736850380897522e-01 + <_> + + 0 -1 1349 3.2835570164024830e-03 + + 5.2885460853576660e-01 3.1712919473648071e-01 + <_> + + 0 -1 1350 2.3729570675641298e-03 + + 4.7508129477500916e-01 7.0601707696914673e-01 + <_> + + 0 -1 1351 -1.4541699783876538e-03 + + 3.8117301464080811e-01 5.3307390213012695e-01 + <_> + 177 + 8.7696029663085938e+01 + + <_> + + 0 -1 1352 5.5755238980054855e-02 + + 4.0191569924354553e-01 6.8060368299484253e-01 + <_> + + 0 -1 1353 2.4730248842388391e-03 + + 3.3511489629745483e-01 5.9657198190689087e-01 + <_> + + 0 -1 1354 -3.5031698644161224e-04 + + 5.5577081441879272e-01 3.4822869300842285e-01 + <_> + + 0 -1 1355 5.4167630150914192e-04 + + 4.2608588933944702e-01 5.6933808326721191e-01 + <_> + + 0 -1 1356 7.7193678589537740e-04 + + 3.4942400455474854e-01 5.4336887598037720e-01 + <_> + + 0 -1 1357 -1.5999219613149762e-03 + + 4.0284991264343262e-01 5.4843592643737793e-01 + <_> + + 0 -1 1358 -1.1832080053864047e-04 + + 3.8069018721580505e-01 5.4254651069641113e-01 + <_> + + 0 -1 1359 3.2909031142480671e-04 + + 2.6201000809669495e-01 5.4295217990875244e-01 + <_> + + 0 -1 1360 2.9518108931370080e-04 + + 3.7997689843177795e-01 5.3992640972137451e-01 + <_> + + 0 -1 1361 9.0466710389591753e-05 + + 4.4336450099945068e-01 5.4402261972427368e-01 + <_> + + 0 -1 1362 1.5007190086180344e-05 + + 3.7196549773216248e-01 5.4091197252273560e-01 + <_> + + 0 -1 1363 1.3935610651969910e-01 + + 5.5253958702087402e-01 4.4790428876876831e-01 + <_> + + 0 -1 1364 1.6461990308016539e-03 + + 4.2645010352134705e-01 5.7721698284149170e-01 + <_> + + 0 -1 1365 4.9984431825578213e-04 + + 4.3595260381698608e-01 5.6858712434768677e-01 + <_> + + 0 -1 1366 -1.0971280280500650e-03 + + 3.3901369571685791e-01 5.2054089307785034e-01 + <_> + + 0 -1 1367 6.6919892560690641e-04 + + 4.5574560761451721e-01 5.9806597232818604e-01 + <_> + + 0 -1 1368 8.6471042595803738e-04 + + 5.1348412036895752e-01 2.9440331459045410e-01 + <_> + + 0 -1 1369 -2.7182599296793342e-04 + + 3.9065781235694885e-01 5.3771811723709106e-01 + <_> + + 0 -1 1370 3.0249499104684219e-05 + + 3.6796098947525024e-01 5.2256888151168823e-01 + <_> + + 0 -1 1371 -8.5225896909832954e-03 + + 7.2931021451950073e-01 4.8923650383949280e-01 + <_> + + 0 -1 1372 1.6705560265108943e-03 + + 4.3453249335289001e-01 5.6961381435394287e-01 + <_> + + 0 -1 1373 -7.1433838456869125e-03 + + 2.5912800431251526e-01 5.2256238460540771e-01 + <_> + + 0 -1 1374 -1.6319369897246361e-02 + + 6.9222790002822876e-01 4.6515759825706482e-01 + <_> + + 0 -1 1375 4.8034260980784893e-03 + + 5.3522628545761108e-01 3.2863029837608337e-01 + <_> + + 0 -1 1376 -7.5421929359436035e-03 + + 2.0405440032482147e-01 5.0345462560653687e-01 + <_> + + 0 -1 1377 -1.4363110065460205e-02 + + 6.8048888444900513e-01 4.8890590667724609e-01 + <_> + + 0 -1 1378 8.9063588529825211e-04 + + 5.3106957674026489e-01 3.8954809308052063e-01 + <_> + + 0 -1 1379 -4.4060191139578819e-03 + + 5.7415628433227539e-01 4.3724268674850464e-01 + <_> + + 0 -1 1380 -1.8862540309783071e-04 + + 2.8317859768867493e-01 5.0982052087783813e-01 + <_> + + 0 -1 1381 -3.7979281041771173e-03 + + 3.3725079894065857e-01 5.2465802431106567e-01 + <_> + + 0 -1 1382 1.4627049677073956e-04 + + 5.3066742420196533e-01 3.9117100834846497e-01 + <_> + + 0 -1 1383 -4.9164638767251745e-05 + + 5.4624962806701660e-01 3.9427208900451660e-01 + <_> + + 0 -1 1384 -3.3582501113414764e-02 + + 2.1578240394592285e-01 5.0482118129730225e-01 + <_> + + 0 -1 1385 -3.5339309833943844e-03 + + 6.4653122425079346e-01 4.8726969957351685e-01 + <_> + + 0 -1 1386 5.0144111737608910e-03 + + 4.6176680922508240e-01 6.2480747699737549e-01 + <_> + + 0 -1 1387 1.8817370757460594e-02 + + 5.2206891775131226e-01 2.0000520348548889e-01 + <_> + + 0 -1 1388 -1.3434339780360460e-03 + + 4.0145379304885864e-01 5.3016197681427002e-01 + <_> + + 0 -1 1389 1.7557960236445069e-03 + + 4.7940391302108765e-01 5.6531697511672974e-01 + <_> + + 0 -1 1390 -9.5637463033199310e-02 + + 2.0341950654983521e-01 5.0067067146301270e-01 + <_> + + 0 -1 1391 -2.2241229191422462e-02 + + 7.6724731922149658e-01 5.0463402271270752e-01 + <_> + + 0 -1 1392 -1.5575819648802280e-02 + + 7.4903422594070435e-01 4.7558510303497314e-01 + <_> + + 0 -1 1393 5.3599118255078793e-03 + + 5.3653037548065186e-01 4.0046709775924683e-01 + <_> + + 0 -1 1394 -2.1763499826192856e-02 + + 7.4015498161315918e-02 4.9641749262809753e-01 + <_> + + 0 -1 1395 -1.6561590135097504e-01 + + 2.8591030836105347e-01 5.2180862426757812e-01 + <_> + + 0 -1 1396 1.6461320046801120e-04 + + 4.1916158795356750e-01 5.3807932138442993e-01 + <_> + + 0 -1 1397 -8.9077502489089966e-03 + + 6.2731927633285522e-01 4.8774048686027527e-01 + <_> + + 0 -1 1398 8.6346449097618461e-04 + + 5.1599407196044922e-01 3.6710259318351746e-01 + <_> + + 0 -1 1399 -1.3751760125160217e-03 + + 5.8843767642974854e-01 4.5790839195251465e-01 + <_> + + 0 -1 1400 -1.4081239933148026e-03 + + 3.5605099797248840e-01 5.1399451494216919e-01 + <_> + + 0 -1 1401 -3.9342888630926609e-03 + + 5.9942889213562012e-01 4.6642720699310303e-01 + <_> + + 0 -1 1402 -3.1966928392648697e-02 + + 3.3454620838165283e-01 5.1441830396652222e-01 + <_> + + 0 -1 1403 -1.5089280168467667e-05 + + 5.5826562643051147e-01 4.4140571355819702e-01 + <_> + + 0 -1 1404 5.1994470413774252e-04 + + 4.6236801147460938e-01 6.1689937114715576e-01 + <_> + + 0 -1 1405 -3.4220460802316666e-03 + + 6.5570747852325439e-01 4.9748051166534424e-01 + <_> + + 0 -1 1406 1.7723299970384687e-04 + + 5.2695018053054810e-01 3.9019080996513367e-01 + <_> + + 0 -1 1407 1.5716759953647852e-03 + + 4.6333730220794678e-01 5.7904577255249023e-01 + <_> + + 0 -1 1408 -8.9041329920291901e-03 + + 2.6896080374717712e-01 5.0535911321640015e-01 + <_> + + 0 -1 1409 4.0677518700249493e-04 + + 5.4566031694412231e-01 4.3298989534378052e-01 + <_> + + 0 -1 1410 6.7604780197143555e-03 + + 4.6489939093589783e-01 6.6897618770599365e-01 + <_> + + 0 -1 1411 2.9100088868290186e-03 + + 5.3097039461135864e-01 3.3778399229049683e-01 + <_> + + 0 -1 1412 1.3885459629818797e-03 + + 4.0747389197349548e-01 5.3491330146789551e-01 + <_> + + 0 -1 1413 -7.6764263212680817e-02 + + 1.9921760261058807e-01 5.2282422780990601e-01 + <_> + + 0 -1 1414 -2.2688310127705336e-04 + + 5.4385018348693848e-01 4.2530721426010132e-01 + <_> + + 0 -1 1415 -6.3094152137637138e-03 + + 4.2591789364814758e-01 5.3789097070693970e-01 + <_> + + 0 -1 1416 -1.1007279902696609e-01 + + 6.9041568040847778e-01 4.7217491269111633e-01 + <_> + + 0 -1 1417 2.8619659133255482e-04 + + 4.5249149203300476e-01 5.5483061075210571e-01 + <_> + + 0 -1 1418 2.9425329557852820e-05 + + 5.3703737258911133e-01 4.2364639043807983e-01 + <_> + + 0 -1 1419 -2.4886570870876312e-02 + + 6.4235579967498779e-01 4.9693039059638977e-01 + <_> + + 0 -1 1420 3.3148851245641708e-02 + + 4.9884751439094543e-01 1.6138119995594025e-01 + <_> + + 0 -1 1421 7.8491691965609789e-04 + + 5.4160261154174805e-01 4.2230090498924255e-01 + <_> + + 0 -1 1422 4.7087189741432667e-03 + + 4.5763289928436279e-01 6.0275578498840332e-01 + <_> + + 0 -1 1423 2.4144479539245367e-03 + + 5.3089731931686401e-01 4.4224989414215088e-01 + <_> + + 0 -1 1424 1.9523180089890957e-03 + + 4.7056341171264648e-01 6.6633248329162598e-01 + <_> + + 0 -1 1425 1.3031980488449335e-03 + + 4.4061261415481567e-01 5.5269622802734375e-01 + <_> + + 0 -1 1426 4.4735497795045376e-03 + + 5.1290237903594971e-01 3.3014988899230957e-01 + <_> + + 0 -1 1427 -2.6652868837118149e-03 + + 3.1354710459709167e-01 5.1750361919403076e-01 + <_> + + 0 -1 1428 1.3666770246345550e-04 + + 4.1193708777427673e-01 5.3068768978118896e-01 + <_> + + 0 -1 1429 -1.7126450315117836e-02 + + 6.1778062582015991e-01 4.8365789651870728e-01 + <_> + + 0 -1 1430 -2.6601430727168918e-04 + + 3.6543309688568115e-01 5.1697367429733276e-01 + <_> + + 0 -1 1431 -2.2932380437850952e-02 + + 3.4909150004386902e-01 5.1639920473098755e-01 + <_> + + 0 -1 1432 2.3316550068557262e-03 + + 5.1662999391555786e-01 3.7093898653984070e-01 + <_> + + 0 -1 1433 1.6925660893321037e-02 + + 5.0147360563278198e-01 8.0539882183074951e-01 + <_> + + 0 -1 1434 -8.9858826249837875e-03 + + 6.4707887172698975e-01 4.6570208668708801e-01 + <_> + + 0 -1 1435 -1.1874699965119362e-02 + + 3.2463788986206055e-01 5.2587550878524780e-01 + <_> + + 0 -1 1436 1.9350569345988333e-04 + + 5.1919418573379517e-01 3.8396438956260681e-01 + <_> + + 0 -1 1437 5.8713490143418312e-03 + + 4.9181339144706726e-01 6.1870431900024414e-01 + <_> + + 0 -1 1438 -2.4838790297508240e-01 + + 1.8368029594421387e-01 4.9881500005722046e-01 + <_> + + 0 -1 1439 1.2256000190973282e-02 + + 5.2270537614822388e-01 3.6320298910140991e-01 + <_> + + 0 -1 1440 8.3990179700776935e-04 + + 4.4902500510215759e-01 5.7741481065750122e-01 + <_> + + 0 -1 1441 2.5407369248569012e-03 + + 4.8047870397567749e-01 5.8582991361618042e-01 + <_> + + 0 -1 1442 -1.4822429977357388e-02 + + 2.5210499763488770e-01 5.0235372781753540e-01 + <_> + + 0 -1 1443 -5.7973959483206272e-03 + + 5.9966957569122314e-01 4.8537150025367737e-01 + <_> + + 0 -1 1444 7.2662148158997297e-04 + + 5.1537168025970459e-01 3.6717799305915833e-01 + <_> + + 0 -1 1445 -1.7232580110430717e-02 + + 6.6217190027236938e-01 4.9946561455726624e-01 + <_> + + 0 -1 1446 7.8624086454510689e-03 + + 4.6333950757980347e-01 6.2561017274856567e-01 + <_> + + 0 -1 1447 -4.7343620099127293e-03 + + 3.6155730485916138e-01 5.2818852663040161e-01 + <_> + + 0 -1 1448 8.3048478700220585e-04 + + 4.4428890943527222e-01 5.5509579181671143e-01 + <_> + + 0 -1 1449 7.6602199114859104e-03 + + 5.1629352569580078e-01 2.6133549213409424e-01 + <_> + + 0 -1 1450 -4.1048377752304077e-03 + + 2.7896320819854736e-01 5.0190317630767822e-01 + <_> + + 0 -1 1451 4.8512578941881657e-03 + + 4.9689841270446777e-01 5.6616681814193726e-01 + <_> + + 0 -1 1452 9.9896453320980072e-04 + + 4.4456079602241516e-01 5.5518132448196411e-01 + <_> + + 0 -1 1453 -2.7023631334304810e-01 + + 2.9388209804892540e-02 5.1513141393661499e-01 + <_> + + 0 -1 1454 -1.3090680353343487e-02 + + 5.6993997097015381e-01 4.4474598765373230e-01 + <_> + + 0 -1 1455 -9.4342790544033051e-03 + + 4.3054661154747009e-01 5.4878950119018555e-01 + <_> + + 0 -1 1456 -1.5482039889320731e-03 + + 3.6803171038627625e-01 5.1280808448791504e-01 + <_> + + 0 -1 1457 5.3746132180094719e-03 + + 4.8389169573783875e-01 6.1015558242797852e-01 + <_> + + 0 -1 1458 1.5786769799888134e-03 + + 5.3252232074737549e-01 4.1185480356216431e-01 + <_> + + 0 -1 1459 3.6856050137430429e-03 + + 4.8109480738639832e-01 6.2523031234741211e-01 + <_> + + 0 -1 1460 9.3887019902467728e-03 + + 5.2002298831939697e-01 3.6294108629226685e-01 + <_> + + 0 -1 1461 1.2792630121111870e-02 + + 4.9617099761962891e-01 6.7380160093307495e-01 + <_> + + 0 -1 1462 -3.3661040943115950e-03 + + 4.0602791309356689e-01 5.2835988998413086e-01 + <_> + + 0 -1 1463 3.9771420415490866e-04 + + 4.6741139888763428e-01 5.9007751941680908e-01 + <_> + + 0 -1 1464 1.4868030557408929e-03 + + 4.5191168785095215e-01 6.0820537805557251e-01 + <_> + + 0 -1 1465 -8.8686749339103699e-02 + + 2.8078991174697876e-01 5.1809918880462646e-01 + <_> + + 0 -1 1466 -7.4296112870797515e-05 + + 5.2955842018127441e-01 4.0876251459121704e-01 + <_> + + 0 -1 1467 -1.4932939848222304e-05 + + 5.4614001512527466e-01 4.5385429263114929e-01 + <_> + + 0 -1 1468 5.9162238612771034e-03 + + 5.3291612863540649e-01 4.1921341419219971e-01 + <_> + + 0 -1 1469 1.1141640134155750e-03 + + 4.5120179653167725e-01 5.7062172889709473e-01 + <_> + + 0 -1 1470 8.9249362645205110e-05 + + 4.5778059959411621e-01 5.8976382017135620e-01 + <_> + + 0 -1 1471 2.5319510605186224e-03 + + 5.2996039390563965e-01 3.3576390147209167e-01 + <_> + + 0 -1 1472 1.2426200322806835e-02 + + 4.9590590596199036e-01 1.3466019928455353e-01 + <_> + + 0 -1 1473 2.8335750102996826e-02 + + 5.1170790195465088e-01 6.1043637106195092e-04 + <_> + + 0 -1 1474 6.6165882162749767e-03 + + 4.7363498806953430e-01 7.0116281509399414e-01 + <_> + + 0 -1 1475 8.0468766391277313e-03 + + 5.2164179086685181e-01 3.2828199863433838e-01 + <_> + + 0 -1 1476 -1.1193980462849140e-03 + + 5.8098608255386353e-01 4.5637390017509460e-01 + <_> + + 0 -1 1477 1.3277590274810791e-02 + + 5.3983622789382935e-01 4.1039010882377625e-01 + <_> + + 0 -1 1478 4.8794739996083081e-04 + + 4.2492860555648804e-01 5.4105907678604126e-01 + <_> + + 0 -1 1479 1.1243170127272606e-02 + + 5.2699637413024902e-01 3.4382158517837524e-01 + <_> + + 0 -1 1480 -8.9896668214350939e-04 + + 5.6330758333206177e-01 4.4566130638122559e-01 + <_> + + 0 -1 1481 6.6677159629762173e-03 + + 5.3128892183303833e-01 4.3626791238784790e-01 + <_> + + 0 -1 1482 2.8947299346327782e-02 + + 4.7017949819564819e-01 6.5757977962493896e-01 + <_> + + 0 -1 1483 -2.3400049656629562e-02 + + 0. 5.1373988389968872e-01 + <_> + + 0 -1 1484 -8.9117050170898438e-02 + + 2.3745279759168625e-02 4.9424308538436890e-01 + <_> + + 0 -1 1485 -1.4054600149393082e-02 + + 3.1273230910301208e-01 5.1175111532211304e-01 + <_> + + 0 -1 1486 8.1239398568868637e-03 + + 5.0090491771697998e-01 2.5200259685516357e-01 + <_> + + 0 -1 1487 -4.9964650534093380e-03 + + 6.3871437311172485e-01 4.9278119206428528e-01 + <_> + + 0 -1 1488 3.1253970228135586e-03 + + 5.1368498802185059e-01 3.6804521083831787e-01 + <_> + + 0 -1 1489 6.7669642157852650e-03 + + 5.5098438262939453e-01 4.3636319041252136e-01 + <_> + + 0 -1 1490 -2.3711440153419971e-03 + + 6.1623352766036987e-01 4.5869469642639160e-01 + <_> + + 0 -1 1491 -5.3522791713476181e-03 + + 6.1854577064514160e-01 4.9204909801483154e-01 + <_> + + 0 -1 1492 -1.5968859195709229e-02 + + 1.3826179504394531e-01 4.9832528829574585e-01 + <_> + + 0 -1 1493 4.7676060348749161e-03 + + 4.6880578994750977e-01 5.4900461435317993e-01 + <_> + + 0 -1 1494 -2.4714691098779440e-03 + + 2.3685149848461151e-01 5.0039529800415039e-01 + <_> + + 0 -1 1495 -7.1033788844943047e-04 + + 5.8563941717147827e-01 4.7215330600738525e-01 + <_> + + 0 -1 1496 -1.4117559790611267e-01 + + 8.6900062859058380e-02 4.9615910649299622e-01 + <_> + + 0 -1 1497 1.0651809722185135e-01 + + 5.1388370990753174e-01 1.7410050332546234e-01 + <_> + + 0 -1 1498 -5.2744749933481216e-02 + + 7.3536360263824463e-01 4.7728818655014038e-01 + <_> + + 0 -1 1499 -4.7431760467588902e-03 + + 3.8844060897827148e-01 5.2927017211914062e-01 + <_> + + 0 -1 1500 9.9676765967160463e-04 + + 5.2234929800033569e-01 4.0034240484237671e-01 + <_> + + 0 -1 1501 8.0284131690859795e-03 + + 4.9591061472892761e-01 7.2129642963409424e-01 + <_> + + 0 -1 1502 8.6025858763605356e-04 + + 4.4448840618133545e-01 5.5384761095046997e-01 + <_> + + 0 -1 1503 9.3191501218825579e-04 + + 5.3983712196350098e-01 4.1632440686225891e-01 + <_> + + 0 -1 1504 -2.5082060601562262e-03 + + 5.8542650938034058e-01 4.5625001192092896e-01 + <_> + + 0 -1 1505 -2.1378761157393456e-03 + + 4.6080690622329712e-01 5.2802592515945435e-01 + <_> + + 0 -1 1506 -2.1546049974858761e-03 + + 3.7911269068717957e-01 5.2559971809387207e-01 + <_> + + 0 -1 1507 -7.6214009895920753e-03 + + 5.9986090660095215e-01 4.9520739912986755e-01 + <_> + + 0 -1 1508 2.2055360022932291e-03 + + 4.4842061400413513e-01 5.5885308980941772e-01 + <_> + + 0 -1 1509 1.2586950324475765e-03 + + 5.4507470130920410e-01 4.4238409399986267e-01 + <_> + + 0 -1 1510 -5.0926720723509789e-03 + + 4.1182750463485718e-01 5.2630358934402466e-01 + <_> + + 0 -1 1511 -2.5095739401876926e-03 + + 5.7879078388214111e-01 4.9984949827194214e-01 + <_> + + 0 -1 1512 -7.7327556908130646e-02 + + 8.3978658914566040e-01 4.8111200332641602e-01 + <_> + + 0 -1 1513 -4.1485819965600967e-02 + + 2.4086110293865204e-01 5.1769930124282837e-01 + <_> + + 0 -1 1514 1.0355669655837119e-04 + + 4.3553608655929565e-01 5.4170542955398560e-01 + <_> + + 0 -1 1515 1.3255809899419546e-03 + + 5.4539710283279419e-01 4.8940950632095337e-01 + <_> + + 0 -1 1516 -8.0598732456564903e-03 + + 5.7710242271423340e-01 4.5779189467430115e-01 + <_> + + 0 -1 1517 1.9058620557188988e-02 + + 5.1698678731918335e-01 3.4004750847816467e-01 + <_> + + 0 -1 1518 -3.5057891160249710e-02 + + 2.2032439708709717e-01 5.0005030632019043e-01 + <_> + + 0 -1 1519 5.7296059094369411e-03 + + 5.0434082746505737e-01 6.5975707769393921e-01 + <_> + + 0 -1 1520 -1.1648329906165600e-02 + + 2.1862849593162537e-01 4.9966529011726379e-01 + <_> + + 0 -1 1521 1.4544479781761765e-03 + + 5.0076818466186523e-01 5.5037277936935425e-01 + <_> + + 0 -1 1522 -2.5030909455381334e-04 + + 4.1298410296440125e-01 5.2416700124740601e-01 + <_> + + 0 -1 1523 -8.2907272735610604e-04 + + 5.4128682613372803e-01 4.9744960665702820e-01 + <_> + + 0 -1 1524 1.0862209601327777e-03 + + 4.6055299043655396e-01 5.8792287111282349e-01 + <_> + + 0 -1 1525 2.0000500080641359e-04 + + 5.2788549661636353e-01 4.7052091360092163e-01 + <_> + + 0 -1 1526 2.9212920926511288e-03 + + 5.1296097040176392e-01 3.7555369734764099e-01 + <_> + + 0 -1 1527 2.5387400761246681e-02 + + 4.8226919770240784e-01 5.7907682657241821e-01 + <_> + + 0 -1 1528 -3.1968469265848398e-03 + + 5.2483952045440674e-01 3.9628401398658752e-01 + <_> + 182 + 9.0253349304199219e+01 + + <_> + + 0 -1 1529 5.8031738735735416e-03 + + 3.4989839792251587e-01 5.9619832038879395e-01 + <_> + + 0 -1 1530 -9.0003069490194321e-03 + + 6.8166369199752808e-01 4.4785520434379578e-01 + <_> + + 0 -1 1531 -1.1549659539014101e-03 + + 5.5857062339782715e-01 3.5782510042190552e-01 + <_> + + 0 -1 1532 -1.1069850297644734e-03 + + 5.3650361299514771e-01 3.0504280328750610e-01 + <_> + + 0 -1 1533 1.0308309720130637e-04 + + 3.6390951275825500e-01 5.3446358442306519e-01 + <_> + + 0 -1 1534 -5.0984839908778667e-03 + + 2.8591570258140564e-01 5.5042648315429688e-01 + <_> + + 0 -1 1535 8.2572200335562229e-04 + + 5.2365237474441528e-01 3.4760418534278870e-01 + <_> + + 0 -1 1536 9.9783325567841530e-03 + + 4.7503221035003662e-01 6.2196469306945801e-01 + <_> + + 0 -1 1537 -3.7402529269456863e-02 + + 3.3433759212493896e-01 5.2780628204345703e-01 + <_> + + 0 -1 1538 4.8548257909715176e-03 + + 5.1921808719635010e-01 3.7004441022872925e-01 + <_> + + 0 -1 1539 -1.8664470408111811e-03 + + 2.9298439621925354e-01 5.0919449329376221e-01 + <_> + + 0 -1 1540 1.6888890415430069e-02 + + 3.6868458986282349e-01 5.4312258958816528e-01 + <_> + + 0 -1 1541 -5.8372621424496174e-03 + + 3.6321839690208435e-01 5.2213358879089355e-01 + <_> + + 0 -1 1542 -1.4713739510625601e-03 + + 5.8706837892532349e-01 4.7006508708000183e-01 + <_> + + 0 -1 1543 -1.1522950371727347e-03 + + 3.1958949565887451e-01 5.1409542560577393e-01 + <_> + + 0 -1 1544 -4.2560300789773464e-03 + + 6.3018590211868286e-01 4.8149210214614868e-01 + <_> + + 0 -1 1545 -6.7378291860222816e-03 + + 1.9770480692386627e-01 5.0258082151412964e-01 + <_> + + 0 -1 1546 1.1382670141756535e-02 + + 4.9541321396827698e-01 6.8670457601547241e-01 + <_> + + 0 -1 1547 5.1794708706438541e-03 + + 5.1644277572631836e-01 3.3506479859352112e-01 + <_> + + 0 -1 1548 -1.1743789911270142e-01 + + 2.3152460157871246e-01 5.2344137430191040e-01 + <_> + + 0 -1 1549 2.8703449293971062e-02 + + 4.6642971038818359e-01 6.7225211858749390e-01 + <_> + + 0 -1 1550 4.8231030814349651e-03 + + 5.2208751440048218e-01 2.7235329151153564e-01 + <_> + + 0 -1 1551 2.6798530016094446e-03 + + 5.0792771577835083e-01 2.9069489240646362e-01 + <_> + + 0 -1 1552 8.0504082143306732e-03 + + 4.8859509825706482e-01 6.3950210809707642e-01 + <_> + + 0 -1 1553 4.8054959625005722e-03 + + 5.1972568035125732e-01 3.6566638946533203e-01 + <_> + + 0 -1 1554 -2.2420159075409174e-03 + + 6.1534678936004639e-01 4.7637018561363220e-01 + <_> + + 0 -1 1555 -1.3757710345089436e-02 + + 2.6373448967933655e-01 5.0309032201766968e-01 + <_> + + 0 -1 1556 -1.0338299721479416e-01 + + 2.2875219583511353e-01 5.1824611425399780e-01 + <_> + + 0 -1 1557 -9.4432085752487183e-03 + + 6.9533038139343262e-01 4.6949490904808044e-01 + <_> + + 0 -1 1558 8.0271181650459766e-04 + + 5.4506552219390869e-01 4.2687839269638062e-01 + <_> + + 0 -1 1559 -4.1945669800043106e-03 + + 6.0913878679275513e-01 4.5716428756713867e-01 + <_> + + 0 -1 1560 1.0942210443317890e-02 + + 5.2410632371902466e-01 3.2845470309257507e-01 + <_> + + 0 -1 1561 -5.7841069065034389e-04 + + 5.3879290819168091e-01 4.1793689131736755e-01 + <_> + + 0 -1 1562 -2.0888620056211948e-03 + + 4.2926910519599915e-01 5.3017157316207886e-01 + <_> + + 0 -1 1563 3.2383969519287348e-03 + + 3.7923479080200195e-01 5.2207440137863159e-01 + <_> + + 0 -1 1564 4.9075027927756310e-03 + + 5.2372831106185913e-01 4.1267579793930054e-01 + <_> + + 0 -1 1565 -3.2277941703796387e-02 + + 1.9476559758186340e-01 4.9945020675659180e-01 + <_> + + 0 -1 1566 -8.9711230248212814e-03 + + 6.0112851858139038e-01 4.9290320277214050e-01 + <_> + + 0 -1 1567 1.5321089886128902e-02 + + 5.0097537040710449e-01 2.0398220419883728e-01 + <_> + + 0 -1 1568 2.0855569746345282e-03 + + 4.8621898889541626e-01 5.7216948270797729e-01 + <_> + + 0 -1 1569 5.0615021027624607e-03 + + 5.0002187490463257e-01 1.8018059432506561e-01 + <_> + + 0 -1 1570 -3.7174751050770283e-03 + + 5.5301171541213989e-01 4.8975929617881775e-01 + <_> + + 0 -1 1571 -1.2170500122010708e-02 + + 4.1786059737205505e-01 5.3837239742279053e-01 + <_> + + 0 -1 1572 4.6248398721218109e-03 + + 4.9971699714660645e-01 5.7613271474838257e-01 + <_> + + 0 -1 1573 -2.1040429419372231e-04 + + 5.3318071365356445e-01 4.0976810455322266e-01 + <_> + + 0 -1 1574 -1.4641780406236649e-02 + + 5.7559251785278320e-01 5.0517761707305908e-01 + <_> + + 0 -1 1575 3.3199489116668701e-03 + + 4.5769768953323364e-01 6.0318058729171753e-01 + <_> + + 0 -1 1576 3.7236879579722881e-03 + + 4.3803969025611877e-01 5.4158830642700195e-01 + <_> + + 0 -1 1577 8.2951161311939359e-04 + + 5.1630318164825439e-01 3.7022191286087036e-01 + <_> + + 0 -1 1578 -1.1408490128815174e-02 + + 6.0729467868804932e-01 4.8625651001930237e-01 + <_> + + 0 -1 1579 -4.5320121571421623e-03 + + 3.2924759387969971e-01 5.0889629125595093e-01 + <_> + + 0 -1 1580 5.1276017911732197e-03 + + 4.8297679424285889e-01 6.1227089166641235e-01 + <_> + + 0 -1 1581 9.8583158105611801e-03 + + 4.6606799960136414e-01 6.5561771392822266e-01 + <_> + + 0 -1 1582 3.6985918879508972e-02 + + 5.2048492431640625e-01 1.6904720664024353e-01 + <_> + + 0 -1 1583 4.6491161920130253e-03 + + 5.1673221588134766e-01 3.7252250313758850e-01 + <_> + + 0 -1 1584 -4.2664702050387859e-03 + + 6.4064931869506836e-01 4.9873429536819458e-01 + <_> + + 0 -1 1585 -4.7956590424291790e-04 + + 5.8972930908203125e-01 4.4648739695549011e-01 + <_> + + 0 -1 1586 3.6827160511165857e-03 + + 5.4415607452392578e-01 3.4726628661155701e-01 + <_> + + 0 -1 1587 -1.0059880092740059e-02 + + 2.1431629359722137e-01 5.0048297643661499e-01 + <_> + + 0 -1 1588 -3.0361840617842972e-04 + + 5.3864240646362305e-01 4.5903238654136658e-01 + <_> + + 0 -1 1589 -1.4545479789376259e-03 + + 5.7511842250823975e-01 4.4970950484275818e-01 + <_> + + 0 -1 1590 1.6515209572389722e-03 + + 5.4219377040863037e-01 4.2385208606719971e-01 + <_> + + 0 -1 1591 -7.8468639403581619e-03 + + 4.0779209136962891e-01 5.2581572532653809e-01 + <_> + + 0 -1 1592 -5.1259850151836872e-03 + + 4.2292758822441101e-01 5.4794532060623169e-01 + <_> + + 0 -1 1593 -3.6890961229801178e-02 + + 6.5963757038116455e-01 4.6746781468391418e-01 + <_> + + 0 -1 1594 2.4035639944486320e-04 + + 4.2511358857154846e-01 5.5732029676437378e-01 + <_> + + 0 -1 1595 -1.5150169929256663e-05 + + 5.2592468261718750e-01 4.0741148591041565e-01 + <_> + + 0 -1 1596 2.2108471021056175e-03 + + 4.6717229485511780e-01 5.8863520622253418e-01 + <_> + + 0 -1 1597 -1.1568620102480054e-03 + + 5.7110661268234253e-01 4.4871619343757629e-01 + <_> + + 0 -1 1598 4.9996292218565941e-03 + + 5.2641981840133667e-01 2.8983271121978760e-01 + <_> + + 0 -1 1599 -1.4656189596280456e-03 + + 3.8917380571365356e-01 5.1978719234466553e-01 + <_> + + 0 -1 1600 -1.1975039960816503e-03 + + 5.7958728075027466e-01 4.9279558658599854e-01 + <_> + + 0 -1 1601 -4.4954330660402775e-03 + + 2.3776030540466309e-01 5.0125551223754883e-01 + <_> + + 0 -1 1602 1.4997160178609192e-04 + + 4.8766261339187622e-01 5.6176078319549561e-01 + <_> + + 0 -1 1603 2.6391509454697371e-03 + + 5.1680880784988403e-01 3.7655091285705566e-01 + <_> + + 0 -1 1604 -2.9368131072260439e-04 + + 5.4466491937637329e-01 4.8746308684349060e-01 + <_> + + 0 -1 1605 1.4211760135367513e-03 + + 4.6878978610038757e-01 6.6913318634033203e-01 + <_> + + 0 -1 1606 7.9427637159824371e-02 + + 5.1934438943862915e-01 2.7329459786415100e-01 + <_> + + 0 -1 1607 7.9937502741813660e-02 + + 4.9717310070991516e-01 1.7820839583873749e-01 + <_> + + 0 -1 1608 1.1089259758591652e-02 + + 5.1659947633743286e-01 3.2094758749008179e-01 + <_> + + 0 -1 1609 1.6560709627810866e-04 + + 4.0584719181060791e-01 5.3072762489318848e-01 + <_> + + 0 -1 1610 -5.3354292176663876e-03 + + 3.4450569748878479e-01 5.1581299304962158e-01 + <_> + + 0 -1 1611 1.1287260567769408e-03 + + 4.5948630571365356e-01 6.0755330324172974e-01 + <_> + + 0 -1 1612 -2.1969219669699669e-02 + + 1.6804009675979614e-01 5.2285957336425781e-01 + <_> + + 0 -1 1613 -2.1775320055894554e-04 + + 3.8615968823432922e-01 5.2156728506088257e-01 + <_> + + 0 -1 1614 2.0200149447191507e-04 + + 5.5179792642593384e-01 4.3630391359329224e-01 + <_> + + 0 -1 1615 -2.1733149886131287e-02 + + 7.9994601011276245e-01 4.7898510098457336e-01 + <_> + + 0 -1 1616 -8.4399932529777288e-04 + + 4.0859758853912354e-01 5.3747731447219849e-01 + <_> + + 0 -1 1617 -4.3895249837078154e-04 + + 5.4704052209854126e-01 4.3661430478096008e-01 + <_> + + 0 -1 1618 1.5092400135472417e-03 + + 4.9889969825744629e-01 5.8421492576599121e-01 + <_> + + 0 -1 1619 -3.5547839943319559e-03 + + 6.7536902427673340e-01 4.7210058569908142e-01 + <_> + + 0 -1 1620 4.8191400128416717e-04 + + 5.4158538579940796e-01 4.3571090698242188e-01 + <_> + + 0 -1 1621 -6.0264398343861103e-03 + + 2.2585099935531616e-01 4.9918809533119202e-01 + <_> + + 0 -1 1622 -1.1668140068650246e-02 + + 6.2565547227859497e-01 4.9274989962577820e-01 + <_> + + 0 -1 1623 -2.8718370012938976e-03 + + 3.9477849006652832e-01 5.2458018064498901e-01 + <_> + + 0 -1 1624 1.7051169648766518e-02 + + 4.7525110840797424e-01 5.7942241430282593e-01 + <_> + + 0 -1 1625 -1.3352080248296261e-02 + + 6.0411047935485840e-01 4.5445358753204346e-01 + <_> + + 0 -1 1626 -3.9301801007241011e-04 + + 4.2582759261131287e-01 5.5449050664901733e-01 + <_> + + 0 -1 1627 3.0483349692076445e-03 + + 5.2334201335906982e-01 3.7802729010581970e-01 + <_> + + 0 -1 1628 -4.3579288758337498e-03 + + 6.3718891143798828e-01 4.8386740684509277e-01 + <_> + + 0 -1 1629 5.6661018170416355e-03 + + 5.3747057914733887e-01 4.1636660695075989e-01 + <_> + + 0 -1 1630 6.0677339206449687e-05 + + 4.6387958526611328e-01 5.3116250038146973e-01 + <_> + + 0 -1 1631 3.6738160997629166e-02 + + 4.6886560320854187e-01 6.4665240049362183e-01 + <_> + + 0 -1 1632 8.6528137326240540e-03 + + 5.2043187618255615e-01 2.1886579692363739e-01 + <_> + + 0 -1 1633 -1.5371359884738922e-01 + + 1.6303719580173492e-01 4.9588400125503540e-01 + <_> + + 0 -1 1634 -4.1560421232134104e-04 + + 5.7744592428207397e-01 4.6964588761329651e-01 + <_> + + 0 -1 1635 -1.2640169588848948e-03 + + 3.9771759510040283e-01 5.2171981334686279e-01 + <_> + + 0 -1 1636 -3.5473341122269630e-03 + + 6.0465282201766968e-01 4.8083150386810303e-01 + <_> + + 0 -1 1637 3.0019069527043030e-05 + + 3.9967238903045654e-01 5.2282011508941650e-01 + <_> + + 0 -1 1638 1.3113019522279501e-03 + + 4.7121581435203552e-01 5.7659977674484253e-01 + <_> + + 0 -1 1639 -1.3374709524214268e-03 + + 4.1095849871635437e-01 5.2531701326370239e-01 + <_> + + 0 -1 1640 2.0876709371805191e-02 + + 5.2029937505722046e-01 1.7579819262027740e-01 + <_> + + 0 -1 1641 -7.5497948564589024e-03 + + 6.5666097402572632e-01 4.6949750185012817e-01 + <_> + + 0 -1 1642 2.4188550189137459e-02 + + 5.1286739110946655e-01 3.3702209591865540e-01 + <_> + + 0 -1 1643 -2.9358828905969858e-03 + + 6.5807867050170898e-01 4.6945410966873169e-01 + <_> + + 0 -1 1644 5.7557929307222366e-02 + + 5.1464450359344482e-01 2.7752599120140076e-01 + <_> + + 0 -1 1645 -1.1343370424583554e-03 + + 3.8366019725799561e-01 5.1926672458648682e-01 + <_> + + 0 -1 1646 1.6816999763250351e-02 + + 5.0855928659439087e-01 6.1772608757019043e-01 + <_> + + 0 -1 1647 5.0535178743302822e-03 + + 5.1387631893157959e-01 3.6847919225692749e-01 + <_> + + 0 -1 1648 -4.5874710194766521e-03 + + 5.9896552562713623e-01 4.8352020978927612e-01 + <_> + + 0 -1 1649 1.6882460331544280e-03 + + 4.5094868540763855e-01 5.7230567932128906e-01 + <_> + + 0 -1 1650 -1.6554000321775675e-03 + + 3.4967708587646484e-01 5.2433192729949951e-01 + <_> + + 0 -1 1651 -1.9373800605535507e-02 + + 1.1205369979143143e-01 4.9687129259109497e-01 + <_> + + 0 -1 1652 1.0374450124800205e-02 + + 5.1481968164443970e-01 4.3952131271362305e-01 + <_> + + 0 -1 1653 1.4973050565458834e-04 + + 4.0849998593330383e-01 5.2698868513107300e-01 + <_> + + 0 -1 1654 -4.2981930077075958e-02 + + 6.3941049575805664e-01 5.0185042619705200e-01 + <_> + + 0 -1 1655 8.3065936341881752e-03 + + 4.7075539827346802e-01 6.6983532905578613e-01 + <_> + + 0 -1 1656 -4.1285790503025055e-03 + + 4.5413690805435181e-01 5.3236472606658936e-01 + <_> + + 0 -1 1657 1.7399420030415058e-03 + + 4.3339619040489197e-01 5.4398661851882935e-01 + <_> + + 0 -1 1658 1.1739750334527344e-04 + + 4.5796871185302734e-01 5.5434262752532959e-01 + <_> + + 0 -1 1659 1.8585780344437808e-04 + + 4.3246439099311829e-01 5.4267549514770508e-01 + <_> + + 0 -1 1660 5.5587692186236382e-03 + + 5.2572208642959595e-01 3.5506111383438110e-01 + <_> + + 0 -1 1661 -7.9851560294628143e-03 + + 6.0430181026458740e-01 4.6306359767913818e-01 + <_> + + 0 -1 1662 6.0594122624024749e-04 + + 4.5982548594474792e-01 5.5331951379776001e-01 + <_> + + 0 -1 1663 -2.2983040253166109e-04 + + 4.1307520866394043e-01 5.3224611282348633e-01 + <_> + + 0 -1 1664 4.3740210821852088e-04 + + 4.0430399775505066e-01 5.4092890024185181e-01 + <_> + + 0 -1 1665 2.9482020181603730e-04 + + 4.4949638843536377e-01 5.6288522481918335e-01 + <_> + + 0 -1 1666 1.0312659665942192e-02 + + 5.1775109767913818e-01 2.7043169736862183e-01 + <_> + + 0 -1 1667 -7.7241109684109688e-03 + + 1.9880190491676331e-01 4.9805539846420288e-01 + <_> + + 0 -1 1668 -4.6797208487987518e-03 + + 6.6447502374649048e-01 5.0182962417602539e-01 + <_> + + 0 -1 1669 -5.0755459815263748e-03 + + 3.8983049988746643e-01 5.1852691173553467e-01 + <_> + + 0 -1 1670 2.2479740437120199e-03 + + 4.8018088936805725e-01 5.6603360176086426e-01 + <_> + + 0 -1 1671 8.3327008178457618e-04 + + 5.2109199762344360e-01 3.9571881294250488e-01 + <_> + + 0 -1 1672 -4.1279330849647522e-02 + + 6.1545419692993164e-01 5.0070542097091675e-01 + <_> + + 0 -1 1673 -5.0930189900100231e-04 + + 3.9759421348571777e-01 5.2284038066864014e-01 + <_> + + 0 -1 1674 1.2568780221045017e-03 + + 4.9791380763053894e-01 5.9391832351684570e-01 + <_> + + 0 -1 1675 8.0048497766256332e-03 + + 4.9844971299171448e-01 1.6333660483360291e-01 + <_> + + 0 -1 1676 -1.1879300000146031e-03 + + 5.9049648046493530e-01 4.9426248669624329e-01 + <_> + + 0 -1 1677 6.1948952497914433e-04 + + 4.1995579004287720e-01 5.3287261724472046e-01 + <_> + + 0 -1 1678 6.6829859279096127e-03 + + 5.4186028242111206e-01 4.9058890342712402e-01 + <_> + + 0 -1 1679 -3.7062340416014194e-03 + + 3.7259390950202942e-01 5.1380002498626709e-01 + <_> + + 0 -1 1680 -3.9739411324262619e-02 + + 6.4789611101150513e-01 5.0503468513488770e-01 + <_> + + 0 -1 1681 1.4085009461268783e-03 + + 4.6823391318321228e-01 6.3778841495513916e-01 + <_> + + 0 -1 1682 3.9322688826359808e-04 + + 5.4585301876068115e-01 4.1504821181297302e-01 + <_> + + 0 -1 1683 -1.8979819724336267e-03 + + 3.6901599168777466e-01 5.1497042179107666e-01 + <_> + + 0 -1 1684 -1.3970440253615379e-02 + + 6.0505628585815430e-01 4.8113578557968140e-01 + <_> + + 0 -1 1685 -1.0100819915533066e-01 + + 2.0170800387859344e-01 4.9923619627952576e-01 + <_> + + 0 -1 1686 -1.7346920445561409e-02 + + 5.7131487131118774e-01 4.8994860053062439e-01 + <_> + + 0 -1 1687 1.5619759506080300e-04 + + 4.2153888940811157e-01 5.3926420211791992e-01 + <_> + + 0 -1 1688 1.3438929617404938e-01 + + 5.1361519098281860e-01 3.7676128745079041e-01 + <_> + + 0 -1 1689 -2.4582240730524063e-02 + + 7.0273578166961670e-01 4.7479069232940674e-01 + <_> + + 0 -1 1690 -3.8553720805794001e-03 + + 4.3174090981483459e-01 5.4277169704437256e-01 + <_> + + 0 -1 1691 -2.3165249731391668e-03 + + 5.9426987171173096e-01 4.6186479926109314e-01 + <_> + + 0 -1 1692 -4.8518120311200619e-03 + + 6.1915689706802368e-01 4.8848950862884521e-01 + <_> + + 0 -1 1693 2.4699938949197531e-03 + + 5.2566647529602051e-01 4.0171998739242554e-01 + <_> + + 0 -1 1694 4.5496959239244461e-02 + + 5.2378678321838379e-01 2.6857739686965942e-01 + <_> + + 0 -1 1695 -2.0319599658250809e-02 + + 2.1304459869861603e-01 4.9797388911247253e-01 + <_> + + 0 -1 1696 2.6994998916052282e-04 + + 4.8140418529510498e-01 5.5431222915649414e-01 + <_> + + 0 -1 1697 -1.8232699949294329e-03 + + 6.4825797080993652e-01 4.7099891304969788e-01 + <_> + + 0 -1 1698 -6.3015790656208992e-03 + + 4.5819279551506042e-01 5.3062361478805542e-01 + <_> + + 0 -1 1699 -2.4139499873854220e-04 + + 5.2320867776870728e-01 4.0517631173133850e-01 + <_> + + 0 -1 1700 -1.0330369696021080e-03 + + 5.5562019348144531e-01 4.7891938686370850e-01 + <_> + + 0 -1 1701 1.8041160365100950e-04 + + 5.2294427156448364e-01 4.0118101239204407e-01 + <_> + + 0 -1 1702 -6.1407860368490219e-02 + + 6.2986820936203003e-01 5.0107032060623169e-01 + <_> + + 0 -1 1703 -6.9543913006782532e-02 + + 7.2282809019088745e-01 4.7731840610504150e-01 + <_> + + 0 -1 1704 -7.0542663335800171e-02 + + 2.2695130109786987e-01 5.1825290918350220e-01 + <_> + + 0 -1 1705 2.4423799477517605e-03 + + 5.2370971441268921e-01 4.0981510281562805e-01 + <_> + + 0 -1 1706 1.5494349645450711e-03 + + 4.7737509012222290e-01 5.4680430889129639e-01 + <_> + + 0 -1 1707 -2.3914219811558723e-02 + + 7.1469759941101074e-01 4.7838249802589417e-01 + <_> + + 0 -1 1708 -1.2453690171241760e-02 + + 2.6352968811988831e-01 5.2411228418350220e-01 + <_> + + 0 -1 1709 -2.0760179904755205e-04 + + 3.6237570643424988e-01 5.1136088371276855e-01 + <_> + + 0 -1 1710 2.9781080229440704e-05 + + 4.7059321403503418e-01 5.4328018426895142e-01 + <_> + 211 + 1.0474919891357422e+02 + + <_> + + 0 -1 1711 1.1772749945521355e-02 + + 3.8605189323425293e-01 6.4211672544479370e-01 + <_> + + 0 -1 1712 2.7037570253014565e-02 + + 4.3856549263000488e-01 6.7540389299392700e-01 + <_> + + 0 -1 1713 -3.6419500247575343e-05 + + 5.4871010780334473e-01 3.4233158826828003e-01 + <_> + + 0 -1 1714 1.9995409529656172e-03 + + 3.2305321097373962e-01 5.4003179073333740e-01 + <_> + + 0 -1 1715 4.5278300531208515e-03 + + 5.0916397571563721e-01 2.9350438714027405e-01 + <_> + + 0 -1 1716 4.7890920541249216e-04 + + 4.1781538724899292e-01 5.3440642356872559e-01 + <_> + + 0 -1 1717 1.1720920447260141e-03 + + 2.8991821408271790e-01 5.1320707798004150e-01 + <_> + + 0 -1 1718 9.5305702416226268e-04 + + 4.2801249027252197e-01 5.5608451366424561e-01 + <_> + + 0 -1 1719 1.5099150004971307e-05 + + 4.0448719263076782e-01 5.4047602415084839e-01 + <_> + + 0 -1 1720 -6.0817901976406574e-04 + + 4.2717689275741577e-01 5.5034661293029785e-01 + <_> + + 0 -1 1721 3.3224520739167929e-03 + + 3.9627239108085632e-01 5.3697347640991211e-01 + <_> + + 0 -1 1722 -1.1037490330636501e-03 + + 4.7271779179573059e-01 5.2377498149871826e-01 + <_> + + 0 -1 1723 -1.4350269921123981e-03 + + 5.6030082702636719e-01 4.2235091328620911e-01 + <_> + + 0 -1 1724 2.0767399109899998e-03 + + 5.2259171009063721e-01 4.7327259182929993e-01 + <_> + + 0 -1 1725 -1.6412809782195836e-04 + + 3.9990758895874023e-01 5.4327398538589478e-01 + <_> + + 0 -1 1726 8.8302437216043472e-03 + + 4.6783858537673950e-01 6.0273271799087524e-01 + <_> + + 0 -1 1727 -1.0552070103585720e-02 + + 3.4939670562744141e-01 5.2139747142791748e-01 + <_> + + 0 -1 1728 -2.2731600329279900e-03 + + 6.1858189105987549e-01 4.7490629553794861e-01 + <_> + + 0 -1 1729 -8.4786332445219159e-04 + + 5.2853411436080933e-01 3.8434821367263794e-01 + <_> + + 0 -1 1730 1.2081359745934606e-03 + + 5.3606408834457397e-01 3.4473359584808350e-01 + <_> + + 0 -1 1731 2.6512730401009321e-03 + + 4.5582920312881470e-01 6.1939620971679688e-01 + <_> + + 0 -1 1732 -1.1012479662895203e-03 + + 3.6802300810813904e-01 5.3276282548904419e-01 + <_> + + 0 -1 1733 4.9561518244445324e-04 + + 3.9605951309204102e-01 5.2749407291412354e-01 + <_> + + 0 -1 1734 -4.3901771306991577e-02 + + 7.0204448699951172e-01 4.9928390979766846e-01 + <_> + + 0 -1 1735 3.4690350294113159e-02 + + 5.0491642951965332e-01 2.7666029334068298e-01 + <_> + + 0 -1 1736 -2.7442190330475569e-03 + + 2.6726329326629639e-01 5.2749711275100708e-01 + <_> + + 0 -1 1737 3.3316588960587978e-03 + + 4.5794829726219177e-01 6.0011017322540283e-01 + <_> + + 0 -1 1738 -2.0044570788741112e-02 + + 3.1715941429138184e-01 5.2357178926467896e-01 + <_> + + 0 -1 1739 1.3492030557245016e-03 + + 5.2653628587722778e-01 4.0343248844146729e-01 + <_> + + 0 -1 1740 2.9702018946409225e-03 + + 5.3324568271636963e-01 4.5719841122627258e-01 + <_> + + 0 -1 1741 6.3039981760084629e-03 + + 4.5933109521865845e-01 6.0346359014511108e-01 + <_> + + 0 -1 1742 -1.2936590239405632e-02 + + 4.4379639625549316e-01 5.3729712963104248e-01 + <_> + + 0 -1 1743 4.0148729458451271e-03 + + 4.6803238987922668e-01 6.4378339052200317e-01 + <_> + + 0 -1 1744 -2.6401679497212172e-03 + + 3.7096318602561951e-01 5.3143328428268433e-01 + <_> + + 0 -1 1745 1.3918439857661724e-02 + + 4.7235551476478577e-01 7.1308088302612305e-01 + <_> + + 0 -1 1746 -4.5087869511917233e-04 + + 4.4923940300941467e-01 5.3704041242599487e-01 + <_> + + 0 -1 1747 2.5384349282830954e-04 + + 4.4068640470504761e-01 5.5144029855728149e-01 + <_> + + 0 -1 1748 2.2710000630468130e-03 + + 4.6824169158935547e-01 5.9679841995239258e-01 + <_> + + 0 -1 1749 2.4120779708027840e-03 + + 5.0793921947479248e-01 3.0185988545417786e-01 + <_> + + 0 -1 1750 -3.6025670851813629e-05 + + 5.6010371446609497e-01 4.4710969924926758e-01 + <_> + + 0 -1 1751 -7.4905529618263245e-03 + + 2.2075350582599640e-01 4.9899441003799438e-01 + <_> + + 0 -1 1752 -1.7513120546936989e-02 + + 6.5312159061431885e-01 5.0176489353179932e-01 + <_> + + 0 -1 1753 1.4281630516052246e-01 + + 4.9679630994796753e-01 1.4820620417594910e-01 + <_> + + 0 -1 1754 5.5345268920063972e-03 + + 4.8989468812942505e-01 5.9542238712310791e-01 + <_> + + 0 -1 1755 -9.6323591424152255e-04 + + 3.9271169900894165e-01 5.1960742473602295e-01 + <_> + + 0 -1 1756 -2.0370010752230883e-03 + + 5.6133252382278442e-01 4.8848581314086914e-01 + <_> + + 0 -1 1757 1.6614829655736685e-03 + + 4.4728800654411316e-01 5.5788809061050415e-01 + <_> + + 0 -1 1758 -3.1188090797513723e-03 + + 3.8405328989028931e-01 5.3974777460098267e-01 + <_> + + 0 -1 1759 -6.4000617712736130e-03 + + 5.8439838886260986e-01 4.5332181453704834e-01 + <_> + + 0 -1 1760 3.1319601112045348e-04 + + 5.4392218589782715e-01 4.2347279191017151e-01 + <_> + + 0 -1 1761 -1.8222099170088768e-02 + + 1.2884649634361267e-01 4.9584048986434937e-01 + <_> + + 0 -1 1762 8.7969247251749039e-03 + + 4.9512979388237000e-01 7.1534800529479980e-01 + <_> + + 0 -1 1763 -4.2395070195198059e-03 + + 3.9465999603271484e-01 5.1949369907379150e-01 + <_> + + 0 -1 1764 9.7086271271109581e-03 + + 4.8975038528442383e-01 6.0649001598358154e-01 + <_> + + 0 -1 1765 -3.9934171363711357e-03 + + 3.2454401254653931e-01 5.0608289241790771e-01 + <_> + + 0 -1 1766 -1.6785059124231339e-02 + + 1.5819530189037323e-01 5.2037787437438965e-01 + <_> + + 0 -1 1767 1.8272090703248978e-02 + + 4.6809351444244385e-01 6.6269791126251221e-01 + <_> + + 0 -1 1768 5.6872838176786900e-03 + + 5.2116978168487549e-01 3.5121849179267883e-01 + <_> + + 0 -1 1769 -1.0739039862528443e-03 + + 5.7683861255645752e-01 4.5298451185226440e-01 + <_> + + 0 -1 1770 -3.7093870341777802e-03 + + 4.5077630877494812e-01 5.3135812282562256e-01 + <_> + + 0 -1 1771 -2.1110709349159151e-04 + + 5.4608201980590820e-01 4.3333768844604492e-01 + <_> + + 0 -1 1772 1.0670139454305172e-03 + + 5.3718560934066772e-01 4.0783908963203430e-01 + <_> + + 0 -1 1773 3.5943021066486835e-03 + + 4.4712871313095093e-01 5.6438362598419189e-01 + <_> + + 0 -1 1774 -5.1776031032204628e-03 + + 4.4993931055068970e-01 5.2803301811218262e-01 + <_> + + 0 -1 1775 -2.5414369883947074e-04 + + 5.5161732435226440e-01 4.4077080488204956e-01 + <_> + + 0 -1 1776 6.3522560521960258e-03 + + 5.1941901445388794e-01 2.4652279913425446e-01 + <_> + + 0 -1 1777 -4.4205080484971404e-04 + + 3.8307058811187744e-01 5.1396822929382324e-01 + <_> + + 0 -1 1778 7.4488727841526270e-04 + + 4.8910909891128540e-01 5.9747868776321411e-01 + <_> + + 0 -1 1779 -3.5116379149258137e-03 + + 7.4136817455291748e-01 4.7687649726867676e-01 + <_> + + 0 -1 1780 -1.2540910392999649e-02 + + 3.6488190293312073e-01 5.2528268098831177e-01 + <_> + + 0 -1 1781 9.4931852072477341e-03 + + 5.1004928350448608e-01 3.6295869946479797e-01 + <_> + + 0 -1 1782 1.2961150147020817e-02 + + 5.2324420213699341e-01 4.3335610628128052e-01 + <_> + + 0 -1 1783 4.7209449112415314e-03 + + 4.6481490135192871e-01 6.3310527801513672e-01 + <_> + + 0 -1 1784 -2.3119079414755106e-03 + + 5.9303098917007446e-01 4.5310580730438232e-01 + <_> + + 0 -1 1785 -2.8262299019843340e-03 + + 3.8704779744148254e-01 5.2571010589599609e-01 + <_> + + 0 -1 1786 -1.4311339473351836e-03 + + 5.5225032567977905e-01 4.5618548989295959e-01 + <_> + + 0 -1 1787 1.9378310535103083e-03 + + 4.5462208986282349e-01 5.7369667291641235e-01 + <_> + + 0 -1 1788 2.6343559147790074e-04 + + 5.3457391262054443e-01 4.5718750357627869e-01 + <_> + + 0 -1 1789 7.8257522545754910e-04 + + 3.9678159356117249e-01 5.2201879024505615e-01 + <_> + + 0 -1 1790 -1.9550440832972527e-02 + + 2.8296428918838501e-01 5.2435082197189331e-01 + <_> + + 0 -1 1791 4.3914958951063454e-04 + + 4.5900669693946838e-01 5.8990901708602905e-01 + <_> + + 0 -1 1792 2.1452000364661217e-02 + + 5.2314108610153198e-01 2.8553789854049683e-01 + <_> + + 0 -1 1793 5.8973580598831177e-04 + + 4.3972569704055786e-01 5.5064219236373901e-01 + <_> + + 0 -1 1794 -2.6157610118389130e-02 + + 3.1350791454315186e-01 5.1891750097274780e-01 + <_> + + 0 -1 1795 -1.3959860429167747e-02 + + 3.2132729887962341e-01 5.0407177209854126e-01 + <_> + + 0 -1 1796 -6.3699018210172653e-03 + + 6.3875448703765869e-01 4.8495069146156311e-01 + <_> + + 0 -1 1797 -8.5613820701837540e-03 + + 2.7591320872306824e-01 5.0320190191268921e-01 + <_> + + 0 -1 1798 9.6622901037335396e-04 + + 4.6856409311294556e-01 5.8348792791366577e-01 + <_> + + 0 -1 1799 7.6550268568098545e-04 + + 5.1752072572708130e-01 3.8964220881462097e-01 + <_> + + 0 -1 1800 -8.1833340227603912e-03 + + 2.0691369473934174e-01 5.2081221342086792e-01 + <_> + + 0 -1 1801 -9.3976939097046852e-03 + + 6.1340910196304321e-01 4.6412229537963867e-01 + <_> + + 0 -1 1802 4.8028980381786823e-03 + + 5.4541081190109253e-01 4.3952199816703796e-01 + <_> + + 0 -1 1803 -3.5680569708347321e-03 + + 6.3444852828979492e-01 4.6810939908027649e-01 + <_> + + 0 -1 1804 4.0733120404183865e-03 + + 5.2926832437515259e-01 4.0156200528144836e-01 + <_> + + 0 -1 1805 1.2568129459396005e-03 + + 4.3929880857467651e-01 5.4528248310089111e-01 + <_> + + 0 -1 1806 -2.9065010603517294e-03 + + 5.8988320827484131e-01 4.8633798956871033e-01 + <_> + + 0 -1 1807 -2.4409340694546700e-03 + + 4.0693649649620056e-01 5.2474218606948853e-01 + <_> + + 0 -1 1808 2.4830700829625130e-02 + + 5.1827257871627808e-01 3.6825248599052429e-01 + <_> + + 0 -1 1809 -4.8854008316993713e-02 + + 1.3075779378414154e-01 4.9612811207771301e-01 + <_> + + 0 -1 1810 -1.6110379947349429e-03 + + 6.4210057258605957e-01 4.8726621270179749e-01 + <_> + + 0 -1 1811 -9.7009479999542236e-02 + + 4.7769349068403244e-02 4.9509888887405396e-01 + <_> + + 0 -1 1812 1.1209240183234215e-03 + + 4.6162670850753784e-01 5.3547459840774536e-01 + <_> + + 0 -1 1813 -1.3064090162515640e-03 + + 6.2618541717529297e-01 4.6388059854507446e-01 + <_> + + 0 -1 1814 4.5771620352752507e-04 + + 5.3844177722930908e-01 4.6466401219367981e-01 + <_> + + 0 -1 1815 -6.3149951165542006e-04 + + 3.8040471076965332e-01 5.1302570104598999e-01 + <_> + + 0 -1 1816 1.4505970466416329e-04 + + 4.5543101429939270e-01 5.6644618511199951e-01 + <_> + + 0 -1 1817 -1.6474550589919090e-02 + + 6.5969580411911011e-01 4.7158598899841309e-01 + <_> + + 0 -1 1818 1.3369579799473286e-02 + + 5.1954662799835205e-01 3.0359649658203125e-01 + <_> + + 0 -1 1819 1.0271780047332868e-04 + + 5.2291762828826904e-01 4.1070660948753357e-01 + <_> + + 0 -1 1820 -5.5311559699475765e-03 + + 6.3528877496719360e-01 4.9609071016311646e-01 + <_> + + 0 -1 1821 -2.6187049224972725e-03 + + 3.8245460391044617e-01 5.1409840583801270e-01 + <_> + + 0 -1 1822 5.0834268331527710e-03 + + 4.9504399299621582e-01 6.2208187580108643e-01 + <_> + + 0 -1 1823 7.9818159341812134e-02 + + 4.9523359537124634e-01 1.3224759697914124e-01 + <_> + + 0 -1 1824 -9.9226586520671844e-02 + + 7.5427287817001343e-01 5.0084167718887329e-01 + <_> + + 0 -1 1825 -6.5174017800018191e-04 + + 3.6993029713630676e-01 5.1301211118698120e-01 + <_> + + 0 -1 1826 -1.8996849656105042e-02 + + 6.6891789436340332e-01 4.9212029576301575e-01 + <_> + + 0 -1 1827 1.7346899956464767e-02 + + 4.9833008646965027e-01 1.8591980636119843e-01 + <_> + + 0 -1 1828 5.5082101607695222e-04 + + 4.5744240283966064e-01 5.5221217870712280e-01 + <_> + + 0 -1 1829 2.0056050270795822e-03 + + 5.1317447423934937e-01 3.8564699888229370e-01 + <_> + + 0 -1 1830 -7.7688191086053848e-03 + + 4.3617001175880432e-01 5.4343092441558838e-01 + <_> + + 0 -1 1831 5.0878278911113739e-02 + + 4.6827208995819092e-01 6.8406397104263306e-01 + <_> + + 0 -1 1832 -2.2901780903339386e-03 + + 4.3292450904846191e-01 5.3060990571975708e-01 + <_> + + 0 -1 1833 -1.5715380141045898e-04 + + 5.3700572252273560e-01 4.3781641125679016e-01 + <_> + + 0 -1 1834 1.0519240051507950e-01 + + 5.1372742652893066e-01 6.7361466586589813e-02 + <_> + + 0 -1 1835 2.7198919560760260e-03 + + 4.1120609641075134e-01 5.2556651830673218e-01 + <_> + + 0 -1 1836 4.8337779939174652e-02 + + 5.4046237468719482e-01 4.4389671087265015e-01 + <_> + + 0 -1 1837 9.5703761326149106e-04 + + 4.3559691309928894e-01 5.3995108604431152e-01 + <_> + + 0 -1 1838 -2.5371259078383446e-02 + + 5.9951752424240112e-01 5.0310248136520386e-01 + <_> + + 0 -1 1839 5.2457951009273529e-02 + + 4.9502879381179810e-01 1.3983510434627533e-01 + <_> + + 0 -1 1840 -1.2365629896521568e-02 + + 6.3972991704940796e-01 4.9641060829162598e-01 + <_> + + 0 -1 1841 -1.4589719474315643e-01 + + 1.0016699880361557e-01 4.9463221430778503e-01 + <_> + + 0 -1 1842 -1.5908600762486458e-02 + + 3.3123299479484558e-01 5.2083408832550049e-01 + <_> + + 0 -1 1843 3.9486068999394774e-04 + + 4.4063639640808105e-01 5.4261028766632080e-01 + <_> + + 0 -1 1844 -5.2454001270234585e-03 + + 2.7995899319648743e-01 5.1899671554565430e-01 + <_> + + 0 -1 1845 -5.0421799533069134e-03 + + 6.9875800609588623e-01 4.7521421313285828e-01 + <_> + + 0 -1 1846 2.9812189750373363e-03 + + 4.9832889437675476e-01 6.3074797391891479e-01 + <_> + + 0 -1 1847 -7.2884308174252510e-03 + + 2.9823330044746399e-01 5.0268697738647461e-01 + <_> + + 0 -1 1848 1.5094350092113018e-03 + + 5.3084421157836914e-01 3.8329708576202393e-01 + <_> + + 0 -1 1849 -9.3340799212455750e-03 + + 2.0379640161991119e-01 4.9698171019554138e-01 + <_> + + 0 -1 1850 2.8667140752077103e-02 + + 5.0256967544555664e-01 6.9280272722244263e-01 + <_> + + 0 -1 1851 1.7019680142402649e-01 + + 4.9600529670715332e-01 1.4764429628849030e-01 + <_> + + 0 -1 1852 -3.2614478841423988e-03 + + 5.6030637025833130e-01 4.8260560631752014e-01 + <_> + + 0 -1 1853 5.5769277969375253e-04 + + 5.2055621147155762e-01 4.1296330094337463e-01 + <_> + + 0 -1 1854 3.6258339881896973e-01 + + 5.2216529846191406e-01 3.7686121463775635e-01 + <_> + + 0 -1 1855 -1.1615130119025707e-02 + + 6.0226827859878540e-01 4.6374899148941040e-01 + <_> + + 0 -1 1856 -4.0795197710394859e-03 + + 4.0704470872879028e-01 5.3374791145324707e-01 + <_> + + 0 -1 1857 5.7204300537705421e-04 + + 4.6018350124359131e-01 5.9003931283950806e-01 + <_> + + 0 -1 1858 6.7543348995968699e-04 + + 5.3982520103454590e-01 4.3454289436340332e-01 + <_> + + 0 -1 1859 6.3295697327703238e-04 + + 5.2015632390975952e-01 4.0513589978218079e-01 + <_> + + 0 -1 1860 1.2435320531949401e-03 + + 4.6423879265785217e-01 5.5474412441253662e-01 + <_> + + 0 -1 1861 -4.7363857738673687e-03 + + 6.1985671520233154e-01 4.6725520491600037e-01 + <_> + + 0 -1 1862 -6.4658462069928646e-03 + + 6.8373328447341919e-01 5.0190007686614990e-01 + <_> + + 0 -1 1863 3.5017321351915598e-04 + + 4.3448030948638916e-01 5.3636229038238525e-01 + <_> + + 0 -1 1864 1.5754920605104417e-04 + + 4.7600790858268738e-01 5.7320207357406616e-01 + <_> + + 0 -1 1865 9.9774366244673729e-03 + + 5.0909858942031860e-01 3.6350399255752563e-01 + <_> + + 0 -1 1866 -4.1464529931545258e-04 + + 5.5700647830963135e-01 4.5938020944595337e-01 + <_> + + 0 -1 1867 -3.5888899583369493e-04 + + 5.3568458557128906e-01 4.3391349911689758e-01 + <_> + + 0 -1 1868 4.0463250479660928e-04 + + 4.4398030638694763e-01 5.4367768764495850e-01 + <_> + + 0 -1 1869 -8.2184787606820464e-04 + + 4.0422949194908142e-01 5.1762992143630981e-01 + <_> + + 0 -1 1870 5.9467419050633907e-03 + + 4.9276518821716309e-01 5.6337797641754150e-01 + <_> + + 0 -1 1871 -2.1753389388322830e-02 + + 8.0062937736511230e-01 4.8008409142494202e-01 + <_> + + 0 -1 1872 -1.4540379866957664e-02 + + 3.9460548758506775e-01 5.1822227239608765e-01 + <_> + + 0 -1 1873 -4.0510769933462143e-02 + + 2.1324990317225456e-02 4.9357929825782776e-01 + <_> + + 0 -1 1874 -5.8458268176764250e-04 + + 4.0127959847450256e-01 5.3140252828598022e-01 + <_> + + 0 -1 1875 5.5151800625026226e-03 + + 4.6424189209938049e-01 5.8962607383728027e-01 + <_> + + 0 -1 1876 -6.0626221820712090e-03 + + 6.5021592378616333e-01 5.0164777040481567e-01 + <_> + + 0 -1 1877 9.4535842537879944e-02 + + 5.2647089958190918e-01 4.1268271207809448e-01 + <_> + + 0 -1 1878 4.7315051779150963e-03 + + 4.8791998624801636e-01 5.8924478292465210e-01 + <_> + + 0 -1 1879 -5.2571471314877272e-04 + + 3.9172801375389099e-01 5.1894128322601318e-01 + <_> + + 0 -1 1880 -2.5464049540460110e-03 + + 5.8375990390777588e-01 4.9857059121131897e-01 + <_> + + 0 -1 1881 -2.6075689122080803e-02 + + 1.2619839608669281e-01 4.9558219313621521e-01 + <_> + + 0 -1 1882 -5.4779709316790104e-03 + + 5.7225137948989868e-01 5.0102657079696655e-01 + <_> + + 0 -1 1883 5.1337741315364838e-03 + + 5.2732622623443604e-01 4.2263761162757874e-01 + <_> + + 0 -1 1884 4.7944980906322598e-04 + + 4.4500669836997986e-01 5.8195871114730835e-01 + <_> + + 0 -1 1885 -2.1114079281687737e-03 + + 5.7576531171798706e-01 4.5117148756980896e-01 + <_> + + 0 -1 1886 -1.3179990462958813e-02 + + 1.8843810260295868e-01 5.1607340574264526e-01 + <_> + + 0 -1 1887 -4.7968099825084209e-03 + + 6.5897899866104126e-01 4.7361189126968384e-01 + <_> + + 0 -1 1888 6.7483168095350266e-03 + + 5.2594298124313354e-01 3.3563950657844543e-01 + <_> + + 0 -1 1889 1.4623369788751006e-03 + + 5.3552711009979248e-01 4.2640921473503113e-01 + <_> + + 0 -1 1890 4.7645159065723419e-03 + + 5.0344067811965942e-01 5.7868278026580811e-01 + <_> + + 0 -1 1891 6.8066660314798355e-03 + + 4.7566050291061401e-01 6.6778290271759033e-01 + <_> + + 0 -1 1892 3.6608621012419462e-03 + + 5.3696119785308838e-01 4.3115469813346863e-01 + <_> + + 0 -1 1893 2.1449640393257141e-02 + + 4.9686419963836670e-01 1.8888160586357117e-01 + <_> + + 0 -1 1894 4.1678901761770248e-03 + + 4.9307331442832947e-01 5.8153688907623291e-01 + <_> + + 0 -1 1895 8.6467564105987549e-03 + + 5.2052050828933716e-01 4.1325950622558594e-01 + <_> + + 0 -1 1896 -3.6114078829996288e-04 + + 5.4835551977157593e-01 4.8009279370307922e-01 + <_> + + 0 -1 1897 1.0808729566633701e-03 + + 4.6899020671844482e-01 6.0414212942123413e-01 + <_> + + 0 -1 1898 5.7719959877431393e-03 + + 5.1711422204971313e-01 3.0532771348953247e-01 + <_> + + 0 -1 1899 1.5720770461484790e-03 + + 5.2199780941009521e-01 4.1788038611412048e-01 + <_> + + 0 -1 1900 -1.9307859474793077e-03 + + 5.8603698015213013e-01 4.8129200935363770e-01 + <_> + + 0 -1 1901 -7.8926272690296173e-03 + + 1.7492769658565521e-01 4.9717339873313904e-01 + <_> + + 0 -1 1902 -2.2224679123610258e-03 + + 4.3425890803337097e-01 5.2128481864929199e-01 + <_> + + 0 -1 1903 1.9011989934369922e-03 + + 4.7651869058609009e-01 6.8920552730560303e-01 + <_> + + 0 -1 1904 2.7576119173318148e-03 + + 5.2621912956237793e-01 4.3374860286712646e-01 + <_> + + 0 -1 1905 5.1787449046969414e-03 + + 4.8040691018104553e-01 7.8437292575836182e-01 + <_> + + 0 -1 1906 -9.0273341629654169e-04 + + 4.1208469867706299e-01 5.3534239530563354e-01 + <_> + + 0 -1 1907 5.1797959022223949e-03 + + 4.7403728961944580e-01 6.4259600639343262e-01 + <_> + + 0 -1 1908 -1.0114000178873539e-02 + + 2.4687920510768890e-01 5.1750177145004272e-01 + <_> + + 0 -1 1909 -1.8617060035467148e-02 + + 5.7562941312789917e-01 4.6289789676666260e-01 + <_> + + 0 -1 1910 5.9225959703326225e-03 + + 5.1696258783340454e-01 3.2142710685729980e-01 + <_> + + 0 -1 1911 -6.2945079989731312e-03 + + 3.8720148801803589e-01 5.1416367292404175e-01 + <_> + + 0 -1 1912 6.5353019163012505e-03 + + 4.8530489206314087e-01 6.3104897737503052e-01 + <_> + + 0 -1 1913 1.0878399480134249e-03 + + 5.1173150539398193e-01 3.7232589721679688e-01 + <_> + + 0 -1 1914 -2.2542240098118782e-02 + + 5.6927400827407837e-01 4.8871129751205444e-01 + <_> + + 0 -1 1915 -3.0065660830587149e-03 + + 2.5560128688812256e-01 5.0039929151535034e-01 + <_> + + 0 -1 1916 7.4741272255778313e-03 + + 4.8108729720115662e-01 5.6759268045425415e-01 + <_> + + 0 -1 1917 2.6162320747971535e-02 + + 4.9711948633193970e-01 1.7772370576858521e-01 + <_> + + 0 -1 1918 9.4352738233283162e-04 + + 4.9400109052658081e-01 5.4912507534027100e-01 + <_> + + 0 -1 1919 3.3363241702318192e-02 + + 5.0076121091842651e-01 2.7907240390777588e-01 + <_> + + 0 -1 1920 -1.5118650160729885e-02 + + 7.0595788955688477e-01 4.9730318784713745e-01 + <_> + + 0 -1 1921 9.8648946732282639e-04 + + 5.1286202669143677e-01 3.7767618894577026e-01 + <_> + 213 + 1.0576110076904297e+02 + + <_> + + 0 -1 1922 -9.5150798559188843e-02 + + 6.4707571268081665e-01 4.0172868967056274e-01 + <_> + + 0 -1 1923 6.2702340073883533e-03 + + 3.9998221397399902e-01 5.7464492321014404e-01 + <_> + + 0 -1 1924 3.0018089455552399e-04 + + 3.5587701201438904e-01 5.5388098955154419e-01 + <_> + + 0 -1 1925 1.1757409665733576e-03 + + 4.2565348744392395e-01 5.3826177120208740e-01 + <_> + + 0 -1 1926 4.4235268433112651e-05 + + 3.6829081177711487e-01 5.5899268388748169e-01 + <_> + + 0 -1 1927 -2.9936920327600092e-05 + + 5.4524701833724976e-01 4.0203678607940674e-01 + <_> + + 0 -1 1928 3.0073199886828661e-03 + + 5.2390581369400024e-01 3.3178439736366272e-01 + <_> + + 0 -1 1929 -1.0513889603316784e-02 + + 4.3206891417503357e-01 5.3079837560653687e-01 + <_> + + 0 -1 1930 8.3476826548576355e-03 + + 4.5046371221542358e-01 6.4532989263534546e-01 + <_> + + 0 -1 1931 -3.1492270063608885e-03 + + 4.3134251236915588e-01 5.3705251216888428e-01 + <_> + + 0 -1 1932 -1.4435649973165710e-05 + + 5.3266030550003052e-01 3.8179719448089600e-01 + <_> + + 0 -1 1933 -4.2855090578086674e-04 + + 4.3051639199256897e-01 5.3820097446441650e-01 + <_> + + 0 -1 1934 1.5062429883982986e-04 + + 4.2359709739685059e-01 5.5449652671813965e-01 + <_> + + 0 -1 1935 7.1559831500053406e-02 + + 5.3030598163604736e-01 2.6788029074668884e-01 + <_> + + 0 -1 1936 8.4095180500298738e-04 + + 3.5571089386940002e-01 5.2054339647293091e-01 + <_> + + 0 -1 1937 6.2986500561237335e-02 + + 5.2253627777099609e-01 2.8613761067390442e-01 + <_> + + 0 -1 1938 -3.3798629883676767e-03 + + 3.6241859197616577e-01 5.2016979455947876e-01 + <_> + + 0 -1 1939 -1.1810739670181647e-04 + + 5.4744768142700195e-01 3.9598938822746277e-01 + <_> + + 0 -1 1940 -5.4505601292476058e-04 + + 3.7404221296310425e-01 5.2157157659530640e-01 + <_> + + 0 -1 1941 -1.8454910023137927e-03 + + 5.8930522203445435e-01 4.5844489336013794e-01 + <_> + + 0 -1 1942 -4.3832371011376381e-04 + + 4.0845820307731628e-01 5.3853511810302734e-01 + <_> + + 0 -1 1943 -2.4000830017030239e-03 + + 3.7774550914764404e-01 5.2935802936553955e-01 + <_> + + 0 -1 1944 -9.8795741796493530e-02 + + 2.9636120796203613e-01 5.0700891017913818e-01 + <_> + + 0 -1 1945 3.1798239797353745e-03 + + 4.8776328563690186e-01 6.7264437675476074e-01 + <_> + + 0 -1 1946 3.2406419632025063e-04 + + 4.3669110536575317e-01 5.5611097812652588e-01 + <_> + + 0 -1 1947 -3.2547250390052795e-02 + + 3.1281578540802002e-01 5.3086161613464355e-01 + <_> + + 0 -1 1948 -7.7561130747199059e-03 + + 6.5602248907089233e-01 4.6398720145225525e-01 + <_> + + 0 -1 1949 1.6027249395847321e-02 + + 5.1726800203323364e-01 3.1418979167938232e-01 + <_> + + 0 -1 1950 7.1002350523485802e-06 + + 4.0844461321830750e-01 5.3362947702407837e-01 + <_> + + 0 -1 1951 7.3422808200120926e-03 + + 4.9669221043586731e-01 6.6034650802612305e-01 + <_> + + 0 -1 1952 -1.6970280557870865e-03 + + 5.9082370996475220e-01 4.5001828670501709e-01 + <_> + + 0 -1 1953 2.4118260480463505e-03 + + 5.3151607513427734e-01 3.5997208952903748e-01 + <_> + + 0 -1 1954 -5.5300937965512276e-03 + + 2.3340409994125366e-01 4.9968141317367554e-01 + <_> + + 0 -1 1955 -2.6478730142116547e-03 + + 5.8809357881546021e-01 4.6847340464591980e-01 + <_> + + 0 -1 1956 1.1295629665255547e-02 + + 4.9837771058082581e-01 1.8845909833908081e-01 + <_> + + 0 -1 1957 -6.6952878842130303e-04 + + 5.8721381425857544e-01 4.7990199923515320e-01 + <_> + + 0 -1 1958 1.4410680159926414e-03 + + 5.1311892271041870e-01 3.5010111331939697e-01 + <_> + + 0 -1 1959 2.4637870956212282e-03 + + 5.3393721580505371e-01 4.1176390647888184e-01 + <_> + + 0 -1 1960 3.3114518737420440e-04 + + 4.3133831024169922e-01 5.3982460498809814e-01 + <_> + + 0 -1 1961 -3.3557269722223282e-02 + + 2.6753368973731995e-01 5.1791548728942871e-01 + <_> + + 0 -1 1962 1.8539419397711754e-02 + + 4.9738699197769165e-01 2.3171770572662354e-01 + <_> + + 0 -1 1963 -2.9698139405809343e-04 + + 5.5297082662582397e-01 4.6436640620231628e-01 + <_> + + 0 -1 1964 -4.5577259152196348e-04 + + 5.6295841932296753e-01 4.4691911339759827e-01 + <_> + + 0 -1 1965 -1.0158980265259743e-02 + + 6.7062127590179443e-01 4.9259188771247864e-01 + <_> + + 0 -1 1966 -2.2413829356082715e-05 + + 5.2394217252731323e-01 3.9129018783569336e-01 + <_> + + 0 -1 1967 7.2034963523037732e-05 + + 4.7994381189346313e-01 5.5017888545989990e-01 + <_> + + 0 -1 1968 -6.9267209619283676e-03 + + 6.9300097227096558e-01 4.6980848908424377e-01 + <_> + + 0 -1 1969 -7.6997838914394379e-03 + + 4.0996238589286804e-01 5.4808831214904785e-01 + <_> + + 0 -1 1970 -7.3130549862980843e-03 + + 3.2834759354591370e-01 5.0578862428665161e-01 + <_> + + 0 -1 1971 1.9650589674711227e-03 + + 4.9780470132827759e-01 6.3982498645782471e-01 + <_> + + 0 -1 1972 7.1647600270807743e-03 + + 4.6611601114273071e-01 6.2221372127532959e-01 + <_> + + 0 -1 1973 -2.4078639224171638e-02 + + 2.3346449434757233e-01 5.2221620082855225e-01 + <_> + + 0 -1 1974 -2.1027969196438789e-02 + + 1.1836539953947067e-01 4.9382260441780090e-01 + <_> + + 0 -1 1975 3.6017020465806127e-04 + + 5.3250199556350708e-01 4.1167110204696655e-01 + <_> + + 0 -1 1976 -1.7219729721546173e-02 + + 6.2787622213363647e-01 4.6642690896987915e-01 + <_> + + 0 -1 1977 -7.8672142699360847e-03 + + 3.4034150838851929e-01 5.2497369050979614e-01 + <_> + + 0 -1 1978 -4.4777389848604798e-04 + + 3.6104118824005127e-01 5.0862592458724976e-01 + <_> + + 0 -1 1979 5.5486010387539864e-03 + + 4.8842659592628479e-01 6.2034982442855835e-01 + <_> + + 0 -1 1980 -6.9461148232221603e-03 + + 2.6259300112724304e-01 5.0110971927642822e-01 + <_> + + 0 -1 1981 1.3569870498031378e-04 + + 4.3407949805259705e-01 5.6283122301101685e-01 + <_> + + 0 -1 1982 -4.5880250632762909e-02 + + 6.5079987049102783e-01 4.6962749958038330e-01 + <_> + + 0 -1 1983 -2.1582560613751411e-02 + + 3.8265028595924377e-01 5.2876168489456177e-01 + <_> + + 0 -1 1984 -2.0209539681673050e-02 + + 3.2333680987358093e-01 5.0744771957397461e-01 + <_> + + 0 -1 1985 5.8496710844337940e-03 + + 5.1776039600372314e-01 4.4896709918975830e-01 + <_> + + 0 -1 1986 -5.7476379879517481e-05 + + 4.0208509564399719e-01 5.2463638782501221e-01 + <_> + + 0 -1 1987 -1.1513100471347570e-03 + + 6.3150721788406372e-01 4.9051541090011597e-01 + <_> + + 0 -1 1988 1.9862831104546785e-03 + + 4.7024598717689514e-01 6.4971512556076050e-01 + <_> + + 0 -1 1989 -5.2719512023031712e-03 + + 3.6503839492797852e-01 5.2276527881622314e-01 + <_> + + 0 -1 1990 1.2662699446082115e-03 + + 5.1661008596420288e-01 3.8776180148124695e-01 + <_> + + 0 -1 1991 -6.2919440679252148e-03 + + 7.3758941888809204e-01 5.0238478183746338e-01 + <_> + + 0 -1 1992 6.7360111279413104e-04 + + 4.4232261180877686e-01 5.4955857992172241e-01 + <_> + + 0 -1 1993 -1.0523450328037143e-03 + + 5.9763962030410767e-01 4.8595830798149109e-01 + <_> + + 0 -1 1994 -4.4216238893568516e-04 + + 5.9559392929077148e-01 4.3989309668540955e-01 + <_> + + 0 -1 1995 1.1747940443456173e-03 + + 5.3498882055282593e-01 4.6050581336021423e-01 + <_> + + 0 -1 1996 5.2457437850534916e-03 + + 5.0491911172866821e-01 2.9415771365165710e-01 + <_> + + 0 -1 1997 -2.4539720267057419e-02 + + 2.5501778721809387e-01 5.2185869216918945e-01 + <_> + + 0 -1 1998 7.3793041519820690e-04 + + 4.4248610734939575e-01 5.4908162355422974e-01 + <_> + + 0 -1 1999 1.4233799884095788e-03 + + 5.3195142745971680e-01 4.0813559293746948e-01 + <_> + + 0 -1 2000 -2.4149110540747643e-03 + + 4.0876591205596924e-01 5.2389502525329590e-01 + <_> + + 0 -1 2001 -1.2165299849584699e-03 + + 5.6745791435241699e-01 4.9080529808998108e-01 + <_> + + 0 -1 2002 -1.2438809499144554e-03 + + 4.1294258832931519e-01 5.2561181783676147e-01 + <_> + + 0 -1 2003 6.1942739412188530e-03 + + 5.0601941347122192e-01 7.3136532306671143e-01 + <_> + + 0 -1 2004 -1.6607169527560472e-03 + + 5.9796321392059326e-01 4.5963698625564575e-01 + <_> + + 0 -1 2005 -2.7316259220242500e-02 + + 4.1743651032447815e-01 5.3088420629501343e-01 + <_> + + 0 -1 2006 -1.5845570014789701e-03 + + 5.6158047914505005e-01 4.5194861292839050e-01 + <_> + + 0 -1 2007 -1.5514739789068699e-03 + + 4.0761870145797729e-01 5.3607851266860962e-01 + <_> + + 0 -1 2008 3.8446558755822480e-04 + + 4.3472939729690552e-01 5.4304420948028564e-01 + <_> + + 0 -1 2009 -1.4672259800136089e-02 + + 1.6593049466609955e-01 5.1460939645767212e-01 + <_> + + 0 -1 2010 8.1608882173895836e-03 + + 4.9618190526962280e-01 1.8847459554672241e-01 + <_> + + 0 -1 2011 1.1121659772470593e-03 + + 4.8682639002799988e-01 6.0938161611557007e-01 + <_> + + 0 -1 2012 -7.2603770531713963e-03 + + 6.2843251228332520e-01 4.6903759241104126e-01 + <_> + + 0 -1 2013 -2.4046430189628154e-04 + + 5.5750000476837158e-01 4.0460440516471863e-01 + <_> + + 0 -1 2014 -2.3348190006799996e-04 + + 4.1157621145248413e-01 5.2528482675552368e-01 + <_> + + 0 -1 2015 5.5736480280756950e-03 + + 4.7300729155540466e-01 5.6901007890701294e-01 + <_> + + 0 -1 2016 3.0623769387602806e-02 + + 4.9718868732452393e-01 1.7400950193405151e-01 + <_> + + 0 -1 2017 9.2074798885732889e-04 + + 5.3721177577972412e-01 4.3548721075057983e-01 + <_> + + 0 -1 2018 -4.3550739064812660e-05 + + 5.3668838739395142e-01 4.3473169207572937e-01 + <_> + + 0 -1 2019 -6.6452710889279842e-03 + + 3.4355181455612183e-01 5.1605331897735596e-01 + <_> + + 0 -1 2020 4.3221998959779739e-02 + + 4.7667920589447021e-01 7.2936528921127319e-01 + <_> + + 0 -1 2021 2.2331769578158855e-03 + + 5.0293159484863281e-01 5.6331712007522583e-01 + <_> + + 0 -1 2022 3.1829739455133677e-03 + + 4.0160921216011047e-01 5.1921367645263672e-01 + <_> + + 0 -1 2023 -1.8027749320026487e-04 + + 4.0883159637451172e-01 5.4179197549819946e-01 + <_> + + 0 -1 2024 -5.2934689447283745e-03 + + 4.0756770968437195e-01 5.2435618638992310e-01 + <_> + + 0 -1 2025 1.2750959722325206e-03 + + 4.9132829904556274e-01 6.3870108127593994e-01 + <_> + + 0 -1 2026 4.3385322205722332e-03 + + 5.0316721200942993e-01 2.9473468661308289e-01 + <_> + + 0 -1 2027 8.5250744596123695e-03 + + 4.9497890472412109e-01 6.3088691234588623e-01 + <_> + + 0 -1 2028 -9.4266352243721485e-04 + + 5.3283667564392090e-01 4.2856499552726746e-01 + <_> + + 0 -1 2029 1.3609660090878606e-03 + + 4.9915251135826111e-01 5.9415012598037720e-01 + <_> + + 0 -1 2030 4.4782509212382138e-04 + + 4.5735040307044983e-01 5.8544808626174927e-01 + <_> + + 0 -1 2031 1.3360050506889820e-03 + + 4.6043589711189270e-01 5.8490520715713501e-01 + <_> + + 0 -1 2032 -6.0967548051849008e-04 + + 3.9693889021873474e-01 5.2294230461120605e-01 + <_> + + 0 -1 2033 -2.3656780831515789e-03 + + 5.8083200454711914e-01 4.8983570933341980e-01 + <_> + + 0 -1 2034 1.0734340175986290e-03 + + 4.3512108922004700e-01 5.4700392484664917e-01 + <_> + + 0 -1 2035 2.1923359017819166e-03 + + 5.3550601005554199e-01 3.8429039716720581e-01 + <_> + + 0 -1 2036 5.4968618787825108e-03 + + 5.0181388854980469e-01 2.8271919488906860e-01 + <_> + + 0 -1 2037 -7.5368821620941162e-02 + + 1.2250760197639465e-01 5.1488268375396729e-01 + <_> + + 0 -1 2038 2.5134470313787460e-02 + + 4.7317668795585632e-01 7.0254462957382202e-01 + <_> + + 0 -1 2039 -2.9358599931583740e-05 + + 5.4305320978164673e-01 4.6560868620872498e-01 + <_> + + 0 -1 2040 -5.8355910005047917e-04 + + 4.0310400724411011e-01 5.1901197433471680e-01 + <_> + + 0 -1 2041 -2.6639450807124376e-03 + + 4.3081268668174744e-01 5.1617711782455444e-01 + <_> + + 0 -1 2042 -1.3804089976474643e-03 + + 6.2198299169540405e-01 4.6955159306526184e-01 + <_> + + 0 -1 2043 1.2313219485804439e-03 + + 5.3793638944625854e-01 4.4258311390876770e-01 + <_> + + 0 -1 2044 -1.4644179827882908e-05 + + 5.2816402912139893e-01 4.2225030064582825e-01 + <_> + + 0 -1 2045 -1.2818809598684311e-02 + + 2.5820928812026978e-01 5.1799327135086060e-01 + <_> + + 0 -1 2046 2.2852189838886261e-02 + + 4.7786930203437805e-01 7.6092642545700073e-01 + <_> + + 0 -1 2047 8.2305970136076212e-04 + + 5.3409922122955322e-01 4.6717241406440735e-01 + <_> + + 0 -1 2048 1.2770120054483414e-02 + + 4.9657610058784485e-01 1.4723660051822662e-01 + <_> + + 0 -1 2049 -5.0051510334014893e-02 + + 6.4149940013885498e-01 5.0165921449661255e-01 + <_> + + 0 -1 2050 1.5775270760059357e-02 + + 4.5223200321197510e-01 5.6853622198104858e-01 + <_> + + 0 -1 2051 -1.8501620739698410e-02 + + 2.7647489309310913e-01 5.1379591226577759e-01 + <_> + + 0 -1 2052 2.4626250378787518e-03 + + 5.1419419050216675e-01 3.7954080104827881e-01 + <_> + + 0 -1 2053 6.2916167080402374e-02 + + 5.0606489181518555e-01 6.5804338455200195e-01 + <_> + + 0 -1 2054 -2.1648500478477217e-05 + + 5.1953881978988647e-01 4.0198868513107300e-01 + <_> + + 0 -1 2055 2.1180990152060986e-03 + + 4.9623650312423706e-01 5.9544587135314941e-01 + <_> + + 0 -1 2056 -1.6634890809655190e-02 + + 3.7579330801963806e-01 5.1754468679428101e-01 + <_> + + 0 -1 2057 -2.8899470344185829e-03 + + 6.6240137815475464e-01 5.0571787357330322e-01 + <_> + + 0 -1 2058 7.6783262193202972e-02 + + 4.7957968711853027e-01 8.0477148294448853e-01 + <_> + + 0 -1 2059 3.9170677773654461e-03 + + 4.9378821253776550e-01 5.7199418544769287e-01 + <_> + + 0 -1 2060 -7.2670601308345795e-02 + + 5.3894560784101486e-02 4.9439039826393127e-01 + <_> + + 0 -1 2061 5.4039502143859863e-01 + + 5.1297742128372192e-01 1.1433389782905579e-01 + <_> + + 0 -1 2062 2.9510019812732935e-03 + + 4.5283439755439758e-01 5.6985741853713989e-01 + <_> + + 0 -1 2063 3.4508369863033295e-03 + + 5.3577268123626709e-01 4.2187309265136719e-01 + <_> + + 0 -1 2064 -4.2077939724549651e-04 + + 5.9161728620529175e-01 4.6379259228706360e-01 + <_> + + 0 -1 2065 3.3051050268113613e-03 + + 5.2733850479125977e-01 4.3820428848266602e-01 + <_> + + 0 -1 2066 4.7735060798004270e-04 + + 4.0465280413627625e-01 5.1818847656250000e-01 + <_> + + 0 -1 2067 -2.5928510352969170e-02 + + 7.4522358179092407e-01 5.0893861055374146e-01 + <_> + + 0 -1 2068 -2.9729790985584259e-03 + + 3.2954359054565430e-01 5.0587952136993408e-01 + <_> + + 0 -1 2069 5.8508329093456268e-03 + + 4.8571440577507019e-01 5.7930248975753784e-01 + <_> + + 0 -1 2070 -4.5967519283294678e-02 + + 4.3127310276031494e-01 5.3806531429290771e-01 + <_> + + 0 -1 2071 1.5585960447788239e-01 + + 5.1961702108383179e-01 1.6847139596939087e-01 + <_> + + 0 -1 2072 1.5164829790592194e-02 + + 4.7357571125030518e-01 6.7350268363952637e-01 + <_> + + 0 -1 2073 -1.0604249546304345e-03 + + 5.8229267597198486e-01 4.7757029533386230e-01 + <_> + + 0 -1 2074 6.6476291976869106e-03 + + 4.9991989135742188e-01 2.3195350170135498e-01 + <_> + + 0 -1 2075 -1.2231130152940750e-02 + + 4.7508931159973145e-01 5.2629822492599487e-01 + <_> + + 0 -1 2076 5.6528882123529911e-03 + + 5.0697678327560425e-01 3.5618188977241516e-01 + <_> + + 0 -1 2077 1.2977829901501536e-03 + + 4.8756939172744751e-01 5.6190627813339233e-01 + <_> + + 0 -1 2078 1.0781589895486832e-02 + + 4.7507700324058533e-01 6.7823082208633423e-01 + <_> + + 0 -1 2079 2.8654779307544231e-03 + + 5.3054618835449219e-01 4.2907360196113586e-01 + <_> + + 0 -1 2080 2.8663428965955973e-03 + + 4.5184791088104248e-01 5.5393511056900024e-01 + <_> + + 0 -1 2081 -5.1983320154249668e-03 + + 4.1491198539733887e-01 5.4341888427734375e-01 + <_> + + 0 -1 2082 5.3739990107715130e-03 + + 4.7178968787193298e-01 6.5076571702957153e-01 + <_> + + 0 -1 2083 -1.4641529880464077e-02 + + 2.1721640229225159e-01 5.1617771387100220e-01 + <_> + + 0 -1 2084 -1.5042580344015732e-05 + + 5.3373837471008301e-01 4.2988368868827820e-01 + <_> + + 0 -1 2085 -1.1875660129589960e-04 + + 4.6045941114425659e-01 5.5824470520019531e-01 + <_> + + 0 -1 2086 1.6995530575513840e-02 + + 4.9458950757980347e-01 7.3880076408386230e-02 + <_> + + 0 -1 2087 -3.5095941275358200e-02 + + 7.0055091381072998e-01 4.9775910377502441e-01 + <_> + + 0 -1 2088 2.4217350874096155e-03 + + 4.4662651419639587e-01 5.4776942729949951e-01 + <_> + + 0 -1 2089 -9.6340337768197060e-04 + + 4.7140988707542419e-01 5.3133380413055420e-01 + <_> + + 0 -1 2090 1.6391130338888615e-04 + + 4.3315461277961731e-01 5.3422421216964722e-01 + <_> + + 0 -1 2091 -2.1141460165381432e-02 + + 2.6447001099586487e-01 5.2044987678527832e-01 + <_> + + 0 -1 2092 8.7775202700868249e-04 + + 5.2083498239517212e-01 4.1527429223060608e-01 + <_> + + 0 -1 2093 -2.7943920344114304e-02 + + 6.3441252708435059e-01 5.0188118219375610e-01 + <_> + + 0 -1 2094 6.7297378554940224e-03 + + 5.0504380464553833e-01 3.5008639097213745e-01 + <_> + + 0 -1 2095 2.3281039670109749e-02 + + 4.9663180112838745e-01 6.9686770439147949e-01 + <_> + + 0 -1 2096 -1.1644979938864708e-02 + + 3.3002600073814392e-01 5.0496298074722290e-01 + <_> + + 0 -1 2097 1.5764309093356133e-02 + + 4.9915981292724609e-01 7.3211538791656494e-01 + <_> + + 0 -1 2098 -1.3611479662358761e-03 + + 3.9117351174354553e-01 5.1606708765029907e-01 + <_> + + 0 -1 2099 -8.1522337859496474e-04 + + 5.6289112567901611e-01 4.9497190117835999e-01 + <_> + + 0 -1 2100 -6.0066272271797061e-04 + + 5.8535951375961304e-01 4.5505958795547485e-01 + <_> + + 0 -1 2101 4.9715518252924085e-04 + + 4.2714700102806091e-01 5.4435992240905762e-01 + <_> + + 0 -1 2102 2.3475370835512877e-03 + + 5.1431107521057129e-01 3.8876569271087646e-01 + <_> + + 0 -1 2103 -8.9261569082736969e-03 + + 6.0445022583007812e-01 4.9717208743095398e-01 + <_> + + 0 -1 2104 -1.3919910416007042e-02 + + 2.5831609964370728e-01 5.0003677606582642e-01 + <_> + + 0 -1 2105 1.0209949687123299e-03 + + 4.8573741316795349e-01 5.5603581666946411e-01 + <_> + + 0 -1 2106 -2.7441629208624363e-03 + + 5.9368848800659180e-01 4.6457770466804504e-01 + <_> + + 0 -1 2107 -1.6200130805373192e-02 + + 3.1630149483680725e-01 5.1934951543807983e-01 + <_> + + 0 -1 2108 4.3331980705261230e-03 + + 5.0612241029739380e-01 3.4588789939880371e-01 + <_> + + 0 -1 2109 5.8497930876910686e-04 + + 4.7790178656578064e-01 5.8701777458190918e-01 + <_> + + 0 -1 2110 -2.2466450463980436e-03 + + 4.2978510260581970e-01 5.3747731447219849e-01 + <_> + + 0 -1 2111 2.3146099410951138e-03 + + 5.4386717081069946e-01 4.6409699320793152e-01 + <_> + + 0 -1 2112 8.7679121643304825e-03 + + 4.7268930077552795e-01 6.7717897891998291e-01 + <_> + + 0 -1 2113 -2.2448020172305405e-04 + + 4.2291730642318726e-01 5.4280489683151245e-01 + <_> + + 0 -1 2114 -7.4336021207273006e-03 + + 6.0988807678222656e-01 4.6836739778518677e-01 + <_> + + 0 -1 2115 -2.3189240600913763e-03 + + 5.6894367933273315e-01 4.4242420792579651e-01 + <_> + + 0 -1 2116 -2.1042178850620985e-03 + + 3.7622210383415222e-01 5.1870870590209961e-01 + <_> + + 0 -1 2117 4.6034841216169298e-04 + + 4.6994051337242126e-01 5.7712072134017944e-01 + <_> + + 0 -1 2118 1.0547629790380597e-03 + + 4.4652169942855835e-01 5.6017017364501953e-01 + <_> + + 0 -1 2119 8.7148818420246243e-04 + + 5.4498052597045898e-01 3.9147090911865234e-01 + <_> + + 0 -1 2120 3.3364820410497487e-04 + + 4.5640090107917786e-01 5.6457388401031494e-01 + <_> + + 0 -1 2121 -1.4853250468149781e-03 + + 5.7473778724670410e-01 4.6927788853645325e-01 + <_> + + 0 -1 2122 3.0251620337367058e-03 + + 5.1661968231201172e-01 3.7628141045570374e-01 + <_> + + 0 -1 2123 5.0280741415917873e-03 + + 5.0021117925643921e-01 6.1515271663665771e-01 + <_> + + 0 -1 2124 -5.8164511574432254e-04 + + 5.3945982456207275e-01 4.3907511234283447e-01 + <_> + + 0 -1 2125 4.5141529291868210e-02 + + 5.1883268356323242e-01 2.0630359649658203e-01 + <_> + + 0 -1 2126 -1.0795620037242770e-03 + + 3.9046850800514221e-01 5.1379072666168213e-01 + <_> + + 0 -1 2127 1.5995999274309725e-04 + + 4.8953229188919067e-01 5.4275041818618774e-01 + <_> + + 0 -1 2128 -1.9359270110726357e-02 + + 6.9752287864685059e-01 4.7735071182250977e-01 + <_> + + 0 -1 2129 2.0725509524345398e-01 + + 5.2336359024047852e-01 3.0349919199943542e-01 + <_> + + 0 -1 2130 -4.1953290929086506e-04 + + 5.4193967580795288e-01 4.4601860642433167e-01 + <_> + + 0 -1 2131 2.2582069505006075e-03 + + 4.8157641291618347e-01 6.0274088382720947e-01 + <_> + + 0 -1 2132 -6.7811207845807076e-03 + + 3.9802789688110352e-01 5.1833057403564453e-01 + <_> + + 0 -1 2133 1.1154309846460819e-02 + + 5.4312318563461304e-01 4.1887599229812622e-01 + <_> + + 0 -1 2134 4.3162431567907333e-02 + + 4.7382280230522156e-01 6.5229612588882446e-01 + + <_> + + <_> + 3 7 14 4 -1. + <_> + 3 9 14 2 2. + <_> + + <_> + 1 2 18 4 -1. + <_> + 7 2 6 4 3. + <_> + + <_> + 1 7 15 9 -1. + <_> + 1 10 15 3 3. + <_> + + <_> + 5 6 2 6 -1. + <_> + 5 9 2 3 2. + <_> + + <_> + 7 5 6 3 -1. + <_> + 9 5 2 3 3. + <_> + + <_> + 4 0 12 9 -1. + <_> + 4 3 12 3 3. + <_> + + <_> + 6 9 10 8 -1. + <_> + 6 13 10 4 2. + <_> + + <_> + 3 6 14 8 -1. + <_> + 3 10 14 4 2. + <_> + + <_> + 14 1 6 10 -1. + <_> + 14 1 3 10 2. + <_> + + <_> + 7 8 5 12 -1. + <_> + 7 12 5 4 3. + <_> + + <_> + 1 1 18 3 -1. + <_> + 7 1 6 3 3. + <_> + + <_> + 1 8 17 2 -1. + <_> + 1 9 17 1 2. + <_> + + <_> + 16 6 4 2 -1. + <_> + 16 7 4 1 2. + <_> + + <_> + 5 17 2 2 -1. + <_> + 5 18 2 1 2. + <_> + + <_> + 14 2 6 12 -1. + <_> + 14 2 3 12 2. + <_> + + <_> + 4 0 4 12 -1. + <_> + 4 0 2 6 2. + <_> + 6 6 2 6 2. + <_> + + <_> + 2 11 18 8 -1. + <_> + 8 11 6 8 3. + <_> + + <_> + 5 7 10 2 -1. + <_> + 5 8 10 1 2. + <_> + + <_> + 15 11 5 3 -1. + <_> + 15 12 5 1 3. + <_> + + <_> + 5 3 10 9 -1. + <_> + 5 6 10 3 3. + <_> + + <_> + 9 4 2 14 -1. + <_> + 9 11 2 7 2. + <_> + + <_> + 3 5 4 12 -1. + <_> + 3 9 4 4 3. + <_> + + <_> + 4 5 12 5 -1. + <_> + 8 5 4 5 3. + <_> + + <_> + 5 6 10 8 -1. + <_> + 5 10 10 4 2. + <_> + + <_> + 8 0 6 9 -1. + <_> + 8 3 6 3 3. + <_> + + <_> + 9 12 1 8 -1. + <_> + 9 16 1 4 2. + <_> + + <_> + 0 7 20 6 -1. + <_> + 0 9 20 2 3. + <_> + + <_> + 7 0 6 17 -1. + <_> + 9 0 2 17 3. + <_> + + <_> + 9 0 6 4 -1. + <_> + 11 0 2 4 3. + <_> + + <_> + 5 1 6 4 -1. + <_> + 7 1 2 4 3. + <_> + + <_> + 12 1 6 16 -1. + <_> + 14 1 2 16 3. + <_> + + <_> + 0 5 18 8 -1. + <_> + 0 5 9 4 2. + <_> + 9 9 9 4 2. + <_> + + <_> + 8 15 10 4 -1. + <_> + 13 15 5 2 2. + <_> + 8 17 5 2 2. + <_> + + <_> + 3 1 4 8 -1. + <_> + 3 1 2 4 2. + <_> + 5 5 2 4 2. + <_> + + <_> + 3 6 14 10 -1. + <_> + 10 6 7 5 2. + <_> + 3 11 7 5 2. + <_> + + <_> + 2 1 6 16 -1. + <_> + 4 1 2 16 3. + <_> + + <_> + 0 18 20 2 -1. + <_> + 0 19 20 1 2. + <_> + + <_> + 8 13 4 3 -1. + <_> + 8 14 4 1 3. + <_> + + <_> + 9 14 2 3 -1. + <_> + 9 15 2 1 3. + <_> + + <_> + 0 12 9 6 -1. + <_> + 0 14 9 2 3. + <_> + + <_> + 5 7 3 4 -1. + <_> + 5 9 3 2 2. + <_> + + <_> + 9 3 2 16 -1. + <_> + 9 11 2 8 2. + <_> + + <_> + 3 6 13 8 -1. + <_> + 3 10 13 4 2. + <_> + + <_> + 12 3 8 2 -1. + <_> + 12 3 4 2 2. + <_> + + <_> + 8 8 4 12 -1. + <_> + 8 12 4 4 3. + <_> + + <_> + 11 3 8 6 -1. + <_> + 15 3 4 3 2. + <_> + 11 6 4 3 2. + <_> + + <_> + 7 1 6 19 -1. + <_> + 9 1 2 19 3. + <_> + + <_> + 9 0 6 4 -1. + <_> + 11 0 2 4 3. + <_> + + <_> + 3 1 9 3 -1. + <_> + 6 1 3 3 3. + <_> + + <_> + 8 15 10 4 -1. + <_> + 13 15 5 2 2. + <_> + 8 17 5 2 2. + <_> + + <_> + 0 3 6 10 -1. + <_> + 3 3 3 10 2. + <_> + + <_> + 3 4 15 15 -1. + <_> + 3 9 15 5 3. + <_> + + <_> + 6 5 8 6 -1. + <_> + 6 7 8 2 3. + <_> + + <_> + 4 4 12 10 -1. + <_> + 10 4 6 5 2. + <_> + 4 9 6 5 2. + <_> + + <_> + 6 4 4 4 -1. + <_> + 8 4 2 4 2. + <_> + + <_> + 15 11 1 2 -1. + <_> + 15 12 1 1 2. + <_> + + <_> + 3 11 2 2 -1. + <_> + 3 12 2 1 2. + <_> + + <_> + 16 11 1 3 -1. + <_> + 16 12 1 1 3. + <_> + + <_> + 3 15 6 4 -1. + <_> + 3 15 3 2 2. + <_> + 6 17 3 2 2. + <_> + + <_> + 6 7 8 2 -1. + <_> + 6 8 8 1 2. + <_> + + <_> + 3 11 1 3 -1. + <_> + 3 12 1 1 3. + <_> + + <_> + 6 0 12 2 -1. + <_> + 6 1 12 1 2. + <_> + + <_> + 9 14 2 3 -1. + <_> + 9 15 2 1 3. + <_> + + <_> + 7 15 6 2 -1. + <_> + 7 16 6 1 2. + <_> + + <_> + 0 5 4 6 -1. + <_> + 0 7 4 2 3. + <_> + + <_> + 4 12 12 2 -1. + <_> + 8 12 4 2 3. + <_> + + <_> + 6 3 1 9 -1. + <_> + 6 6 1 3 3. + <_> + + <_> + 10 17 3 2 -1. + <_> + 11 17 1 2 3. + <_> + + <_> + 9 9 2 2 -1. + <_> + 9 10 2 1 2. + <_> + + <_> + 7 6 6 4 -1. + <_> + 9 6 2 4 3. + <_> + + <_> + 7 17 3 2 -1. + <_> + 8 17 1 2 3. + <_> + + <_> + 10 17 3 3 -1. + <_> + 11 17 1 3 3. + <_> + + <_> + 8 12 3 2 -1. + <_> + 8 13 3 1 2. + <_> + + <_> + 9 3 6 2 -1. + <_> + 11 3 2 2 3. + <_> + + <_> + 3 11 14 4 -1. + <_> + 3 13 14 2 2. + <_> + + <_> + 1 10 18 4 -1. + <_> + 10 10 9 2 2. + <_> + 1 12 9 2 2. + <_> + + <_> + 0 10 3 3 -1. + <_> + 0 11 3 1 3. + <_> + + <_> + 9 1 6 6 -1. + <_> + 11 1 2 6 3. + <_> + + <_> + 8 7 3 6 -1. + <_> + 9 7 1 6 3. + <_> + + <_> + 1 0 18 9 -1. + <_> + 1 3 18 3 3. + <_> + + <_> + 12 10 2 6 -1. + <_> + 12 13 2 3 2. + <_> + + <_> + 0 5 19 8 -1. + <_> + 0 9 19 4 2. + <_> + + <_> + 7 0 6 9 -1. + <_> + 9 0 2 9 3. + <_> + + <_> + 5 3 6 1 -1. + <_> + 7 3 2 1 3. + <_> + + <_> + 11 3 6 1 -1. + <_> + 13 3 2 1 3. + <_> + + <_> + 5 10 4 6 -1. + <_> + 5 13 4 3 2. + <_> + + <_> + 11 3 6 1 -1. + <_> + 13 3 2 1 3. + <_> + + <_> + 4 4 12 6 -1. + <_> + 4 6 12 2 3. + <_> + + <_> + 15 12 2 6 -1. + <_> + 15 14 2 2 3. + <_> + + <_> + 9 3 2 2 -1. + <_> + 10 3 1 2 2. + <_> + + <_> + 9 3 3 1 -1. + <_> + 10 3 1 1 3. + <_> + + <_> + 1 1 4 14 -1. + <_> + 3 1 2 14 2. + <_> + + <_> + 9 0 4 4 -1. + <_> + 11 0 2 2 2. + <_> + 9 2 2 2 2. + <_> + + <_> + 7 5 1 14 -1. + <_> + 7 12 1 7 2. + <_> + + <_> + 19 0 1 4 -1. + <_> + 19 2 1 2 2. + <_> + + <_> + 5 5 6 4 -1. + <_> + 8 5 3 4 2. + <_> + + <_> + 9 18 3 2 -1. + <_> + 10 18 1 2 3. + <_> + + <_> + 8 18 3 2 -1. + <_> + 9 18 1 2 3. + <_> + + <_> + 4 5 12 6 -1. + <_> + 4 7 12 2 3. + <_> + + <_> + 3 12 2 6 -1. + <_> + 3 14 2 2 3. + <_> + + <_> + 10 8 2 12 -1. + <_> + 10 12 2 4 3. + <_> + + <_> + 7 18 3 2 -1. + <_> + 8 18 1 2 3. + <_> + + <_> + 9 0 6 2 -1. + <_> + 11 0 2 2 3. + <_> + + <_> + 5 11 9 3 -1. + <_> + 5 12 9 1 3. + <_> + + <_> + 9 0 6 2 -1. + <_> + 11 0 2 2 3. + <_> + + <_> + 1 1 18 5 -1. + <_> + 7 1 6 5 3. + <_> + + <_> + 8 0 4 4 -1. + <_> + 10 0 2 2 2. + <_> + 8 2 2 2 2. + <_> + + <_> + 3 12 1 3 -1. + <_> + 3 13 1 1 3. + <_> + + <_> + 8 14 5 3 -1. + <_> + 8 15 5 1 3. + <_> + + <_> + 5 4 10 12 -1. + <_> + 5 4 5 6 2. + <_> + 10 10 5 6 2. + <_> + + <_> + 9 6 9 12 -1. + <_> + 9 10 9 4 3. + <_> + + <_> + 2 2 12 14 -1. + <_> + 2 2 6 7 2. + <_> + 8 9 6 7 2. + <_> + + <_> + 4 7 12 2 -1. + <_> + 8 7 4 2 3. + <_> + + <_> + 7 4 6 4 -1. + <_> + 7 6 6 2 2. + <_> + + <_> + 4 5 11 8 -1. + <_> + 4 9 11 4 2. + <_> + + <_> + 3 10 16 4 -1. + <_> + 3 12 16 2 2. + <_> + + <_> + 0 0 16 2 -1. + <_> + 0 1 16 1 2. + <_> + + <_> + 7 5 6 2 -1. + <_> + 9 5 2 2 3. + <_> + + <_> + 3 2 6 10 -1. + <_> + 3 2 3 5 2. + <_> + 6 7 3 5 2. + <_> + + <_> + 10 5 8 15 -1. + <_> + 10 10 8 5 3. + <_> + + <_> + 3 14 8 6 -1. + <_> + 3 14 4 3 2. + <_> + 7 17 4 3 2. + <_> + + <_> + 14 2 2 2 -1. + <_> + 14 3 2 1 2. + <_> + + <_> + 1 10 7 6 -1. + <_> + 1 13 7 3 2. + <_> + + <_> + 15 4 4 3 -1. + <_> + 15 4 2 3 2. + <_> + + <_> + 2 9 14 6 -1. + <_> + 2 9 7 3 2. + <_> + 9 12 7 3 2. + <_> + + <_> + 5 7 10 4 -1. + <_> + 5 9 10 2 2. + <_> + + <_> + 6 9 8 8 -1. + <_> + 6 9 4 4 2. + <_> + 10 13 4 4 2. + <_> + + <_> + 14 1 3 2 -1. + <_> + 14 2 3 1 2. + <_> + + <_> + 1 4 4 2 -1. + <_> + 3 4 2 2 2. + <_> + + <_> + 11 10 2 8 -1. + <_> + 11 14 2 4 2. + <_> + + <_> + 0 0 5 3 -1. + <_> + 0 1 5 1 3. + <_> + + <_> + 2 5 18 8 -1. + <_> + 11 5 9 4 2. + <_> + 2 9 9 4 2. + <_> + + <_> + 6 6 1 6 -1. + <_> + 6 9 1 3 2. + <_> + + <_> + 19 1 1 3 -1. + <_> + 19 2 1 1 3. + <_> + + <_> + 7 6 6 6 -1. + <_> + 9 6 2 6 3. + <_> + + <_> + 19 1 1 3 -1. + <_> + 19 2 1 1 3. + <_> + + <_> + 3 13 2 3 -1. + <_> + 3 14 2 1 3. + <_> + + <_> + 8 4 8 12 -1. + <_> + 12 4 4 6 2. + <_> + 8 10 4 6 2. + <_> + + <_> + 5 2 6 3 -1. + <_> + 7 2 2 3 3. + <_> + + <_> + 6 1 9 10 -1. + <_> + 6 6 9 5 2. + <_> + + <_> + 0 4 6 12 -1. + <_> + 2 4 2 12 3. + <_> + + <_> + 15 13 2 3 -1. + <_> + 15 14 2 1 3. + <_> + + <_> + 7 14 5 3 -1. + <_> + 7 15 5 1 3. + <_> + + <_> + 15 13 3 3 -1. + <_> + 15 14 3 1 3. + <_> + + <_> + 6 14 8 3 -1. + <_> + 6 15 8 1 3. + <_> + + <_> + 15 13 3 3 -1. + <_> + 15 14 3 1 3. + <_> + + <_> + 2 13 3 3 -1. + <_> + 2 14 3 1 3. + <_> + + <_> + 4 7 12 12 -1. + <_> + 10 7 6 6 2. + <_> + 4 13 6 6 2. + <_> + + <_> + 9 7 2 6 -1. + <_> + 10 7 1 6 2. + <_> + + <_> + 8 9 5 2 -1. + <_> + 8 10 5 1 2. + <_> + + <_> + 8 6 3 4 -1. + <_> + 9 6 1 4 3. + <_> + + <_> + 9 6 2 8 -1. + <_> + 9 10 2 4 2. + <_> + + <_> + 7 7 3 6 -1. + <_> + 8 7 1 6 3. + <_> + + <_> + 11 3 3 3 -1. + <_> + 12 3 1 3 3. + <_> + + <_> + 5 4 6 1 -1. + <_> + 7 4 2 1 3. + <_> + + <_> + 5 6 10 3 -1. + <_> + 5 7 10 1 3. + <_> + + <_> + 7 3 6 9 -1. + <_> + 7 6 6 3 3. + <_> + + <_> + 6 7 9 1 -1. + <_> + 9 7 3 1 3. + <_> + + <_> + 2 8 16 8 -1. + <_> + 2 12 16 4 2. + <_> + + <_> + 14 6 2 6 -1. + <_> + 14 9 2 3 2. + <_> + + <_> + 1 5 6 15 -1. + <_> + 1 10 6 5 3. + <_> + + <_> + 10 0 6 9 -1. + <_> + 10 3 6 3 3. + <_> + + <_> + 6 6 7 14 -1. + <_> + 6 13 7 7 2. + <_> + + <_> + 13 7 3 6 -1. + <_> + 13 9 3 2 3. + <_> + + <_> + 1 8 15 4 -1. + <_> + 6 8 5 4 3. + <_> + + <_> + 11 2 3 10 -1. + <_> + 11 7 3 5 2. + <_> + + <_> + 3 7 4 6 -1. + <_> + 3 9 4 2 3. + <_> + + <_> + 13 3 6 10 -1. + <_> + 15 3 2 10 3. + <_> + + <_> + 5 7 8 10 -1. + <_> + 5 7 4 5 2. + <_> + 9 12 4 5 2. + <_> + + <_> + 4 4 12 12 -1. + <_> + 10 4 6 6 2. + <_> + 4 10 6 6 2. + <_> + + <_> + 1 4 6 9 -1. + <_> + 3 4 2 9 3. + <_> + + <_> + 11 3 2 5 -1. + <_> + 11 3 1 5 2. + <_> + + <_> + 7 3 2 5 -1. + <_> + 8 3 1 5 2. + <_> + + <_> + 10 14 2 3 -1. + <_> + 10 15 2 1 3. + <_> + + <_> + 5 12 6 2 -1. + <_> + 8 12 3 2 2. + <_> + + <_> + 9 14 2 3 -1. + <_> + 9 15 2 1 3. + <_> + + <_> + 4 11 12 6 -1. + <_> + 4 14 12 3 2. + <_> + + <_> + 11 11 5 9 -1. + <_> + 11 14 5 3 3. + <_> + + <_> + 6 15 3 2 -1. + <_> + 6 16 3 1 2. + <_> + + <_> + 11 0 3 5 -1. + <_> + 12 0 1 5 3. + <_> + + <_> + 5 5 6 7 -1. + <_> + 8 5 3 7 2. + <_> + + <_> + 13 0 1 9 -1. + <_> + 13 3 1 3 3. + <_> + + <_> + 3 2 4 8 -1. + <_> + 3 2 2 4 2. + <_> + 5 6 2 4 2. + <_> + + <_> + 13 12 4 6 -1. + <_> + 13 14 4 2 3. + <_> + + <_> + 3 12 4 6 -1. + <_> + 3 14 4 2 3. + <_> + + <_> + 13 11 3 4 -1. + <_> + 13 13 3 2 2. + <_> + + <_> + 4 4 4 3 -1. + <_> + 4 5 4 1 3. + <_> + + <_> + 7 5 11 8 -1. + <_> + 7 9 11 4 2. + <_> + + <_> + 7 8 3 4 -1. + <_> + 8 8 1 4 3. + <_> + + <_> + 9 1 6 1 -1. + <_> + 11 1 2 1 3. + <_> + + <_> + 5 5 3 3 -1. + <_> + 5 6 3 1 3. + <_> + + <_> + 0 9 20 6 -1. + <_> + 10 9 10 3 2. + <_> + 0 12 10 3 2. + <_> + + <_> + 8 6 3 5 -1. + <_> + 9 6 1 5 3. + <_> + + <_> + 11 0 1 3 -1. + <_> + 11 1 1 1 3. + <_> + + <_> + 4 2 4 2 -1. + <_> + 4 3 4 1 2. + <_> + + <_> + 12 6 4 3 -1. + <_> + 12 7 4 1 3. + <_> + + <_> + 5 0 6 4 -1. + <_> + 7 0 2 4 3. + <_> + + <_> + 9 7 3 8 -1. + <_> + 10 7 1 8 3. + <_> + + <_> + 9 7 2 2 -1. + <_> + 10 7 1 2 2. + <_> + + <_> + 6 7 14 4 -1. + <_> + 13 7 7 2 2. + <_> + 6 9 7 2 2. + <_> + + <_> + 0 5 3 6 -1. + <_> + 0 7 3 2 3. + <_> + + <_> + 13 11 3 4 -1. + <_> + 13 13 3 2 2. + <_> + + <_> + 4 11 3 4 -1. + <_> + 4 13 3 2 2. + <_> + + <_> + 5 9 12 8 -1. + <_> + 11 9 6 4 2. + <_> + 5 13 6 4 2. + <_> + + <_> + 9 12 1 3 -1. + <_> + 9 13 1 1 3. + <_> + + <_> + 10 15 2 4 -1. + <_> + 10 17 2 2 2. + <_> + + <_> + 7 7 6 1 -1. + <_> + 9 7 2 1 3. + <_> + + <_> + 12 3 6 6 -1. + <_> + 15 3 3 3 2. + <_> + 12 6 3 3 2. + <_> + + <_> + 0 4 10 6 -1. + <_> + 0 6 10 2 3. + <_> + + <_> + 8 3 8 14 -1. + <_> + 12 3 4 7 2. + <_> + 8 10 4 7 2. + <_> + + <_> + 4 4 7 15 -1. + <_> + 4 9 7 5 3. + <_> + + <_> + 12 2 6 8 -1. + <_> + 15 2 3 4 2. + <_> + 12 6 3 4 2. + <_> + + <_> + 2 2 6 8 -1. + <_> + 2 2 3 4 2. + <_> + 5 6 3 4 2. + <_> + + <_> + 2 13 18 7 -1. + <_> + 8 13 6 7 3. + <_> + + <_> + 4 3 8 14 -1. + <_> + 4 3 4 7 2. + <_> + 8 10 4 7 2. + <_> + + <_> + 18 1 2 6 -1. + <_> + 18 3 2 2 3. + <_> + + <_> + 9 11 2 3 -1. + <_> + 9 12 2 1 3. + <_> + + <_> + 18 1 2 6 -1. + <_> + 18 3 2 2 3. + <_> + + <_> + 0 1 2 6 -1. + <_> + 0 3 2 2 3. + <_> + + <_> + 1 5 18 6 -1. + <_> + 1 7 18 2 3. + <_> + + <_> + 0 2 6 7 -1. + <_> + 3 2 3 7 2. + <_> + + <_> + 7 3 6 14 -1. + <_> + 7 10 6 7 2. + <_> + + <_> + 3 7 13 10 -1. + <_> + 3 12 13 5 2. + <_> + + <_> + 11 15 2 2 -1. + <_> + 11 16 2 1 2. + <_> + + <_> + 2 11 16 4 -1. + <_> + 2 11 8 2 2. + <_> + 10 13 8 2 2. + <_> + + <_> + 13 7 6 4 -1. + <_> + 16 7 3 2 2. + <_> + 13 9 3 2 2. + <_> + + <_> + 6 10 3 9 -1. + <_> + 6 13 3 3 3. + <_> + + <_> + 14 6 1 6 -1. + <_> + 14 9 1 3 2. + <_> + + <_> + 5 10 4 1 -1. + <_> + 7 10 2 1 2. + <_> + + <_> + 3 8 15 5 -1. + <_> + 8 8 5 5 3. + <_> + + <_> + 1 6 5 4 -1. + <_> + 1 8 5 2 2. + <_> + + <_> + 3 1 17 6 -1. + <_> + 3 3 17 2 3. + <_> + + <_> + 6 7 8 2 -1. + <_> + 10 7 4 2 2. + <_> + + <_> + 9 7 3 2 -1. + <_> + 10 7 1 2 3. + <_> + + <_> + 8 7 3 2 -1. + <_> + 9 7 1 2 3. + <_> + + <_> + 8 9 4 2 -1. + <_> + 8 10 4 1 2. + <_> + + <_> + 8 8 4 3 -1. + <_> + 8 9 4 1 3. + <_> + + <_> + 9 5 6 4 -1. + <_> + 9 5 3 4 2. + <_> + + <_> + 8 13 4 3 -1. + <_> + 8 14 4 1 3. + <_> + + <_> + 4 7 12 6 -1. + <_> + 10 7 6 3 2. + <_> + 4 10 6 3 2. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 9 7 3 3 -1. + <_> + 9 8 3 1 3. + <_> + + <_> + 7 4 3 8 -1. + <_> + 8 4 1 8 3. + <_> + + <_> + 10 0 3 6 -1. + <_> + 11 0 1 6 3. + <_> + + <_> + 6 3 4 8 -1. + <_> + 8 3 2 8 2. + <_> + + <_> + 14 3 6 13 -1. + <_> + 14 3 3 13 2. + <_> + + <_> + 8 13 3 6 -1. + <_> + 8 16 3 3 2. + <_> + + <_> + 14 3 6 13 -1. + <_> + 14 3 3 13 2. + <_> + + <_> + 0 7 10 4 -1. + <_> + 0 7 5 2 2. + <_> + 5 9 5 2 2. + <_> + + <_> + 14 3 6 13 -1. + <_> + 14 3 3 13 2. + <_> + + <_> + 0 3 6 13 -1. + <_> + 3 3 3 13 2. + <_> + + <_> + 9 1 4 1 -1. + <_> + 9 1 2 1 2. + <_> + + <_> + 8 0 2 1 -1. + <_> + 9 0 1 1 2. + <_> + + <_> + 10 16 4 4 -1. + <_> + 12 16 2 2 2. + <_> + 10 18 2 2 2. + <_> + + <_> + 9 6 2 3 -1. + <_> + 10 6 1 3 2. + <_> + + <_> + 4 5 12 2 -1. + <_> + 8 5 4 2 3. + <_> + + <_> + 8 7 3 5 -1. + <_> + 9 7 1 5 3. + <_> + + <_> + 6 4 8 6 -1. + <_> + 6 6 8 2 3. + <_> + + <_> + 9 5 2 12 -1. + <_> + 9 11 2 6 2. + <_> + + <_> + 4 6 6 8 -1. + <_> + 4 10 6 4 2. + <_> + + <_> + 12 2 8 5 -1. + <_> + 12 2 4 5 2. + <_> + + <_> + 0 8 18 3 -1. + <_> + 0 9 18 1 3. + <_> + + <_> + 8 12 4 8 -1. + <_> + 8 16 4 4 2. + <_> + + <_> + 0 2 8 5 -1. + <_> + 4 2 4 5 2. + <_> + + <_> + 13 11 3 4 -1. + <_> + 13 13 3 2 2. + <_> + + <_> + 5 11 6 1 -1. + <_> + 7 11 2 1 3. + <_> + + <_> + 11 3 3 1 -1. + <_> + 12 3 1 1 3. + <_> + + <_> + 7 13 5 3 -1. + <_> + 7 14 5 1 3. + <_> + + <_> + 11 11 7 6 -1. + <_> + 11 14 7 3 2. + <_> + + <_> + 2 11 7 6 -1. + <_> + 2 14 7 3 2. + <_> + + <_> + 12 14 2 6 -1. + <_> + 12 16 2 2 3. + <_> + + <_> + 8 14 3 3 -1. + <_> + 8 15 3 1 3. + <_> + + <_> + 11 0 3 5 -1. + <_> + 12 0 1 5 3. + <_> + + <_> + 6 1 4 9 -1. + <_> + 8 1 2 9 2. + <_> + + <_> + 10 3 6 1 -1. + <_> + 12 3 2 1 3. + <_> + + <_> + 8 8 3 4 -1. + <_> + 8 10 3 2 2. + <_> + + <_> + 8 12 4 2 -1. + <_> + 8 13 4 1 2. + <_> + + <_> + 5 18 4 2 -1. + <_> + 5 19 4 1 2. + <_> + + <_> + 2 1 18 6 -1. + <_> + 2 3 18 2 3. + <_> + + <_> + 6 0 3 2 -1. + <_> + 7 0 1 2 3. + <_> + + <_> + 13 8 6 2 -1. + <_> + 16 8 3 1 2. + <_> + 13 9 3 1 2. + <_> + + <_> + 6 10 3 6 -1. + <_> + 6 13 3 3 2. + <_> + + <_> + 0 13 20 4 -1. + <_> + 10 13 10 2 2. + <_> + 0 15 10 2 2. + <_> + + <_> + 7 7 6 5 -1. + <_> + 9 7 2 5 3. + <_> + + <_> + 11 0 2 2 -1. + <_> + 11 1 2 1 2. + <_> + + <_> + 1 8 6 2 -1. + <_> + 1 8 3 1 2. + <_> + 4 9 3 1 2. + <_> + + <_> + 0 2 20 2 -1. + <_> + 10 2 10 1 2. + <_> + 0 3 10 1 2. + <_> + + <_> + 7 14 5 3 -1. + <_> + 7 15 5 1 3. + <_> + + <_> + 7 13 6 6 -1. + <_> + 10 13 3 3 2. + <_> + 7 16 3 3 2. + <_> + + <_> + 9 12 2 3 -1. + <_> + 9 13 2 1 3. + <_> + + <_> + 16 11 1 6 -1. + <_> + 16 13 1 2 3. + <_> + + <_> + 3 11 1 6 -1. + <_> + 3 13 1 2 3. + <_> + + <_> + 4 4 14 12 -1. + <_> + 11 4 7 6 2. + <_> + 4 10 7 6 2. + <_> + + <_> + 5 4 3 3 -1. + <_> + 5 5 3 1 3. + <_> + + <_> + 12 3 3 3 -1. + <_> + 13 3 1 3 3. + <_> + + <_> + 6 6 8 3 -1. + <_> + 6 7 8 1 3. + <_> + + <_> + 12 3 3 3 -1. + <_> + 13 3 1 3 3. + <_> + + <_> + 3 1 4 10 -1. + <_> + 3 1 2 5 2. + <_> + 5 6 2 5 2. + <_> + + <_> + 5 7 10 2 -1. + <_> + 5 7 5 2 2. + <_> + + <_> + 8 7 3 3 -1. + <_> + 9 7 1 3 3. + <_> + + <_> + 15 12 2 3 -1. + <_> + 15 13 2 1 3. + <_> + + <_> + 7 8 3 4 -1. + <_> + 8 8 1 4 3. + <_> + + <_> + 13 4 1 12 -1. + <_> + 13 10 1 6 2. + <_> + + <_> + 4 5 12 12 -1. + <_> + 4 5 6 6 2. + <_> + 10 11 6 6 2. + <_> + + <_> + 7 14 7 3 -1. + <_> + 7 15 7 1 3. + <_> + + <_> + 3 12 2 3 -1. + <_> + 3 13 2 1 3. + <_> + + <_> + 3 2 14 2 -1. + <_> + 10 2 7 1 2. + <_> + 3 3 7 1 2. + <_> + + <_> + 0 1 3 10 -1. + <_> + 1 1 1 10 3. + <_> + + <_> + 9 0 6 5 -1. + <_> + 11 0 2 5 3. + <_> + + <_> + 5 7 6 2 -1. + <_> + 8 7 3 2 2. + <_> + + <_> + 7 1 6 10 -1. + <_> + 7 6 6 5 2. + <_> + + <_> + 1 1 18 3 -1. + <_> + 7 1 6 3 3. + <_> + + <_> + 16 3 3 6 -1. + <_> + 16 5 3 2 3. + <_> + + <_> + 6 3 7 6 -1. + <_> + 6 6 7 3 2. + <_> + + <_> + 4 7 12 2 -1. + <_> + 8 7 4 2 3. + <_> + + <_> + 0 4 17 10 -1. + <_> + 0 9 17 5 2. + <_> + + <_> + 3 4 15 16 -1. + <_> + 3 12 15 8 2. + <_> + + <_> + 7 15 6 4 -1. + <_> + 7 17 6 2 2. + <_> + + <_> + 15 2 4 9 -1. + <_> + 15 2 2 9 2. + <_> + + <_> + 2 3 3 2 -1. + <_> + 2 4 3 1 2. + <_> + + <_> + 13 6 7 9 -1. + <_> + 13 9 7 3 3. + <_> + + <_> + 8 11 4 3 -1. + <_> + 8 12 4 1 3. + <_> + + <_> + 0 2 20 6 -1. + <_> + 10 2 10 3 2. + <_> + 0 5 10 3 2. + <_> + + <_> + 3 2 6 10 -1. + <_> + 3 2 3 5 2. + <_> + 6 7 3 5 2. + <_> + + <_> + 13 10 3 4 -1. + <_> + 13 12 3 2 2. + <_> + + <_> + 4 10 3 4 -1. + <_> + 4 12 3 2 2. + <_> + + <_> + 7 5 6 3 -1. + <_> + 9 5 2 3 3. + <_> + + <_> + 7 6 6 8 -1. + <_> + 7 10 6 4 2. + <_> + + <_> + 0 11 20 6 -1. + <_> + 0 14 20 3 2. + <_> + + <_> + 4 13 4 6 -1. + <_> + 4 13 2 3 2. + <_> + 6 16 2 3 2. + <_> + + <_> + 6 0 8 12 -1. + <_> + 10 0 4 6 2. + <_> + 6 6 4 6 2. + <_> + + <_> + 2 0 15 2 -1. + <_> + 2 1 15 1 2. + <_> + + <_> + 9 12 2 3 -1. + <_> + 9 13 2 1 3. + <_> + + <_> + 3 12 1 2 -1. + <_> + 3 13 1 1 2. + <_> + + <_> + 9 11 2 3 -1. + <_> + 9 12 2 1 3. + <_> + + <_> + 7 3 3 1 -1. + <_> + 8 3 1 1 3. + <_> + + <_> + 17 7 3 6 -1. + <_> + 17 9 3 2 3. + <_> + + <_> + 7 2 3 2 -1. + <_> + 8 2 1 2 3. + <_> + + <_> + 11 4 5 3 -1. + <_> + 11 5 5 1 3. + <_> + + <_> + 4 4 5 3 -1. + <_> + 4 5 5 1 3. + <_> + + <_> + 19 3 1 2 -1. + <_> + 19 4 1 1 2. + <_> + + <_> + 5 5 4 3 -1. + <_> + 5 6 4 1 3. + <_> + + <_> + 17 7 3 6 -1. + <_> + 17 9 3 2 3. + <_> + + <_> + 0 7 3 6 -1. + <_> + 0 9 3 2 3. + <_> + + <_> + 14 2 6 9 -1. + <_> + 14 5 6 3 3. + <_> + + <_> + 0 4 5 6 -1. + <_> + 0 6 5 2 3. + <_> + + <_> + 10 5 6 2 -1. + <_> + 12 5 2 2 3. + <_> + + <_> + 4 5 6 2 -1. + <_> + 6 5 2 2 3. + <_> + + <_> + 8 1 4 6 -1. + <_> + 8 3 4 2 3. + <_> + + <_> + 0 2 3 6 -1. + <_> + 0 4 3 2 3. + <_> + + <_> + 6 6 8 3 -1. + <_> + 6 7 8 1 3. + <_> + + <_> + 0 1 5 9 -1. + <_> + 0 4 5 3 3. + <_> + + <_> + 16 0 4 15 -1. + <_> + 16 0 2 15 2. + <_> + + <_> + 1 10 3 2 -1. + <_> + 1 11 3 1 2. + <_> + + <_> + 14 4 1 10 -1. + <_> + 14 9 1 5 2. + <_> + + <_> + 0 1 4 12 -1. + <_> + 2 1 2 12 2. + <_> + + <_> + 11 11 4 2 -1. + <_> + 11 11 2 2 2. + <_> + + <_> + 5 11 4 2 -1. + <_> + 7 11 2 2 2. + <_> + + <_> + 3 8 15 5 -1. + <_> + 8 8 5 5 3. + <_> + + <_> + 0 0 6 10 -1. + <_> + 3 0 3 10 2. + <_> + + <_> + 11 4 3 2 -1. + <_> + 12 4 1 2 3. + <_> + + <_> + 8 12 3 8 -1. + <_> + 8 16 3 4 2. + <_> + + <_> + 8 14 5 3 -1. + <_> + 8 15 5 1 3. + <_> + + <_> + 7 14 4 3 -1. + <_> + 7 15 4 1 3. + <_> + + <_> + 11 4 3 2 -1. + <_> + 12 4 1 2 3. + <_> + + <_> + 3 15 14 4 -1. + <_> + 3 15 7 2 2. + <_> + 10 17 7 2 2. + <_> + + <_> + 2 2 16 4 -1. + <_> + 10 2 8 2 2. + <_> + 2 4 8 2 2. + <_> + + <_> + 0 8 6 12 -1. + <_> + 3 8 3 12 2. + <_> + + <_> + 5 7 10 2 -1. + <_> + 5 7 5 2 2. + <_> + + <_> + 9 7 2 5 -1. + <_> + 10 7 1 5 2. + <_> + + <_> + 13 7 6 4 -1. + <_> + 16 7 3 2 2. + <_> + 13 9 3 2 2. + <_> + + <_> + 0 13 8 2 -1. + <_> + 0 14 8 1 2. + <_> + + <_> + 13 7 6 4 -1. + <_> + 16 7 3 2 2. + <_> + 13 9 3 2 2. + <_> + + <_> + 1 7 6 4 -1. + <_> + 1 7 3 2 2. + <_> + 4 9 3 2 2. + <_> + + <_> + 12 6 1 12 -1. + <_> + 12 12 1 6 2. + <_> + + <_> + 9 5 2 6 -1. + <_> + 10 5 1 6 2. + <_> + + <_> + 14 12 2 3 -1. + <_> + 14 13 2 1 3. + <_> + + <_> + 4 12 2 3 -1. + <_> + 4 13 2 1 3. + <_> + + <_> + 8 12 4 3 -1. + <_> + 8 13 4 1 3. + <_> + + <_> + 5 2 2 4 -1. + <_> + 5 2 1 2 2. + <_> + 6 4 1 2 2. + <_> + + <_> + 5 5 11 3 -1. + <_> + 5 6 11 1 3. + <_> + + <_> + 7 6 4 12 -1. + <_> + 7 12 4 6 2. + <_> + + <_> + 12 13 8 5 -1. + <_> + 12 13 4 5 2. + <_> + + <_> + 7 6 1 12 -1. + <_> + 7 12 1 6 2. + <_> + + <_> + 1 2 6 3 -1. + <_> + 4 2 3 3 2. + <_> + + <_> + 9 5 6 10 -1. + <_> + 12 5 3 5 2. + <_> + 9 10 3 5 2. + <_> + + <_> + 5 5 8 12 -1. + <_> + 5 5 4 6 2. + <_> + 9 11 4 6 2. + <_> + + <_> + 0 7 20 6 -1. + <_> + 0 9 20 2 3. + <_> + + <_> + 4 2 2 2 -1. + <_> + 4 3 2 1 2. + <_> + + <_> + 4 18 12 2 -1. + <_> + 8 18 4 2 3. + <_> + + <_> + 7 4 4 16 -1. + <_> + 7 12 4 8 2. + <_> + + <_> + 7 6 7 8 -1. + <_> + 7 10 7 4 2. + <_> + + <_> + 6 3 3 1 -1. + <_> + 7 3 1 1 3. + <_> + + <_> + 11 15 2 4 -1. + <_> + 11 17 2 2 2. + <_> + + <_> + 3 5 4 8 -1. + <_> + 3 9 4 4 2. + <_> + + <_> + 7 1 6 12 -1. + <_> + 7 7 6 6 2. + <_> + + <_> + 4 6 6 2 -1. + <_> + 6 6 2 2 3. + <_> + + <_> + 16 4 4 6 -1. + <_> + 16 6 4 2 3. + <_> + + <_> + 3 3 5 2 -1. + <_> + 3 4 5 1 2. + <_> + + <_> + 9 11 2 3 -1. + <_> + 9 12 2 1 3. + <_> + + <_> + 2 16 4 2 -1. + <_> + 2 17 4 1 2. + <_> + + <_> + 7 13 6 6 -1. + <_> + 10 13 3 3 2. + <_> + 7 16 3 3 2. + <_> + + <_> + 7 0 3 4 -1. + <_> + 8 0 1 4 3. + <_> + + <_> + 8 15 4 3 -1. + <_> + 8 16 4 1 3. + <_> + + <_> + 0 4 4 6 -1. + <_> + 0 6 4 2 3. + <_> + + <_> + 5 6 12 3 -1. + <_> + 9 6 4 3 3. + <_> + + <_> + 7 6 6 14 -1. + <_> + 9 6 2 14 3. + <_> + + <_> + 9 7 3 3 -1. + <_> + 10 7 1 3 3. + <_> + + <_> + 6 12 2 4 -1. + <_> + 6 14 2 2 2. + <_> + + <_> + 10 12 7 6 -1. + <_> + 10 14 7 2 3. + <_> + + <_> + 1 0 15 2 -1. + <_> + 1 1 15 1 2. + <_> + + <_> + 14 0 6 6 -1. + <_> + 14 0 3 6 2. + <_> + + <_> + 5 3 3 1 -1. + <_> + 6 3 1 1 3. + <_> + + <_> + 14 0 6 6 -1. + <_> + 14 0 3 6 2. + <_> + + <_> + 0 3 20 10 -1. + <_> + 0 8 20 5 2. + <_> + + <_> + 14 0 6 6 -1. + <_> + 14 0 3 6 2. + <_> + + <_> + 0 0 6 6 -1. + <_> + 3 0 3 6 2. + <_> + + <_> + 19 15 1 2 -1. + <_> + 19 16 1 1 2. + <_> + + <_> + 0 2 4 8 -1. + <_> + 2 2 2 8 2. + <_> + + <_> + 2 1 18 4 -1. + <_> + 11 1 9 2 2. + <_> + 2 3 9 2 2. + <_> + + <_> + 8 12 1 2 -1. + <_> + 8 13 1 1 2. + <_> + + <_> + 5 2 10 6 -1. + <_> + 10 2 5 3 2. + <_> + 5 5 5 3 2. + <_> + + <_> + 9 7 2 4 -1. + <_> + 10 7 1 4 2. + <_> + + <_> + 9 7 3 3 -1. + <_> + 10 7 1 3 3. + <_> + + <_> + 4 5 12 8 -1. + <_> + 8 5 4 8 3. + <_> + + <_> + 15 15 4 3 -1. + <_> + 15 16 4 1 3. + <_> + + <_> + 8 18 3 1 -1. + <_> + 9 18 1 1 3. + <_> + + <_> + 9 13 4 3 -1. + <_> + 9 14 4 1 3. + <_> + + <_> + 7 13 4 3 -1. + <_> + 7 14 4 1 3. + <_> + + <_> + 19 15 1 2 -1. + <_> + 19 16 1 1 2. + <_> + + <_> + 0 15 8 4 -1. + <_> + 0 17 8 2 2. + <_> + + <_> + 9 3 6 4 -1. + <_> + 11 3 2 4 3. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 3 14 14 6 -1. + <_> + 3 16 14 2 3. + <_> + + <_> + 6 3 6 6 -1. + <_> + 6 6 6 3 2. + <_> + + <_> + 5 11 10 6 -1. + <_> + 5 14 10 3 2. + <_> + + <_> + 3 10 3 4 -1. + <_> + 4 10 1 4 3. + <_> + + <_> + 13 9 2 2 -1. + <_> + 13 9 1 2 2. + <_> + + <_> + 5 3 6 4 -1. + <_> + 7 3 2 4 3. + <_> + + <_> + 9 7 3 3 -1. + <_> + 10 7 1 3 3. + <_> + + <_> + 2 12 2 3 -1. + <_> + 2 13 2 1 3. + <_> + + <_> + 9 8 3 12 -1. + <_> + 9 12 3 4 3. + <_> + + <_> + 3 14 4 6 -1. + <_> + 3 14 2 3 2. + <_> + 5 17 2 3 2. + <_> + + <_> + 16 15 2 2 -1. + <_> + 16 16 2 1 2. + <_> + + <_> + 2 15 2 2 -1. + <_> + 2 16 2 1 2. + <_> + + <_> + 8 12 4 3 -1. + <_> + 8 13 4 1 3. + <_> + + <_> + 0 7 20 1 -1. + <_> + 10 7 10 1 2. + <_> + + <_> + 7 6 8 3 -1. + <_> + 7 6 4 3 2. + <_> + + <_> + 5 7 8 2 -1. + <_> + 9 7 4 2 2. + <_> + + <_> + 9 7 3 5 -1. + <_> + 10 7 1 5 3. + <_> + + <_> + 8 7 3 5 -1. + <_> + 9 7 1 5 3. + <_> + + <_> + 11 1 3 5 -1. + <_> + 12 1 1 5 3. + <_> + + <_> + 6 2 3 6 -1. + <_> + 7 2 1 6 3. + <_> + + <_> + 14 14 6 5 -1. + <_> + 14 14 3 5 2. + <_> + + <_> + 9 8 2 2 -1. + <_> + 9 9 2 1 2. + <_> + + <_> + 10 7 1 3 -1. + <_> + 10 8 1 1 3. + <_> + + <_> + 6 6 2 2 -1. + <_> + 6 6 1 1 2. + <_> + 7 7 1 1 2. + <_> + + <_> + 2 11 18 4 -1. + <_> + 11 11 9 2 2. + <_> + 2 13 9 2 2. + <_> + + <_> + 6 6 2 2 -1. + <_> + 6 6 1 1 2. + <_> + 7 7 1 1 2. + <_> + + <_> + 0 15 20 2 -1. + <_> + 0 16 20 1 2. + <_> + + <_> + 4 14 2 3 -1. + <_> + 4 15 2 1 3. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 8 7 2 3 -1. + <_> + 8 8 2 1 3. + <_> + + <_> + 9 10 2 3 -1. + <_> + 9 11 2 1 3. + <_> + + <_> + 5 4 10 4 -1. + <_> + 5 6 10 2 2. + <_> + + <_> + 9 7 6 4 -1. + <_> + 12 7 3 2 2. + <_> + 9 9 3 2 2. + <_> + + <_> + 4 7 3 6 -1. + <_> + 4 9 3 2 3. + <_> + + <_> + 11 15 4 4 -1. + <_> + 13 15 2 2 2. + <_> + 11 17 2 2 2. + <_> + + <_> + 7 8 4 2 -1. + <_> + 7 9 4 1 2. + <_> + + <_> + 13 1 4 3 -1. + <_> + 13 1 2 3 2. + <_> + + <_> + 5 15 4 4 -1. + <_> + 5 15 2 2 2. + <_> + 7 17 2 2 2. + <_> + + <_> + 9 5 4 7 -1. + <_> + 9 5 2 7 2. + <_> + + <_> + 5 6 8 3 -1. + <_> + 9 6 4 3 2. + <_> + + <_> + 9 9 2 2 -1. + <_> + 9 10 2 1 2. + <_> + + <_> + 7 15 5 3 -1. + <_> + 7 16 5 1 3. + <_> + + <_> + 11 10 4 3 -1. + <_> + 11 10 2 3 2. + <_> + + <_> + 6 9 8 10 -1. + <_> + 6 14 8 5 2. + <_> + + <_> + 10 11 6 2 -1. + <_> + 10 11 3 2 2. + <_> + + <_> + 4 11 6 2 -1. + <_> + 7 11 3 2 2. + <_> + + <_> + 11 3 8 1 -1. + <_> + 11 3 4 1 2. + <_> + + <_> + 6 3 3 2 -1. + <_> + 7 3 1 2 3. + <_> + + <_> + 14 5 6 5 -1. + <_> + 14 5 3 5 2. + <_> + + <_> + 7 5 2 12 -1. + <_> + 7 11 2 6 2. + <_> + + <_> + 8 11 4 3 -1. + <_> + 8 12 4 1 3. + <_> + + <_> + 4 1 2 3 -1. + <_> + 5 1 1 3 2. + <_> + + <_> + 18 3 2 6 -1. + <_> + 18 5 2 2 3. + <_> + + <_> + 0 3 2 6 -1. + <_> + 0 5 2 2 3. + <_> + + <_> + 9 12 2 3 -1. + <_> + 9 13 2 1 3. + <_> + + <_> + 7 13 4 3 -1. + <_> + 7 14 4 1 3. + <_> + + <_> + 18 0 2 6 -1. + <_> + 18 2 2 2 3. + <_> + + <_> + 0 0 2 6 -1. + <_> + 0 2 2 2 3. + <_> + + <_> + 8 14 6 3 -1. + <_> + 8 15 6 1 3. + <_> + + <_> + 7 4 2 4 -1. + <_> + 8 4 1 4 2. + <_> + + <_> + 8 5 4 6 -1. + <_> + 8 7 4 2 3. + <_> + + <_> + 6 4 2 2 -1. + <_> + 7 4 1 2 2. + <_> + + <_> + 3 14 14 4 -1. + <_> + 10 14 7 2 2. + <_> + 3 16 7 2 2. + <_> + + <_> + 6 15 6 2 -1. + <_> + 6 15 3 1 2. + <_> + 9 16 3 1 2. + <_> + + <_> + 14 15 6 2 -1. + <_> + 14 16 6 1 2. + <_> + + <_> + 2 12 12 8 -1. + <_> + 2 16 12 4 2. + <_> + + <_> + 7 7 7 2 -1. + <_> + 7 8 7 1 2. + <_> + + <_> + 0 2 18 2 -1. + <_> + 0 3 18 1 2. + <_> + + <_> + 9 6 2 5 -1. + <_> + 9 6 1 5 2. + <_> + + <_> + 7 5 3 8 -1. + <_> + 8 5 1 8 3. + <_> + + <_> + 9 6 3 4 -1. + <_> + 10 6 1 4 3. + <_> + + <_> + 4 13 3 2 -1. + <_> + 4 14 3 1 2. + <_> + + <_> + 9 4 6 3 -1. + <_> + 11 4 2 3 3. + <_> + + <_> + 5 4 6 3 -1. + <_> + 7 4 2 3 3. + <_> + + <_> + 14 11 5 2 -1. + <_> + 14 12 5 1 2. + <_> + + <_> + 1 2 6 9 -1. + <_> + 3 2 2 9 3. + <_> + + <_> + 14 6 6 13 -1. + <_> + 14 6 3 13 2. + <_> + + <_> + 3 6 14 8 -1. + <_> + 3 6 7 4 2. + <_> + 10 10 7 4 2. + <_> + + <_> + 16 0 4 11 -1. + <_> + 16 0 2 11 2. + <_> + + <_> + 3 4 12 12 -1. + <_> + 3 4 6 6 2. + <_> + 9 10 6 6 2. + <_> + + <_> + 11 4 5 3 -1. + <_> + 11 5 5 1 3. + <_> + + <_> + 4 11 4 2 -1. + <_> + 4 12 4 1 2. + <_> + + <_> + 10 7 2 2 -1. + <_> + 10 7 1 2 2. + <_> + + <_> + 8 7 2 2 -1. + <_> + 9 7 1 2 2. + <_> + + <_> + 9 17 3 2 -1. + <_> + 10 17 1 2 3. + <_> + + <_> + 5 6 3 3 -1. + <_> + 5 7 3 1 3. + <_> + + <_> + 10 0 3 3 -1. + <_> + 11 0 1 3 3. + <_> + + <_> + 5 6 6 2 -1. + <_> + 5 6 3 1 2. + <_> + 8 7 3 1 2. + <_> + + <_> + 12 16 4 3 -1. + <_> + 12 17 4 1 3. + <_> + + <_> + 3 12 3 2 -1. + <_> + 3 13 3 1 2. + <_> + + <_> + 9 12 3 2 -1. + <_> + 9 13 3 1 2. + <_> + + <_> + 1 11 16 4 -1. + <_> + 1 11 8 2 2. + <_> + 9 13 8 2 2. + <_> + + <_> + 12 4 3 3 -1. + <_> + 12 5 3 1 3. + <_> + + <_> + 4 4 5 3 -1. + <_> + 4 5 5 1 3. + <_> + + <_> + 12 16 4 3 -1. + <_> + 12 17 4 1 3. + <_> + + <_> + 5 4 3 3 -1. + <_> + 5 5 3 1 3. + <_> + + <_> + 9 0 2 2 -1. + <_> + 9 1 2 1 2. + <_> + + <_> + 8 9 4 2 -1. + <_> + 8 10 4 1 2. + <_> + + <_> + 8 8 4 3 -1. + <_> + 8 9 4 1 3. + <_> + + <_> + 0 13 6 3 -1. + <_> + 2 13 2 3 3. + <_> + + <_> + 16 14 3 2 -1. + <_> + 16 15 3 1 2. + <_> + + <_> + 1 18 18 2 -1. + <_> + 7 18 6 2 3. + <_> + + <_> + 16 14 3 2 -1. + <_> + 16 15 3 1 2. + <_> + + <_> + 1 14 3 2 -1. + <_> + 1 15 3 1 2. + <_> + + <_> + 7 14 6 3 -1. + <_> + 7 15 6 1 3. + <_> + + <_> + 5 14 8 3 -1. + <_> + 5 15 8 1 3. + <_> + + <_> + 10 6 4 14 -1. + <_> + 10 6 2 14 2. + <_> + + <_> + 6 6 4 14 -1. + <_> + 8 6 2 14 2. + <_> + + <_> + 13 5 2 3 -1. + <_> + 13 6 2 1 3. + <_> + + <_> + 7 16 6 1 -1. + <_> + 9 16 2 1 3. + <_> + + <_> + 9 12 3 3 -1. + <_> + 9 13 3 1 3. + <_> + + <_> + 7 0 3 3 -1. + <_> + 8 0 1 3 3. + <_> + + <_> + 4 0 16 18 -1. + <_> + 4 9 16 9 2. + <_> + + <_> + 1 1 16 14 -1. + <_> + 1 8 16 7 2. + <_> + + <_> + 3 9 15 4 -1. + <_> + 8 9 5 4 3. + <_> + + <_> + 6 12 7 3 -1. + <_> + 6 13 7 1 3. + <_> + + <_> + 14 15 2 3 -1. + <_> + 14 16 2 1 3. + <_> + + <_> + 2 3 16 14 -1. + <_> + 2 3 8 7 2. + <_> + 10 10 8 7 2. + <_> + + <_> + 16 2 4 18 -1. + <_> + 18 2 2 9 2. + <_> + 16 11 2 9 2. + <_> + + <_> + 4 15 2 3 -1. + <_> + 4 16 2 1 3. + <_> + + <_> + 16 2 4 18 -1. + <_> + 18 2 2 9 2. + <_> + 16 11 2 9 2. + <_> + + <_> + 1 1 8 3 -1. + <_> + 1 2 8 1 3. + <_> + + <_> + 8 11 4 3 -1. + <_> + 8 12 4 1 3. + <_> + + <_> + 5 11 5 9 -1. + <_> + 5 14 5 3 3. + <_> + + <_> + 16 0 4 11 -1. + <_> + 16 0 2 11 2. + <_> + + <_> + 7 0 6 1 -1. + <_> + 9 0 2 1 3. + <_> + + <_> + 16 3 3 7 -1. + <_> + 17 3 1 7 3. + <_> + + <_> + 1 3 3 7 -1. + <_> + 2 3 1 7 3. + <_> + + <_> + 7 8 6 12 -1. + <_> + 7 12 6 4 3. + <_> + + <_> + 0 0 4 11 -1. + <_> + 2 0 2 11 2. + <_> + + <_> + 14 0 6 20 -1. + <_> + 14 0 3 20 2. + <_> + + <_> + 0 3 1 2 -1. + <_> + 0 4 1 1 2. + <_> + + <_> + 5 5 10 8 -1. + <_> + 10 5 5 4 2. + <_> + 5 9 5 4 2. + <_> + + <_> + 4 7 12 4 -1. + <_> + 4 7 6 2 2. + <_> + 10 9 6 2 2. + <_> + + <_> + 2 1 6 4 -1. + <_> + 5 1 3 4 2. + <_> + + <_> + 9 7 6 4 -1. + <_> + 12 7 3 2 2. + <_> + 9 9 3 2 2. + <_> + + <_> + 5 6 2 6 -1. + <_> + 5 9 2 3 2. + <_> + + <_> + 9 16 6 4 -1. + <_> + 12 16 3 2 2. + <_> + 9 18 3 2 2. + <_> + + <_> + 9 4 2 12 -1. + <_> + 9 10 2 6 2. + <_> + + <_> + 7 1 6 18 -1. + <_> + 9 1 2 18 3. + <_> + + <_> + 4 12 12 2 -1. + <_> + 8 12 4 2 3. + <_> + + <_> + 8 8 6 2 -1. + <_> + 8 9 6 1 2. + <_> + + <_> + 8 0 3 6 -1. + <_> + 9 0 1 6 3. + <_> + + <_> + 11 18 3 2 -1. + <_> + 11 19 3 1 2. + <_> + + <_> + 1 1 17 4 -1. + <_> + 1 3 17 2 2. + <_> + + <_> + 11 8 4 12 -1. + <_> + 11 8 2 12 2. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 12 3 2 17 -1. + <_> + 12 3 1 17 2. + <_> + + <_> + 4 7 6 1 -1. + <_> + 6 7 2 1 3. + <_> + + <_> + 18 3 2 3 -1. + <_> + 18 4 2 1 3. + <_> + + <_> + 8 4 3 4 -1. + <_> + 8 6 3 2 2. + <_> + + <_> + 4 5 12 10 -1. + <_> + 4 10 12 5 2. + <_> + + <_> + 5 18 4 2 -1. + <_> + 7 18 2 2 2. + <_> + + <_> + 17 2 3 6 -1. + <_> + 17 4 3 2 3. + <_> + + <_> + 7 7 6 6 -1. + <_> + 9 7 2 6 3. + <_> + + <_> + 17 2 3 6 -1. + <_> + 17 4 3 2 3. + <_> + + <_> + 8 0 3 4 -1. + <_> + 9 0 1 4 3. + <_> + + <_> + 9 14 2 3 -1. + <_> + 9 15 2 1 3. + <_> + + <_> + 0 12 6 3 -1. + <_> + 0 13 6 1 3. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 3 12 2 3 -1. + <_> + 3 13 2 1 3. + <_> + + <_> + 5 6 12 7 -1. + <_> + 9 6 4 7 3. + <_> + + <_> + 0 2 3 6 -1. + <_> + 0 4 3 2 3. + <_> + + <_> + 14 6 1 3 -1. + <_> + 14 7 1 1 3. + <_> + + <_> + 2 0 3 14 -1. + <_> + 3 0 1 14 3. + <_> + + <_> + 12 14 5 6 -1. + <_> + 12 16 5 2 3. + <_> + + <_> + 4 14 5 6 -1. + <_> + 4 16 5 2 3. + <_> + + <_> + 11 10 2 2 -1. + <_> + 12 10 1 1 2. + <_> + 11 11 1 1 2. + <_> + + <_> + 5 0 3 14 -1. + <_> + 6 0 1 14 3. + <_> + + <_> + 10 15 2 3 -1. + <_> + 10 16 2 1 3. + <_> + + <_> + 0 2 2 3 -1. + <_> + 0 3 2 1 3. + <_> + + <_> + 5 11 12 6 -1. + <_> + 5 14 12 3 2. + <_> + + <_> + 6 11 3 9 -1. + <_> + 6 14 3 3 3. + <_> + + <_> + 11 10 2 2 -1. + <_> + 12 10 1 1 2. + <_> + 11 11 1 1 2. + <_> + + <_> + 5 6 1 3 -1. + <_> + 5 7 1 1 3. + <_> + + <_> + 4 9 13 3 -1. + <_> + 4 10 13 1 3. + <_> + + <_> + 1 7 15 6 -1. + <_> + 6 7 5 6 3. + <_> + + <_> + 4 5 12 6 -1. + <_> + 8 5 4 6 3. + <_> + + <_> + 8 10 4 3 -1. + <_> + 8 11 4 1 3. + <_> + + <_> + 15 14 1 3 -1. + <_> + 15 15 1 1 3. + <_> + + <_> + 1 11 5 3 -1. + <_> + 1 12 5 1 3. + <_> + + <_> + 7 1 7 12 -1. + <_> + 7 7 7 6 2. + <_> + + <_> + 0 1 6 10 -1. + <_> + 0 1 3 5 2. + <_> + 3 6 3 5 2. + <_> + + <_> + 16 1 4 3 -1. + <_> + 16 2 4 1 3. + <_> + + <_> + 5 5 2 3 -1. + <_> + 5 6 2 1 3. + <_> + + <_> + 12 2 3 5 -1. + <_> + 13 2 1 5 3. + <_> + + <_> + 0 3 4 6 -1. + <_> + 0 5 4 2 3. + <_> + + <_> + 8 12 4 2 -1. + <_> + 8 13 4 1 2. + <_> + + <_> + 8 18 3 1 -1. + <_> + 9 18 1 1 3. + <_> + + <_> + 11 10 2 2 -1. + <_> + 12 10 1 1 2. + <_> + 11 11 1 1 2. + <_> + + <_> + 7 10 2 2 -1. + <_> + 7 10 1 1 2. + <_> + 8 11 1 1 2. + <_> + + <_> + 11 11 4 4 -1. + <_> + 11 13 4 2 2. + <_> + + <_> + 8 12 3 8 -1. + <_> + 9 12 1 8 3. + <_> + + <_> + 13 0 6 3 -1. + <_> + 13 1 6 1 3. + <_> + + <_> + 8 8 3 4 -1. + <_> + 9 8 1 4 3. + <_> + + <_> + 5 7 10 10 -1. + <_> + 10 7 5 5 2. + <_> + 5 12 5 5 2. + <_> + + <_> + 3 18 8 2 -1. + <_> + 3 18 4 1 2. + <_> + 7 19 4 1 2. + <_> + + <_> + 10 2 6 8 -1. + <_> + 12 2 2 8 3. + <_> + + <_> + 4 2 6 8 -1. + <_> + 6 2 2 8 3. + <_> + + <_> + 11 0 3 7 -1. + <_> + 12 0 1 7 3. + <_> + + <_> + 7 11 2 1 -1. + <_> + 8 11 1 1 2. + <_> + + <_> + 15 14 1 3 -1. + <_> + 15 15 1 1 3. + <_> + + <_> + 7 15 2 2 -1. + <_> + 7 15 1 1 2. + <_> + 8 16 1 1 2. + <_> + + <_> + 15 14 1 3 -1. + <_> + 15 15 1 1 3. + <_> + + <_> + 6 0 3 7 -1. + <_> + 7 0 1 7 3. + <_> + + <_> + 18 1 2 7 -1. + <_> + 18 1 1 7 2. + <_> + + <_> + 2 0 8 20 -1. + <_> + 2 10 8 10 2. + <_> + + <_> + 3 0 15 6 -1. + <_> + 3 2 15 2 3. + <_> + + <_> + 4 3 12 2 -1. + <_> + 4 4 12 1 2. + <_> + + <_> + 16 0 4 5 -1. + <_> + 16 0 2 5 2. + <_> + + <_> + 7 0 3 4 -1. + <_> + 8 0 1 4 3. + <_> + + <_> + 16 0 4 5 -1. + <_> + 16 0 2 5 2. + <_> + + <_> + 1 7 6 13 -1. + <_> + 3 7 2 13 3. + <_> + + <_> + 16 0 4 5 -1. + <_> + 16 0 2 5 2. + <_> + + <_> + 0 0 4 5 -1. + <_> + 2 0 2 5 2. + <_> + + <_> + 14 12 3 6 -1. + <_> + 14 14 3 2 3. + <_> + + <_> + 3 12 3 6 -1. + <_> + 3 14 3 2 3. + <_> + + <_> + 16 1 4 3 -1. + <_> + 16 2 4 1 3. + <_> + + <_> + 8 7 2 10 -1. + <_> + 8 7 1 5 2. + <_> + 9 12 1 5 2. + <_> + + <_> + 11 11 4 4 -1. + <_> + 11 13 4 2 2. + <_> + + <_> + 0 1 4 3 -1. + <_> + 0 2 4 1 3. + <_> + + <_> + 13 4 1 3 -1. + <_> + 13 5 1 1 3. + <_> + + <_> + 7 15 3 5 -1. + <_> + 8 15 1 5 3. + <_> + + <_> + 9 7 3 5 -1. + <_> + 10 7 1 5 3. + <_> + + <_> + 8 7 3 5 -1. + <_> + 9 7 1 5 3. + <_> + + <_> + 10 6 4 14 -1. + <_> + 10 6 2 14 2. + <_> + + <_> + 0 5 5 6 -1. + <_> + 0 7 5 2 3. + <_> + + <_> + 9 5 6 4 -1. + <_> + 9 5 3 4 2. + <_> + + <_> + 0 0 18 10 -1. + <_> + 6 0 6 10 3. + <_> + + <_> + 10 6 4 14 -1. + <_> + 10 6 2 14 2. + <_> + + <_> + 6 6 4 14 -1. + <_> + 8 6 2 14 2. + <_> + + <_> + 13 4 1 3 -1. + <_> + 13 5 1 1 3. + <_> + + <_> + 5 1 2 3 -1. + <_> + 6 1 1 3 2. + <_> + + <_> + 18 1 2 18 -1. + <_> + 19 1 1 9 2. + <_> + 18 10 1 9 2. + <_> + + <_> + 2 1 4 3 -1. + <_> + 2 2 4 1 3. + <_> + + <_> + 18 1 2 18 -1. + <_> + 19 1 1 9 2. + <_> + 18 10 1 9 2. + <_> + + <_> + 1 14 4 6 -1. + <_> + 1 14 2 3 2. + <_> + 3 17 2 3 2. + <_> + + <_> + 10 11 7 6 -1. + <_> + 10 13 7 2 3. + <_> + + <_> + 0 10 6 10 -1. + <_> + 0 10 3 5 2. + <_> + 3 15 3 5 2. + <_> + + <_> + 11 0 3 4 -1. + <_> + 12 0 1 4 3. + <_> + + <_> + 5 10 5 6 -1. + <_> + 5 13 5 3 2. + <_> + + <_> + 14 6 1 8 -1. + <_> + 14 10 1 4 2. + <_> + + <_> + 1 7 18 6 -1. + <_> + 1 7 9 3 2. + <_> + 10 10 9 3 2. + <_> + + <_> + 9 7 2 2 -1. + <_> + 9 7 1 2 2. + <_> + + <_> + 5 9 4 5 -1. + <_> + 7 9 2 5 2. + <_> + + <_> + 7 6 6 3 -1. + <_> + 9 6 2 3 3. + <_> + + <_> + 1 0 18 4 -1. + <_> + 7 0 6 4 3. + <_> + + <_> + 7 15 2 4 -1. + <_> + 7 17 2 2 2. + <_> + + <_> + 1 0 19 9 -1. + <_> + 1 3 19 3 3. + <_> + + <_> + 3 7 3 6 -1. + <_> + 3 9 3 2 3. + <_> + + <_> + 13 7 4 4 -1. + <_> + 15 7 2 2 2. + <_> + 13 9 2 2 2. + <_> + + <_> + 3 7 4 4 -1. + <_> + 3 7 2 2 2. + <_> + 5 9 2 2 2. + <_> + + <_> + 9 6 10 8 -1. + <_> + 9 10 10 4 2. + <_> + + <_> + 3 8 14 12 -1. + <_> + 3 14 14 6 2. + <_> + + <_> + 6 5 10 12 -1. + <_> + 11 5 5 6 2. + <_> + 6 11 5 6 2. + <_> + + <_> + 9 11 2 3 -1. + <_> + 9 12 2 1 3. + <_> + + <_> + 9 5 6 5 -1. + <_> + 9 5 3 5 2. + <_> + + <_> + 9 4 2 4 -1. + <_> + 9 6 2 2 2. + <_> + + <_> + 9 5 6 5 -1. + <_> + 9 5 3 5 2. + <_> + + <_> + 5 5 6 5 -1. + <_> + 8 5 3 5 2. + <_> + + <_> + 11 2 6 1 -1. + <_> + 13 2 2 1 3. + <_> + + <_> + 3 2 6 1 -1. + <_> + 5 2 2 1 3. + <_> + + <_> + 13 5 2 3 -1. + <_> + 13 6 2 1 3. + <_> + + <_> + 0 10 1 4 -1. + <_> + 0 12 1 2 2. + <_> + + <_> + 13 5 2 3 -1. + <_> + 13 6 2 1 3. + <_> + + <_> + 8 18 3 2 -1. + <_> + 9 18 1 2 3. + <_> + + <_> + 6 15 9 2 -1. + <_> + 6 16 9 1 2. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 18 4 2 4 -1. + <_> + 18 6 2 2 2. + <_> + + <_> + 5 5 2 3 -1. + <_> + 5 6 2 1 3. + <_> + + <_> + 15 16 3 2 -1. + <_> + 15 17 3 1 2. + <_> + + <_> + 0 0 3 9 -1. + <_> + 0 3 3 3 3. + <_> + + <_> + 9 7 3 3 -1. + <_> + 9 8 3 1 3. + <_> + + <_> + 8 7 3 3 -1. + <_> + 8 8 3 1 3. + <_> + + <_> + 9 5 2 6 -1. + <_> + 9 5 1 6 2. + <_> + + <_> + 8 6 3 4 -1. + <_> + 9 6 1 4 3. + <_> + + <_> + 7 6 8 12 -1. + <_> + 11 6 4 6 2. + <_> + 7 12 4 6 2. + <_> + + <_> + 5 6 8 12 -1. + <_> + 5 6 4 6 2. + <_> + 9 12 4 6 2. + <_> + + <_> + 12 4 3 3 -1. + <_> + 12 5 3 1 3. + <_> + + <_> + 2 16 3 2 -1. + <_> + 2 17 3 1 2. + <_> + + <_> + 12 4 3 3 -1. + <_> + 12 5 3 1 3. + <_> + + <_> + 2 12 6 6 -1. + <_> + 2 14 6 2 3. + <_> + + <_> + 7 13 6 3 -1. + <_> + 7 14 6 1 3. + <_> + + <_> + 6 14 6 3 -1. + <_> + 6 15 6 1 3. + <_> + + <_> + 14 15 5 3 -1. + <_> + 14 16 5 1 3. + <_> + + <_> + 5 4 3 3 -1. + <_> + 5 5 3 1 3. + <_> + + <_> + 14 15 5 3 -1. + <_> + 14 16 5 1 3. + <_> + + <_> + 5 3 6 2 -1. + <_> + 7 3 2 2 3. + <_> + + <_> + 8 15 4 3 -1. + <_> + 8 16 4 1 3. + <_> + + <_> + 1 15 5 3 -1. + <_> + 1 16 5 1 3. + <_> + + <_> + 8 13 4 6 -1. + <_> + 10 13 2 3 2. + <_> + 8 16 2 3 2. + <_> + + <_> + 7 8 3 3 -1. + <_> + 8 8 1 3 3. + <_> + + <_> + 12 0 5 4 -1. + <_> + 12 2 5 2 2. + <_> + + <_> + 0 2 20 2 -1. + <_> + 0 2 10 1 2. + <_> + 10 3 10 1 2. + <_> + + <_> + 1 0 18 4 -1. + <_> + 7 0 6 4 3. + <_> + + <_> + 4 3 6 1 -1. + <_> + 6 3 2 1 3. + <_> + + <_> + 4 18 13 2 -1. + <_> + 4 19 13 1 2. + <_> + + <_> + 2 10 3 6 -1. + <_> + 2 12 3 2 3. + <_> + + <_> + 14 12 6 8 -1. + <_> + 17 12 3 4 2. + <_> + 14 16 3 4 2. + <_> + + <_> + 4 13 10 6 -1. + <_> + 4 13 5 3 2. + <_> + 9 16 5 3 2. + <_> + + <_> + 14 12 1 2 -1. + <_> + 14 13 1 1 2. + <_> + + <_> + 8 13 4 3 -1. + <_> + 8 14 4 1 3. + <_> + + <_> + 14 12 2 2 -1. + <_> + 14 13 2 1 2. + <_> + + <_> + 4 12 2 2 -1. + <_> + 4 13 2 1 2. + <_> + + <_> + 8 12 9 2 -1. + <_> + 8 13 9 1 2. + <_> + + <_> + 9 14 2 3 -1. + <_> + 9 15 2 1 3. + <_> + + <_> + 11 10 3 6 -1. + <_> + 11 13 3 3 2. + <_> + + <_> + 5 6 9 12 -1. + <_> + 5 12 9 6 2. + <_> + + <_> + 11 10 3 6 -1. + <_> + 11 13 3 3 2. + <_> + + <_> + 6 10 3 6 -1. + <_> + 6 13 3 3 2. + <_> + + <_> + 5 4 11 3 -1. + <_> + 5 5 11 1 3. + <_> + + <_> + 7 1 5 10 -1. + <_> + 7 6 5 5 2. + <_> + + <_> + 2 8 18 2 -1. + <_> + 2 9 18 1 2. + <_> + + <_> + 7 17 5 3 -1. + <_> + 7 18 5 1 3. + <_> + + <_> + 5 9 12 1 -1. + <_> + 9 9 4 1 3. + <_> + + <_> + 0 14 6 6 -1. + <_> + 0 14 3 3 2. + <_> + 3 17 3 3 2. + <_> + + <_> + 5 9 12 1 -1. + <_> + 9 9 4 1 3. + <_> + + <_> + 3 9 12 1 -1. + <_> + 7 9 4 1 3. + <_> + + <_> + 14 10 6 7 -1. + <_> + 14 10 3 7 2. + <_> + + <_> + 1 0 16 2 -1. + <_> + 1 1 16 1 2. + <_> + + <_> + 10 9 10 9 -1. + <_> + 10 12 10 3 3. + <_> + + <_> + 0 1 10 2 -1. + <_> + 5 1 5 2 2. + <_> + + <_> + 17 3 2 3 -1. + <_> + 17 4 2 1 3. + <_> + + <_> + 1 3 2 3 -1. + <_> + 1 4 2 1 3. + <_> + + <_> + 9 7 3 6 -1. + <_> + 10 7 1 6 3. + <_> + + <_> + 6 5 4 3 -1. + <_> + 8 5 2 3 2. + <_> + + <_> + 7 5 6 6 -1. + <_> + 9 5 2 6 3. + <_> + + <_> + 3 4 12 12 -1. + <_> + 3 4 6 6 2. + <_> + 9 10 6 6 2. + <_> + + <_> + 9 2 6 15 -1. + <_> + 11 2 2 15 3. + <_> + + <_> + 2 2 6 17 -1. + <_> + 4 2 2 17 3. + <_> + + <_> + 14 10 6 7 -1. + <_> + 14 10 3 7 2. + <_> + + <_> + 0 10 6 7 -1. + <_> + 3 10 3 7 2. + <_> + + <_> + 9 2 6 15 -1. + <_> + 11 2 2 15 3. + <_> + + <_> + 5 2 6 15 -1. + <_> + 7 2 2 15 3. + <_> + + <_> + 17 9 3 6 -1. + <_> + 17 11 3 2 3. + <_> + + <_> + 6 7 6 6 -1. + <_> + 8 7 2 6 3. + <_> + + <_> + 1 10 18 6 -1. + <_> + 10 10 9 3 2. + <_> + 1 13 9 3 2. + <_> + + <_> + 0 9 10 9 -1. + <_> + 0 12 10 3 3. + <_> + + <_> + 8 15 4 3 -1. + <_> + 8 16 4 1 3. + <_> + + <_> + 5 12 3 4 -1. + <_> + 5 14 3 2 2. + <_> + + <_> + 3 3 16 12 -1. + <_> + 3 9 16 6 2. + <_> + + <_> + 1 1 12 12 -1. + <_> + 1 1 6 6 2. + <_> + 7 7 6 6 2. + <_> + + <_> + 10 4 2 4 -1. + <_> + 11 4 1 2 2. + <_> + 10 6 1 2 2. + <_> + + <_> + 0 9 10 2 -1. + <_> + 0 9 5 1 2. + <_> + 5 10 5 1 2. + <_> + + <_> + 9 11 3 3 -1. + <_> + 9 12 3 1 3. + <_> + + <_> + 3 12 9 2 -1. + <_> + 3 13 9 1 2. + <_> + + <_> + 9 9 2 2 -1. + <_> + 9 10 2 1 2. + <_> + + <_> + 3 4 13 6 -1. + <_> + 3 6 13 2 3. + <_> + + <_> + 9 7 6 4 -1. + <_> + 12 7 3 2 2. + <_> + 9 9 3 2 2. + <_> + + <_> + 1 0 6 8 -1. + <_> + 4 0 3 8 2. + <_> + + <_> + 9 5 2 12 -1. + <_> + 9 11 2 6 2. + <_> + + <_> + 4 4 3 10 -1. + <_> + 4 9 3 5 2. + <_> + + <_> + 6 17 8 3 -1. + <_> + 6 18 8 1 3. + <_> + + <_> + 0 5 10 6 -1. + <_> + 0 7 10 2 3. + <_> + + <_> + 13 2 3 2 -1. + <_> + 13 3 3 1 2. + <_> + + <_> + 7 5 4 5 -1. + <_> + 9 5 2 5 2. + <_> + + <_> + 12 14 3 6 -1. + <_> + 12 16 3 2 3. + <_> + + <_> + 1 11 8 2 -1. + <_> + 1 12 8 1 2. + <_> + + <_> + 7 13 6 3 -1. + <_> + 7 14 6 1 3. + <_> + + <_> + 0 5 3 6 -1. + <_> + 0 7 3 2 3. + <_> + + <_> + 13 2 3 2 -1. + <_> + 13 3 3 1 2. + <_> + + <_> + 4 14 4 6 -1. + <_> + 4 14 2 3 2. + <_> + 6 17 2 3 2. + <_> + + <_> + 13 2 3 2 -1. + <_> + 13 3 3 1 2. + <_> + + <_> + 8 2 4 12 -1. + <_> + 8 6 4 4 3. + <_> + + <_> + 14 0 6 8 -1. + <_> + 17 0 3 4 2. + <_> + 14 4 3 4 2. + <_> + + <_> + 7 17 3 2 -1. + <_> + 8 17 1 2 3. + <_> + + <_> + 8 12 4 2 -1. + <_> + 8 13 4 1 2. + <_> + + <_> + 6 0 8 12 -1. + <_> + 6 0 4 6 2. + <_> + 10 6 4 6 2. + <_> + + <_> + 14 0 2 10 -1. + <_> + 15 0 1 5 2. + <_> + 14 5 1 5 2. + <_> + + <_> + 5 3 8 6 -1. + <_> + 5 3 4 3 2. + <_> + 9 6 4 3 2. + <_> + + <_> + 14 0 6 10 -1. + <_> + 17 0 3 5 2. + <_> + 14 5 3 5 2. + <_> + + <_> + 9 14 1 2 -1. + <_> + 9 15 1 1 2. + <_> + + <_> + 15 10 4 3 -1. + <_> + 15 11 4 1 3. + <_> + + <_> + 8 14 2 3 -1. + <_> + 8 15 2 1 3. + <_> + + <_> + 3 13 14 4 -1. + <_> + 10 13 7 2 2. + <_> + 3 15 7 2 2. + <_> + + <_> + 1 10 4 3 -1. + <_> + 1 11 4 1 3. + <_> + + <_> + 9 11 6 1 -1. + <_> + 11 11 2 1 3. + <_> + + <_> + 5 11 6 1 -1. + <_> + 7 11 2 1 3. + <_> + + <_> + 3 5 16 15 -1. + <_> + 3 10 16 5 3. + <_> + + <_> + 6 12 4 2 -1. + <_> + 8 12 2 2 2. + <_> + + <_> + 4 4 12 10 -1. + <_> + 10 4 6 5 2. + <_> + 4 9 6 5 2. + <_> + + <_> + 8 6 3 4 -1. + <_> + 9 6 1 4 3. + <_> + + <_> + 8 12 4 8 -1. + <_> + 10 12 2 4 2. + <_> + 8 16 2 4 2. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 12 2 3 2 -1. + <_> + 13 2 1 2 3. + <_> + + <_> + 8 15 3 2 -1. + <_> + 8 16 3 1 2. + <_> + + <_> + 6 0 9 14 -1. + <_> + 9 0 3 14 3. + <_> + + <_> + 9 6 2 3 -1. + <_> + 10 6 1 3 2. + <_> + + <_> + 10 8 2 3 -1. + <_> + 10 9 2 1 3. + <_> + + <_> + 0 9 4 6 -1. + <_> + 0 11 4 2 3. + <_> + + <_> + 6 0 8 2 -1. + <_> + 6 1 8 1 2. + <_> + + <_> + 6 14 7 3 -1. + <_> + 6 15 7 1 3. + <_> + + <_> + 8 10 8 9 -1. + <_> + 8 13 8 3 3. + <_> + + <_> + 5 2 3 2 -1. + <_> + 6 2 1 2 3. + <_> + + <_> + 14 1 6 8 -1. + <_> + 17 1 3 4 2. + <_> + 14 5 3 4 2. + <_> + + <_> + 0 1 6 8 -1. + <_> + 0 1 3 4 2. + <_> + 3 5 3 4 2. + <_> + + <_> + 1 2 18 6 -1. + <_> + 10 2 9 3 2. + <_> + 1 5 9 3 2. + <_> + + <_> + 9 3 2 1 -1. + <_> + 10 3 1 1 2. + <_> + + <_> + 13 2 4 6 -1. + <_> + 15 2 2 3 2. + <_> + 13 5 2 3 2. + <_> + + <_> + 5 4 3 3 -1. + <_> + 5 5 3 1 3. + <_> + + <_> + 13 5 1 3 -1. + <_> + 13 6 1 1 3. + <_> + + <_> + 2 16 5 3 -1. + <_> + 2 17 5 1 3. + <_> + + <_> + 13 2 4 6 -1. + <_> + 15 2 2 3 2. + <_> + 13 5 2 3 2. + <_> + + <_> + 3 2 4 6 -1. + <_> + 3 2 2 3 2. + <_> + 5 5 2 3 2. + <_> + + <_> + 13 5 1 2 -1. + <_> + 13 6 1 1 2. + <_> + + <_> + 5 5 2 2 -1. + <_> + 5 6 2 1 2. + <_> + + <_> + 13 9 2 2 -1. + <_> + 13 9 1 2 2. + <_> + + <_> + 5 9 2 2 -1. + <_> + 6 9 1 2 2. + <_> + + <_> + 13 17 3 2 -1. + <_> + 13 18 3 1 2. + <_> + + <_> + 6 16 4 4 -1. + <_> + 6 16 2 2 2. + <_> + 8 18 2 2 2. + <_> + + <_> + 9 16 2 3 -1. + <_> + 9 17 2 1 3. + <_> + + <_> + 0 13 9 6 -1. + <_> + 0 15 9 2 3. + <_> + + <_> + 9 14 2 6 -1. + <_> + 9 17 2 3 2. + <_> + + <_> + 9 15 2 3 -1. + <_> + 9 16 2 1 3. + <_> + + <_> + 1 10 18 6 -1. + <_> + 1 12 18 2 3. + <_> + + <_> + 8 11 4 2 -1. + <_> + 8 12 4 1 2. + <_> + + <_> + 7 9 6 2 -1. + <_> + 7 10 6 1 2. + <_> + + <_> + 8 8 2 3 -1. + <_> + 8 9 2 1 3. + <_> + + <_> + 17 5 3 4 -1. + <_> + 18 5 1 4 3. + <_> + + <_> + 1 19 18 1 -1. + <_> + 7 19 6 1 3. + <_> + + <_> + 9 0 3 2 -1. + <_> + 10 0 1 2 3. + <_> + + <_> + 1 8 1 6 -1. + <_> + 1 10 1 2 3. + <_> + + <_> + 12 17 8 3 -1. + <_> + 12 17 4 3 2. + <_> + + <_> + 0 5 3 4 -1. + <_> + 1 5 1 4 3. + <_> + + <_> + 9 7 2 3 -1. + <_> + 9 8 2 1 3. + <_> + + <_> + 7 11 2 2 -1. + <_> + 7 11 1 1 2. + <_> + 8 12 1 1 2. + <_> + + <_> + 11 3 2 5 -1. + <_> + 11 3 1 5 2. + <_> + + <_> + 7 3 2 5 -1. + <_> + 8 3 1 5 2. + <_> + + <_> + 15 13 2 3 -1. + <_> + 15 14 2 1 3. + <_> + + <_> + 5 6 2 3 -1. + <_> + 5 7 2 1 3. + <_> + + <_> + 4 19 15 1 -1. + <_> + 9 19 5 1 3. + <_> + + <_> + 1 19 15 1 -1. + <_> + 6 19 5 1 3. + <_> + + <_> + 15 13 2 3 -1. + <_> + 15 14 2 1 3. + <_> + + <_> + 5 0 4 15 -1. + <_> + 7 0 2 15 2. + <_> + + <_> + 9 6 2 5 -1. + <_> + 9 6 1 5 2. + <_> + + <_> + 9 5 2 7 -1. + <_> + 10 5 1 7 2. + <_> + + <_> + 16 11 3 3 -1. + <_> + 16 12 3 1 3. + <_> + + <_> + 1 11 3 3 -1. + <_> + 1 12 3 1 3. + <_> + + <_> + 6 6 8 3 -1. + <_> + 6 7 8 1 3. + <_> + + <_> + 0 15 6 2 -1. + <_> + 0 16 6 1 2. + <_> + + <_> + 1 0 18 6 -1. + <_> + 7 0 6 6 3. + <_> + + <_> + 6 0 3 4 -1. + <_> + 7 0 1 4 3. + <_> + + <_> + 14 10 4 10 -1. + <_> + 16 10 2 5 2. + <_> + 14 15 2 5 2. + <_> + + <_> + 3 2 3 2 -1. + <_> + 4 2 1 2 3. + <_> + + <_> + 11 2 2 2 -1. + <_> + 11 3 2 1 2. + <_> + + <_> + 2 10 4 10 -1. + <_> + 2 10 2 5 2. + <_> + 4 15 2 5 2. + <_> + + <_> + 0 13 20 6 -1. + <_> + 10 13 10 3 2. + <_> + 0 16 10 3 2. + <_> + + <_> + 0 5 2 15 -1. + <_> + 1 5 1 15 2. + <_> + + <_> + 1 7 18 4 -1. + <_> + 10 7 9 2 2. + <_> + 1 9 9 2 2. + <_> + + <_> + 0 0 2 17 -1. + <_> + 1 0 1 17 2. + <_> + + <_> + 2 6 16 6 -1. + <_> + 10 6 8 3 2. + <_> + 2 9 8 3 2. + <_> + + <_> + 8 14 1 3 -1. + <_> + 8 15 1 1 3. + <_> + + <_> + 8 15 4 2 -1. + <_> + 8 16 4 1 2. + <_> + + <_> + 5 2 8 2 -1. + <_> + 5 2 4 1 2. + <_> + 9 3 4 1 2. + <_> + + <_> + 6 11 8 6 -1. + <_> + 6 14 8 3 2. + <_> + + <_> + 9 13 2 2 -1. + <_> + 9 14 2 1 2. + <_> + + <_> + 18 4 2 6 -1. + <_> + 18 6 2 2 3. + <_> + + <_> + 9 12 2 2 -1. + <_> + 9 13 2 1 2. + <_> + + <_> + 18 4 2 6 -1. + <_> + 18 6 2 2 3. + <_> + + <_> + 9 13 1 3 -1. + <_> + 9 14 1 1 3. + <_> + + <_> + 18 4 2 6 -1. + <_> + 18 6 2 2 3. + <_> + + <_> + 0 4 2 6 -1. + <_> + 0 6 2 2 3. + <_> + + <_> + 9 12 3 3 -1. + <_> + 9 13 3 1 3. + <_> + + <_> + 3 13 2 3 -1. + <_> + 3 14 2 1 3. + <_> + + <_> + 13 13 4 3 -1. + <_> + 13 14 4 1 3. + <_> + + <_> + 5 4 3 3 -1. + <_> + 5 5 3 1 3. + <_> + + <_> + 5 2 10 6 -1. + <_> + 5 4 10 2 3. + <_> + + <_> + 3 13 4 3 -1. + <_> + 3 14 4 1 3. + <_> + + <_> + 3 7 15 5 -1. + <_> + 8 7 5 5 3. + <_> + + <_> + 3 7 12 2 -1. + <_> + 7 7 4 2 3. + <_> + + <_> + 10 3 3 9 -1. + <_> + 11 3 1 9 3. + <_> + + <_> + 8 6 4 6 -1. + <_> + 10 6 2 6 2. + <_> + + <_> + 9 7 4 3 -1. + <_> + 9 8 4 1 3. + <_> + + <_> + 0 9 4 9 -1. + <_> + 2 9 2 9 2. + <_> + + <_> + 9 13 3 5 -1. + <_> + 10 13 1 5 3. + <_> + + <_> + 7 7 6 3 -1. + <_> + 9 7 2 3 3. + <_> + + <_> + 9 7 3 5 -1. + <_> + 10 7 1 5 3. + <_> + + <_> + 5 7 8 2 -1. + <_> + 9 7 4 2 2. + <_> + + <_> + 5 9 12 2 -1. + <_> + 9 9 4 2 3. + <_> + + <_> + 5 6 10 3 -1. + <_> + 10 6 5 3 2. + <_> + + <_> + 10 12 3 1 -1. + <_> + 11 12 1 1 3. + <_> + + <_> + 0 1 11 15 -1. + <_> + 0 6 11 5 3. + <_> + + <_> + 1 0 18 6 -1. + <_> + 7 0 6 6 3. + <_> + + <_> + 7 7 6 1 -1. + <_> + 9 7 2 1 3. + <_> + + <_> + 5 16 6 4 -1. + <_> + 5 16 3 2 2. + <_> + 8 18 3 2 2. + <_> + + <_> + 6 5 9 8 -1. + <_> + 6 9 9 4 2. + <_> + + <_> + 5 10 2 6 -1. + <_> + 5 13 2 3 2. + <_> + + <_> + 7 6 8 10 -1. + <_> + 11 6 4 5 2. + <_> + 7 11 4 5 2. + <_> + + <_> + 5 6 8 10 -1. + <_> + 5 6 4 5 2. + <_> + 9 11 4 5 2. + <_> + + <_> + 9 5 2 2 -1. + <_> + 9 6 2 1 2. + <_> + + <_> + 5 12 8 2 -1. + <_> + 5 13 8 1 2. + <_> + + <_> + 10 2 8 2 -1. + <_> + 10 3 8 1 2. + <_> + + <_> + 4 0 2 10 -1. + <_> + 4 0 1 5 2. + <_> + 5 5 1 5 2. + <_> + + <_> + 9 10 2 2 -1. + <_> + 9 11 2 1 2. + <_> + + <_> + 2 8 15 3 -1. + <_> + 2 9 15 1 3. + <_> + + <_> + 8 13 4 3 -1. + <_> + 8 14 4 1 3. + <_> + + <_> + 7 2 3 2 -1. + <_> + 8 2 1 2 3. + <_> + + <_> + 7 13 6 3 -1. + <_> + 7 14 6 1 3. + <_> + + <_> + 9 9 2 2 -1. + <_> + 9 10 2 1 2. + <_> + + <_> + 17 2 3 6 -1. + <_> + 17 4 3 2 3. + <_> + + <_> + 1 5 3 4 -1. + <_> + 2 5 1 4 3. + <_> + + <_> + 14 8 4 6 -1. + <_> + 14 10 4 2 3. + <_> + + <_> + 1 4 3 8 -1. + <_> + 2 4 1 8 3. + <_> + + <_> + 8 13 4 6 -1. + <_> + 8 16 4 3 2. + <_> + + <_> + 3 14 2 2 -1. + <_> + 3 15 2 1 2. + <_> + + <_> + 14 8 4 6 -1. + <_> + 14 10 4 2 3. + <_> + + <_> + 2 8 4 6 -1. + <_> + 2 10 4 2 3. + <_> + + <_> + 10 14 1 6 -1. + <_> + 10 17 1 3 2. + <_> + + <_> + 7 5 3 6 -1. + <_> + 8 5 1 6 3. + <_> + + <_> + 11 2 2 6 -1. + <_> + 12 2 1 3 2. + <_> + 11 5 1 3 2. + <_> + + <_> + 6 6 6 5 -1. + <_> + 8 6 2 5 3. + <_> + + <_> + 17 1 3 6 -1. + <_> + 17 3 3 2 3. + <_> + + <_> + 8 7 3 5 -1. + <_> + 9 7 1 5 3. + <_> + + <_> + 9 18 3 2 -1. + <_> + 10 18 1 2 3. + <_> + + <_> + 8 18 3 2 -1. + <_> + 9 18 1 2 3. + <_> + + <_> + 12 3 5 2 -1. + <_> + 12 4 5 1 2. + <_> + + <_> + 7 1 5 12 -1. + <_> + 7 7 5 6 2. + <_> + + <_> + 1 0 18 4 -1. + <_> + 7 0 6 4 3. + <_> + + <_> + 4 2 2 2 -1. + <_> + 4 3 2 1 2. + <_> + + <_> + 11 14 4 2 -1. + <_> + 13 14 2 1 2. + <_> + 11 15 2 1 2. + <_> + + <_> + 0 2 3 6 -1. + <_> + 0 4 3 2 3. + <_> + + <_> + 9 7 2 3 -1. + <_> + 9 8 2 1 3. + <_> + + <_> + 5 5 1 3 -1. + <_> + 5 6 1 1 3. + <_> + + <_> + 10 10 6 1 -1. + <_> + 10 10 3 1 2. + <_> + + <_> + 4 10 6 1 -1. + <_> + 7 10 3 1 2. + <_> + + <_> + 9 17 3 3 -1. + <_> + 9 18 3 1 3. + <_> + + <_> + 4 14 1 3 -1. + <_> + 4 15 1 1 3. + <_> + + <_> + 12 5 3 3 -1. + <_> + 12 6 3 1 3. + <_> + + <_> + 4 5 12 3 -1. + <_> + 4 6 12 1 3. + <_> + + <_> + 9 8 2 3 -1. + <_> + 9 9 2 1 3. + <_> + + <_> + 4 9 3 3 -1. + <_> + 5 9 1 3 3. + <_> + + <_> + 6 0 9 17 -1. + <_> + 9 0 3 17 3. + <_> + + <_> + 9 12 1 3 -1. + <_> + 9 13 1 1 3. + <_> + + <_> + 9 5 2 15 -1. + <_> + 9 10 2 5 3. + <_> + + <_> + 8 14 2 3 -1. + <_> + 8 15 2 1 3. + <_> + + <_> + 10 14 1 3 -1. + <_> + 10 15 1 1 3. + <_> + + <_> + 7 1 6 5 -1. + <_> + 9 1 2 5 3. + <_> + + <_> + 0 0 20 2 -1. + <_> + 0 0 10 2 2. + <_> + + <_> + 2 13 5 3 -1. + <_> + 2 14 5 1 3. + <_> + + <_> + 9 11 2 3 -1. + <_> + 9 12 2 1 3. + <_> + + <_> + 2 5 9 15 -1. + <_> + 2 10 9 5 3. + <_> + + <_> + 5 0 12 10 -1. + <_> + 11 0 6 5 2. + <_> + 5 5 6 5 2. + <_> + + <_> + 5 1 2 3 -1. + <_> + 6 1 1 3 2. + <_> + + <_> + 10 7 6 1 -1. + <_> + 12 7 2 1 3. + <_> + + <_> + 3 1 2 10 -1. + <_> + 3 1 1 5 2. + <_> + 4 6 1 5 2. + <_> + + <_> + 13 7 2 1 -1. + <_> + 13 7 1 1 2. + <_> + + <_> + 4 13 4 6 -1. + <_> + 4 15 4 2 3. + <_> + + <_> + 13 7 2 1 -1. + <_> + 13 7 1 1 2. + <_> + + <_> + 5 7 2 1 -1. + <_> + 6 7 1 1 2. + <_> + + <_> + 2 12 18 4 -1. + <_> + 11 12 9 2 2. + <_> + 2 14 9 2 2. + <_> + + <_> + 5 7 2 2 -1. + <_> + 5 7 1 1 2. + <_> + 6 8 1 1 2. + <_> + + <_> + 16 3 4 2 -1. + <_> + 16 4 4 1 2. + <_> + + <_> + 0 2 2 18 -1. + <_> + 0 2 1 9 2. + <_> + 1 11 1 9 2. + <_> + + <_> + 1 2 18 4 -1. + <_> + 10 2 9 2 2. + <_> + 1 4 9 2 2. + <_> + + <_> + 9 14 1 3 -1. + <_> + 9 15 1 1 3. + <_> + + <_> + 2 12 18 4 -1. + <_> + 11 12 9 2 2. + <_> + 2 14 9 2 2. + <_> + + <_> + 0 12 18 4 -1. + <_> + 0 12 9 2 2. + <_> + 9 14 9 2 2. + <_> + + <_> + 11 4 5 3 -1. + <_> + 11 5 5 1 3. + <_> + + <_> + 6 4 7 3 -1. + <_> + 6 5 7 1 3. + <_> + + <_> + 13 17 3 3 -1. + <_> + 13 18 3 1 3. + <_> + + <_> + 8 1 3 4 -1. + <_> + 9 1 1 4 3. + <_> + + <_> + 11 4 2 4 -1. + <_> + 11 4 1 4 2. + <_> + + <_> + 0 17 9 3 -1. + <_> + 3 17 3 3 3. + <_> + + <_> + 11 0 2 8 -1. + <_> + 12 0 1 4 2. + <_> + 11 4 1 4 2. + <_> + + <_> + 0 8 6 12 -1. + <_> + 0 8 3 6 2. + <_> + 3 14 3 6 2. + <_> + + <_> + 10 7 4 12 -1. + <_> + 10 13 4 6 2. + <_> + + <_> + 5 3 8 14 -1. + <_> + 5 10 8 7 2. + <_> + + <_> + 14 10 6 1 -1. + <_> + 14 10 3 1 2. + <_> + + <_> + 0 4 10 4 -1. + <_> + 0 6 10 2 2. + <_> + + <_> + 10 0 5 8 -1. + <_> + 10 4 5 4 2. + <_> + + <_> + 8 1 4 8 -1. + <_> + 8 1 2 4 2. + <_> + 10 5 2 4 2. + <_> + + <_> + 9 11 6 1 -1. + <_> + 11 11 2 1 3. + <_> + + <_> + 8 9 3 4 -1. + <_> + 9 9 1 4 3. + <_> + + <_> + 18 4 2 6 -1. + <_> + 18 6 2 2 3. + <_> + + <_> + 8 8 3 4 -1. + <_> + 9 8 1 4 3. + <_> + + <_> + 7 1 13 3 -1. + <_> + 7 2 13 1 3. + <_> + + <_> + 7 13 6 1 -1. + <_> + 9 13 2 1 3. + <_> + + <_> + 12 11 3 6 -1. + <_> + 12 13 3 2 3. + <_> + + <_> + 5 11 6 1 -1. + <_> + 7 11 2 1 3. + <_> + + <_> + 1 4 18 10 -1. + <_> + 10 4 9 5 2. + <_> + 1 9 9 5 2. + <_> + + <_> + 8 6 4 9 -1. + <_> + 8 9 4 3 3. + <_> + + <_> + 8 6 4 3 -1. + <_> + 8 7 4 1 3. + <_> + + <_> + 8 7 3 3 -1. + <_> + 9 7 1 3 3. + <_> + + <_> + 14 15 4 3 -1. + <_> + 14 16 4 1 3. + <_> + + <_> + 5 10 3 10 -1. + <_> + 6 10 1 10 3. + <_> + + <_> + 8 15 4 3 -1. + <_> + 8 16 4 1 3. + <_> + + <_> + 0 8 1 6 -1. + <_> + 0 10 1 2 3. + <_> + + <_> + 10 15 1 3 -1. + <_> + 10 16 1 1 3. + <_> + + <_> + 2 15 4 3 -1. + <_> + 2 16 4 1 3. + <_> + + <_> + 18 3 2 8 -1. + <_> + 19 3 1 4 2. + <_> + 18 7 1 4 2. + <_> + + <_> + 0 3 2 8 -1. + <_> + 0 3 1 4 2. + <_> + 1 7 1 4 2. + <_> + + <_> + 3 7 14 10 -1. + <_> + 10 7 7 5 2. + <_> + 3 12 7 5 2. + <_> + + <_> + 0 7 19 3 -1. + <_> + 0 8 19 1 3. + <_> + + <_> + 12 6 3 3 -1. + <_> + 12 7 3 1 3. + <_> + + <_> + 0 6 1 3 -1. + <_> + 0 7 1 1 3. + <_> + + <_> + 12 6 3 3 -1. + <_> + 12 7 3 1 3. + <_> + + <_> + 5 6 3 3 -1. + <_> + 5 7 3 1 3. + <_> + + <_> + 8 2 4 2 -1. + <_> + 8 3 4 1 2. + <_> + + <_> + 6 3 4 12 -1. + <_> + 8 3 2 12 2. + <_> + + <_> + 13 6 2 3 -1. + <_> + 13 7 2 1 3. + <_> + + <_> + 0 10 20 4 -1. + <_> + 0 12 20 2 2. + <_> + + <_> + 2 0 17 14 -1. + <_> + 2 7 17 7 2. + <_> + + <_> + 0 0 6 10 -1. + <_> + 0 0 3 5 2. + <_> + 3 5 3 5 2. + <_> + + <_> + 14 6 6 4 -1. + <_> + 14 6 3 4 2. + <_> + + <_> + 0 6 6 4 -1. + <_> + 3 6 3 4 2. + <_> + + <_> + 13 2 7 2 -1. + <_> + 13 3 7 1 2. + <_> + + <_> + 0 2 7 2 -1. + <_> + 0 3 7 1 2. + <_> + + <_> + 6 11 14 2 -1. + <_> + 13 11 7 1 2. + <_> + 6 12 7 1 2. + <_> + + <_> + 8 5 2 2 -1. + <_> + 8 5 1 1 2. + <_> + 9 6 1 1 2. + <_> + + <_> + 13 9 2 3 -1. + <_> + 13 9 1 3 2. + <_> + + <_> + 1 1 3 12 -1. + <_> + 2 1 1 12 3. + <_> + + <_> + 17 4 1 3 -1. + <_> + 17 5 1 1 3. + <_> + + <_> + 2 4 1 3 -1. + <_> + 2 5 1 1 3. + <_> + + <_> + 14 5 1 3 -1. + <_> + 14 6 1 1 3. + <_> + + <_> + 7 16 2 3 -1. + <_> + 7 17 2 1 3. + <_> + + <_> + 8 13 4 6 -1. + <_> + 10 13 2 3 2. + <_> + 8 16 2 3 2. + <_> + + <_> + 5 5 1 3 -1. + <_> + 5 6 1 1 3. + <_> + + <_> + 16 0 4 20 -1. + <_> + 16 0 2 20 2. + <_> + + <_> + 5 1 2 6 -1. + <_> + 5 1 1 3 2. + <_> + 6 4 1 3 2. + <_> + + <_> + 5 4 10 4 -1. + <_> + 5 6 10 2 2. + <_> + + <_> + 15 2 4 12 -1. + <_> + 15 2 2 12 2. + <_> + + <_> + 7 6 4 12 -1. + <_> + 7 12 4 6 2. + <_> + + <_> + 14 5 1 8 -1. + <_> + 14 9 1 4 2. + <_> + + <_> + 1 4 14 10 -1. + <_> + 1 4 7 5 2. + <_> + 8 9 7 5 2. + <_> + + <_> + 11 6 6 14 -1. + <_> + 14 6 3 7 2. + <_> + 11 13 3 7 2. + <_> + + <_> + 3 6 6 14 -1. + <_> + 3 6 3 7 2. + <_> + 6 13 3 7 2. + <_> + + <_> + 4 9 15 2 -1. + <_> + 9 9 5 2 3. + <_> + + <_> + 7 14 6 3 -1. + <_> + 7 15 6 1 3. + <_> + + <_> + 6 3 14 4 -1. + <_> + 13 3 7 2 2. + <_> + 6 5 7 2 2. + <_> + + <_> + 1 9 15 2 -1. + <_> + 6 9 5 2 3. + <_> + + <_> + 6 11 8 9 -1. + <_> + 6 14 8 3 3. + <_> + + <_> + 7 4 3 8 -1. + <_> + 8 4 1 8 3. + <_> + + <_> + 14 6 2 6 -1. + <_> + 14 9 2 3 2. + <_> + + <_> + 5 7 6 4 -1. + <_> + 5 7 3 2 2. + <_> + 8 9 3 2 2. + <_> + + <_> + 1 1 18 19 -1. + <_> + 7 1 6 19 3. + <_> + + <_> + 1 2 6 5 -1. + <_> + 4 2 3 5 2. + <_> + + <_> + 12 17 6 2 -1. + <_> + 12 18 6 1 2. + <_> + + <_> + 2 17 6 2 -1. + <_> + 2 18 6 1 2. + <_> + + <_> + 17 3 3 6 -1. + <_> + 17 5 3 2 3. + <_> + + <_> + 8 17 3 3 -1. + <_> + 8 18 3 1 3. + <_> + + <_> + 10 13 2 6 -1. + <_> + 10 16 2 3 2. + <_> + + <_> + 7 13 6 3 -1. + <_> + 7 14 6 1 3. + <_> + + <_> + 17 3 3 6 -1. + <_> + 17 5 3 2 3. + <_> + + <_> + 8 13 2 3 -1. + <_> + 8 14 2 1 3. + <_> + + <_> + 9 3 6 2 -1. + <_> + 11 3 2 2 3. + <_> + + <_> + 0 3 3 6 -1. + <_> + 0 5 3 2 3. + <_> + + <_> + 8 5 4 6 -1. + <_> + 8 7 4 2 3. + <_> + + <_> + 5 5 3 2 -1. + <_> + 5 6 3 1 2. + <_> + + <_> + 10 1 3 4 -1. + <_> + 11 1 1 4 3. + <_> + + <_> + 1 2 5 9 -1. + <_> + 1 5 5 3 3. + <_> + + <_> + 13 6 2 3 -1. + <_> + 13 7 2 1 3. + <_> + + <_> + 0 6 14 3 -1. + <_> + 7 6 7 3 2. + <_> + + <_> + 2 11 18 8 -1. + <_> + 2 15 18 4 2. + <_> + + <_> + 5 6 2 3 -1. + <_> + 5 7 2 1 3. + <_> + + <_> + 10 6 4 2 -1. + <_> + 12 6 2 1 2. + <_> + 10 7 2 1 2. + <_> + + <_> + 6 6 4 2 -1. + <_> + 6 6 2 1 2. + <_> + 8 7 2 1 2. + <_> + + <_> + 10 1 3 4 -1. + <_> + 11 1 1 4 3. + <_> + + <_> + 7 1 2 7 -1. + <_> + 8 1 1 7 2. + <_> + + <_> + 4 2 15 14 -1. + <_> + 4 9 15 7 2. + <_> + + <_> + 8 7 3 2 -1. + <_> + 9 7 1 2 3. + <_> + + <_> + 2 3 18 4 -1. + <_> + 11 3 9 2 2. + <_> + 2 5 9 2 2. + <_> + + <_> + 9 7 2 2 -1. + <_> + 10 7 1 2 2. + <_> + + <_> + 13 9 2 3 -1. + <_> + 13 9 1 3 2. + <_> + + <_> + 5 2 6 2 -1. + <_> + 7 2 2 2 3. + <_> + + <_> + 9 5 2 7 -1. + <_> + 9 5 1 7 2. + <_> + + <_> + 5 9 2 3 -1. + <_> + 6 9 1 3 2. + <_> + + <_> + 6 0 14 18 -1. + <_> + 6 9 14 9 2. + <_> + + <_> + 2 16 6 3 -1. + <_> + 2 17 6 1 3. + <_> + + <_> + 9 7 3 6 -1. + <_> + 10 7 1 6 3. + <_> + + <_> + 7 8 4 3 -1. + <_> + 7 9 4 1 3. + <_> + + <_> + 7 12 6 3 -1. + <_> + 7 13 6 1 3. + <_> + + <_> + 9 12 2 3 -1. + <_> + 9 13 2 1 3. + <_> + + <_> + 7 12 6 2 -1. + <_> + 9 12 2 2 3. + <_> + + <_> + 5 11 4 6 -1. + <_> + 5 14 4 3 2. + <_> + + <_> + 11 12 7 2 -1. + <_> + 11 13 7 1 2. + <_> + + <_> + 6 10 8 6 -1. + <_> + 6 10 4 3 2. + <_> + 10 13 4 3 2. + <_> + + <_> + 11 10 3 4 -1. + <_> + 11 12 3 2 2. + <_> + + <_> + 9 16 2 3 -1. + <_> + 9 17 2 1 3. + <_> + + <_> + 13 3 1 9 -1. + <_> + 13 6 1 3 3. + <_> + + <_> + 1 13 14 6 -1. + <_> + 1 15 14 2 3. + <_> + + <_> + 13 6 1 6 -1. + <_> + 13 9 1 3 2. + <_> + + <_> + 0 4 3 8 -1. + <_> + 1 4 1 8 3. + <_> + + <_> + 18 0 2 18 -1. + <_> + 18 0 1 18 2. + <_> + + <_> + 2 3 6 2 -1. + <_> + 2 4 6 1 2. + <_> + + <_> + 9 0 8 6 -1. + <_> + 9 2 8 2 3. + <_> + + <_> + 6 6 1 6 -1. + <_> + 6 9 1 3 2. + <_> + + <_> + 14 8 6 3 -1. + <_> + 14 9 6 1 3. + <_> + + <_> + 0 0 2 18 -1. + <_> + 1 0 1 18 2. + <_> + + <_> + 1 18 18 2 -1. + <_> + 10 18 9 1 2. + <_> + 1 19 9 1 2. + <_> + + <_> + 3 15 2 2 -1. + <_> + 3 16 2 1 2. + <_> + + <_> + 8 14 5 3 -1. + <_> + 8 15 5 1 3. + <_> + + <_> + 8 14 2 3 -1. + <_> + 8 15 2 1 3. + <_> + + <_> + 12 3 3 3 -1. + <_> + 13 3 1 3 3. + <_> + + <_> + 7 5 6 2 -1. + <_> + 9 5 2 2 3. + <_> + + <_> + 15 5 5 2 -1. + <_> + 15 6 5 1 2. + <_> + + <_> + 0 5 5 2 -1. + <_> + 0 6 5 1 2. + <_> + + <_> + 17 14 1 6 -1. + <_> + 17 17 1 3 2. + <_> + + <_> + 2 9 9 3 -1. + <_> + 5 9 3 3 3. + <_> + + <_> + 12 3 3 3 -1. + <_> + 13 3 1 3 3. + <_> + + <_> + 0 0 4 18 -1. + <_> + 2 0 2 18 2. + <_> + + <_> + 17 6 1 3 -1. + <_> + 17 7 1 1 3. + <_> + + <_> + 2 14 1 6 -1. + <_> + 2 17 1 3 2. + <_> + + <_> + 19 8 1 2 -1. + <_> + 19 9 1 1 2. + <_> + + <_> + 5 3 3 3 -1. + <_> + 6 3 1 3 3. + <_> + + <_> + 9 16 2 3 -1. + <_> + 9 17 2 1 3. + <_> + + <_> + 2 6 1 3 -1. + <_> + 2 7 1 1 3. + <_> + + <_> + 12 4 8 2 -1. + <_> + 16 4 4 1 2. + <_> + 12 5 4 1 2. + <_> + + <_> + 0 4 8 2 -1. + <_> + 0 4 4 1 2. + <_> + 4 5 4 1 2. + <_> + + <_> + 2 16 18 4 -1. + <_> + 2 18 18 2 2. + <_> + + <_> + 7 15 2 4 -1. + <_> + 7 17 2 2 2. + <_> + + <_> + 4 0 14 3 -1. + <_> + 4 1 14 1 3. + <_> + + <_> + 0 0 4 20 -1. + <_> + 2 0 2 20 2. + <_> + + <_> + 12 4 4 8 -1. + <_> + 14 4 2 4 2. + <_> + 12 8 2 4 2. + <_> + + <_> + 6 7 2 2 -1. + <_> + 6 7 1 1 2. + <_> + 7 8 1 1 2. + <_> + + <_> + 10 6 2 3 -1. + <_> + 10 7 2 1 3. + <_> + + <_> + 8 7 3 2 -1. + <_> + 8 8 3 1 2. + <_> + + <_> + 8 2 6 12 -1. + <_> + 8 8 6 6 2. + <_> + + <_> + 4 0 11 12 -1. + <_> + 4 4 11 4 3. + <_> + + <_> + 14 9 6 11 -1. + <_> + 16 9 2 11 3. + <_> + + <_> + 0 14 4 3 -1. + <_> + 0 15 4 1 3. + <_> + + <_> + 9 10 2 3 -1. + <_> + 9 11 2 1 3. + <_> + + <_> + 5 11 3 2 -1. + <_> + 5 12 3 1 2. + <_> + + <_> + 9 15 3 3 -1. + <_> + 10 15 1 3 3. + <_> + + <_> + 8 8 3 4 -1. + <_> + 9 8 1 4 3. + <_> + + <_> + 9 15 3 3 -1. + <_> + 10 15 1 3 3. + <_> + + <_> + 7 7 3 2 -1. + <_> + 8 7 1 2 3. + <_> + + <_> + 2 10 16 4 -1. + <_> + 10 10 8 2 2. + <_> + 2 12 8 2 2. + <_> + + <_> + 2 3 4 17 -1. + <_> + 4 3 2 17 2. + <_> + + <_> + 15 13 2 7 -1. + <_> + 15 13 1 7 2. + <_> + + <_> + 2 2 6 1 -1. + <_> + 5 2 3 1 2. + <_> + + <_> + 5 2 12 4 -1. + <_> + 9 2 4 4 3. + <_> + + <_> + 6 0 8 12 -1. + <_> + 6 0 4 6 2. + <_> + 10 6 4 6 2. + <_> + + <_> + 13 7 2 2 -1. + <_> + 14 7 1 1 2. + <_> + 13 8 1 1 2. + <_> + + <_> + 0 12 20 6 -1. + <_> + 0 14 20 2 3. + <_> + + <_> + 14 7 2 3 -1. + <_> + 14 7 1 3 2. + <_> + + <_> + 0 8 9 12 -1. + <_> + 3 8 3 12 3. + <_> + + <_> + 3 0 16 2 -1. + <_> + 3 0 8 2 2. + <_> + + <_> + 6 15 3 3 -1. + <_> + 6 16 3 1 3. + <_> + + <_> + 8 15 6 3 -1. + <_> + 8 16 6 1 3. + <_> + + <_> + 0 10 1 6 -1. + <_> + 0 12 1 2 3. + <_> + + <_> + 10 9 4 3 -1. + <_> + 10 10 4 1 3. + <_> + + <_> + 9 15 2 3 -1. + <_> + 9 16 2 1 3. + <_> + + <_> + 5 7 10 1 -1. + <_> + 5 7 5 1 2. + <_> + + <_> + 4 0 12 19 -1. + <_> + 10 0 6 19 2. + <_> + + <_> + 0 6 20 6 -1. + <_> + 10 6 10 3 2. + <_> + 0 9 10 3 2. + <_> + + <_> + 3 6 2 2 -1. + <_> + 3 6 1 1 2. + <_> + 4 7 1 1 2. + <_> + + <_> + 15 6 2 2 -1. + <_> + 16 6 1 1 2. + <_> + 15 7 1 1 2. + <_> + + <_> + 3 6 2 2 -1. + <_> + 3 6 1 1 2. + <_> + 4 7 1 1 2. + <_> + + <_> + 14 4 1 12 -1. + <_> + 14 10 1 6 2. + <_> + + <_> + 2 5 16 10 -1. + <_> + 2 5 8 5 2. + <_> + 10 10 8 5 2. + <_> + + <_> + 9 17 3 2 -1. + <_> + 10 17 1 2 3. + <_> + + <_> + 1 4 2 2 -1. + <_> + 1 5 2 1 2. + <_> + + <_> + 5 0 15 5 -1. + <_> + 10 0 5 5 3. + <_> + + <_> + 0 0 15 5 -1. + <_> + 5 0 5 5 3. + <_> + + <_> + 11 2 2 17 -1. + <_> + 11 2 1 17 2. + <_> + + <_> + 7 2 2 17 -1. + <_> + 8 2 1 17 2. + <_> + + <_> + 15 11 2 9 -1. + <_> + 15 11 1 9 2. + <_> + + <_> + 3 11 2 9 -1. + <_> + 4 11 1 9 2. + <_> + + <_> + 5 16 14 4 -1. + <_> + 5 16 7 4 2. + <_> + + <_> + 1 4 18 1 -1. + <_> + 7 4 6 1 3. + <_> + + <_> + 13 7 6 4 -1. + <_> + 16 7 3 2 2. + <_> + 13 9 3 2 2. + <_> + + <_> + 9 8 2 12 -1. + <_> + 9 12 2 4 3. + <_> + + <_> + 12 1 6 6 -1. + <_> + 12 3 6 2 3. + <_> + + <_> + 5 2 6 6 -1. + <_> + 5 2 3 3 2. + <_> + 8 5 3 3 2. + <_> + + <_> + 9 16 6 4 -1. + <_> + 12 16 3 2 2. + <_> + 9 18 3 2 2. + <_> + + <_> + 1 2 18 3 -1. + <_> + 7 2 6 3 3. + <_> + + <_> + 7 4 9 10 -1. + <_> + 7 9 9 5 2. + <_> + + <_> + 5 9 4 4 -1. + <_> + 7 9 2 4 2. + <_> + + <_> + 11 10 3 6 -1. + <_> + 11 13 3 3 2. + <_> + + <_> + 7 11 5 3 -1. + <_> + 7 12 5 1 3. + <_> + + <_> + 7 11 6 6 -1. + <_> + 10 11 3 3 2. + <_> + 7 14 3 3 2. + <_> + + <_> + 0 0 10 9 -1. + <_> + 0 3 10 3 3. + <_> + + <_> + 13 14 1 6 -1. + <_> + 13 16 1 2 3. + <_> + + <_> + 0 2 3 6 -1. + <_> + 0 4 3 2 3. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 6 14 1 6 -1. + <_> + 6 16 1 2 3. + <_> + + <_> + 9 15 2 3 -1. + <_> + 9 16 2 1 3. + <_> + + <_> + 6 4 3 3 -1. + <_> + 7 4 1 3 3. + <_> + + <_> + 9 0 11 3 -1. + <_> + 9 1 11 1 3. + <_> + + <_> + 0 6 20 3 -1. + <_> + 0 7 20 1 3. + <_> + + <_> + 10 1 1 2 -1. + <_> + 10 2 1 1 2. + <_> + + <_> + 9 6 2 6 -1. + <_> + 10 6 1 6 2. + <_> + + <_> + 5 8 12 1 -1. + <_> + 9 8 4 1 3. + <_> + + <_> + 3 8 12 1 -1. + <_> + 7 8 4 1 3. + <_> + + <_> + 9 7 3 5 -1. + <_> + 10 7 1 5 3. + <_> + + <_> + 3 9 6 2 -1. + <_> + 6 9 3 2 2. + <_> + + <_> + 12 9 3 3 -1. + <_> + 12 10 3 1 3. + <_> + + <_> + 7 0 6 1 -1. + <_> + 9 0 2 1 3. + <_> + + <_> + 12 9 3 3 -1. + <_> + 12 10 3 1 3. + <_> + + <_> + 7 10 2 1 -1. + <_> + 8 10 1 1 2. + <_> + + <_> + 6 4 9 13 -1. + <_> + 9 4 3 13 3. + <_> + + <_> + 6 8 4 2 -1. + <_> + 6 9 4 1 2. + <_> + + <_> + 16 2 4 6 -1. + <_> + 16 2 2 6 2. + <_> + + <_> + 0 17 6 3 -1. + <_> + 0 18 6 1 3. + <_> + + <_> + 10 10 3 10 -1. + <_> + 10 15 3 5 2. + <_> + + <_> + 8 7 3 5 -1. + <_> + 9 7 1 5 3. + <_> + + <_> + 10 4 4 3 -1. + <_> + 10 4 2 3 2. + <_> + + <_> + 8 4 3 8 -1. + <_> + 9 4 1 8 3. + <_> + + <_> + 6 6 9 13 -1. + <_> + 9 6 3 13 3. + <_> + + <_> + 6 0 8 12 -1. + <_> + 6 0 4 6 2. + <_> + 10 6 4 6 2. + <_> + + <_> + 14 2 6 8 -1. + <_> + 16 2 2 8 3. + <_> + + <_> + 6 0 3 6 -1. + <_> + 7 0 1 6 3. + <_> + + <_> + 14 2 6 8 -1. + <_> + 16 2 2 8 3. + <_> + + <_> + 0 5 6 6 -1. + <_> + 0 8 6 3 2. + <_> + + <_> + 9 12 6 2 -1. + <_> + 12 12 3 1 2. + <_> + 9 13 3 1 2. + <_> + + <_> + 8 17 3 2 -1. + <_> + 9 17 1 2 3. + <_> + + <_> + 11 6 2 2 -1. + <_> + 12 6 1 1 2. + <_> + 11 7 1 1 2. + <_> + + <_> + 1 9 18 2 -1. + <_> + 7 9 6 2 3. + <_> + + <_> + 11 6 2 2 -1. + <_> + 12 6 1 1 2. + <_> + 11 7 1 1 2. + <_> + + <_> + 3 4 12 8 -1. + <_> + 7 4 4 8 3. + <_> + + <_> + 13 11 5 3 -1. + <_> + 13 12 5 1 3. + <_> + + <_> + 9 10 2 3 -1. + <_> + 9 11 2 1 3. + <_> + + <_> + 14 7 2 3 -1. + <_> + 14 7 1 3 2. + <_> + + <_> + 5 4 1 3 -1. + <_> + 5 5 1 1 3. + <_> + + <_> + 13 4 2 3 -1. + <_> + 13 5 2 1 3. + <_> + + <_> + 5 4 2 3 -1. + <_> + 5 5 2 1 3. + <_> + + <_> + 9 8 2 3 -1. + <_> + 9 9 2 1 3. + <_> + + <_> + 8 9 2 2 -1. + <_> + 8 10 2 1 2. + <_> + + <_> + 15 14 1 4 -1. + <_> + 15 16 1 2 2. + <_> + + <_> + 3 12 2 2 -1. + <_> + 3 13 2 1 2. + <_> + + <_> + 12 15 2 2 -1. + <_> + 13 15 1 1 2. + <_> + 12 16 1 1 2. + <_> + + <_> + 9 13 2 2 -1. + <_> + 9 14 2 1 2. + <_> + + <_> + 4 11 14 9 -1. + <_> + 4 14 14 3 3. + <_> + + <_> + 7 13 4 3 -1. + <_> + 7 14 4 1 3. + <_> + + <_> + 15 14 1 4 -1. + <_> + 15 16 1 2 2. + <_> + + <_> + 4 14 1 4 -1. + <_> + 4 16 1 2 2. + <_> + + <_> + 14 0 6 13 -1. + <_> + 16 0 2 13 3. + <_> + + <_> + 4 1 2 12 -1. + <_> + 4 1 1 6 2. + <_> + 5 7 1 6 2. + <_> + + <_> + 11 14 6 6 -1. + <_> + 14 14 3 3 2. + <_> + 11 17 3 3 2. + <_> + + <_> + 3 14 6 6 -1. + <_> + 3 14 3 3 2. + <_> + 6 17 3 3 2. + <_> + + <_> + 14 17 3 2 -1. + <_> + 14 18 3 1 2. + <_> + + <_> + 3 17 3 2 -1. + <_> + 3 18 3 1 2. + <_> + + <_> + 14 0 6 13 -1. + <_> + 16 0 2 13 3. + <_> + + <_> + 0 0 6 13 -1. + <_> + 2 0 2 13 3. + <_> + + <_> + 10 10 7 6 -1. + <_> + 10 12 7 2 3. + <_> + + <_> + 6 15 2 2 -1. + <_> + 6 15 1 1 2. + <_> + 7 16 1 1 2. + <_> + + <_> + 6 11 8 6 -1. + <_> + 10 11 4 3 2. + <_> + 6 14 4 3 2. + <_> + + <_> + 7 6 2 2 -1. + <_> + 7 6 1 1 2. + <_> + 8 7 1 1 2. + <_> + + <_> + 2 2 16 6 -1. + <_> + 10 2 8 3 2. + <_> + 2 5 8 3 2. + <_> + + <_> + 5 4 3 3 -1. + <_> + 5 5 3 1 3. + <_> + + <_> + 11 7 3 10 -1. + <_> + 11 12 3 5 2. + <_> + + <_> + 6 7 3 10 -1. + <_> + 6 12 3 5 2. + <_> + + <_> + 10 7 3 2 -1. + <_> + 11 7 1 2 3. + <_> + + <_> + 8 12 4 2 -1. + <_> + 8 13 4 1 2. + <_> + + <_> + 10 1 1 3 -1. + <_> + 10 2 1 1 3. + <_> + + <_> + 1 2 4 18 -1. + <_> + 1 2 2 9 2. + <_> + 3 11 2 9 2. + <_> + + <_> + 12 4 4 12 -1. + <_> + 12 10 4 6 2. + <_> + + <_> + 0 0 1 6 -1. + <_> + 0 2 1 2 3. + <_> + + <_> + 9 11 2 3 -1. + <_> + 9 12 2 1 3. + <_> + + <_> + 8 7 4 3 -1. + <_> + 8 8 4 1 3. + <_> + + <_> + 10 7 3 2 -1. + <_> + 11 7 1 2 3. + <_> + + <_> + 7 7 3 2 -1. + <_> + 8 7 1 2 3. + <_> + + <_> + 9 4 6 1 -1. + <_> + 11 4 2 1 3. + <_> + + <_> + 8 7 2 3 -1. + <_> + 9 7 1 3 2. + <_> + + <_> + 12 7 8 6 -1. + <_> + 16 7 4 3 2. + <_> + 12 10 4 3 2. + <_> + + <_> + 0 7 8 6 -1. + <_> + 0 7 4 3 2. + <_> + 4 10 4 3 2. + <_> + + <_> + 18 2 2 10 -1. + <_> + 19 2 1 5 2. + <_> + 18 7 1 5 2. + <_> + + <_> + 0 2 6 4 -1. + <_> + 3 2 3 4 2. + <_> + + <_> + 9 4 6 1 -1. + <_> + 11 4 2 1 3. + <_> + + <_> + 7 15 2 2 -1. + <_> + 7 15 1 1 2. + <_> + 8 16 1 1 2. + <_> + + <_> + 11 13 1 6 -1. + <_> + 11 16 1 3 2. + <_> + + <_> + 8 13 1 6 -1. + <_> + 8 16 1 3 2. + <_> + + <_> + 14 3 2 1 -1. + <_> + 14 3 1 1 2. + <_> + + <_> + 8 15 2 3 -1. + <_> + 8 16 2 1 3. + <_> + + <_> + 12 15 7 4 -1. + <_> + 12 17 7 2 2. + <_> + + <_> + 4 14 12 3 -1. + <_> + 4 15 12 1 3. + <_> + + <_> + 10 3 3 2 -1. + <_> + 11 3 1 2 3. + <_> + + <_> + 4 12 2 2 -1. + <_> + 4 13 2 1 2. + <_> + + <_> + 10 11 4 6 -1. + <_> + 10 14 4 3 2. + <_> + + <_> + 7 13 2 2 -1. + <_> + 7 13 1 1 2. + <_> + 8 14 1 1 2. + <_> + + <_> + 4 11 14 4 -1. + <_> + 11 11 7 2 2. + <_> + 4 13 7 2 2. + <_> + + <_> + 1 18 18 2 -1. + <_> + 7 18 6 2 3. + <_> + + <_> + 11 18 2 2 -1. + <_> + 12 18 1 1 2. + <_> + 11 19 1 1 2. + <_> + + <_> + 7 18 2 2 -1. + <_> + 7 18 1 1 2. + <_> + 8 19 1 1 2. + <_> + + <_> + 12 18 8 2 -1. + <_> + 12 19 8 1 2. + <_> + + <_> + 7 14 6 2 -1. + <_> + 7 15 6 1 2. + <_> + + <_> + 8 12 4 8 -1. + <_> + 10 12 2 4 2. + <_> + 8 16 2 4 2. + <_> + + <_> + 4 9 3 3 -1. + <_> + 4 10 3 1 3. + <_> + + <_> + 7 10 6 2 -1. + <_> + 9 10 2 2 3. + <_> + + <_> + 5 0 4 15 -1. + <_> + 7 0 2 15 2. + <_> + + <_> + 8 6 12 14 -1. + <_> + 12 6 4 14 3. + <_> + + <_> + 5 16 3 3 -1. + <_> + 5 17 3 1 3. + <_> + + <_> + 8 1 12 19 -1. + <_> + 12 1 4 19 3. + <_> + + <_> + 3 0 3 2 -1. + <_> + 3 1 3 1 2. + <_> + + <_> + 10 12 4 5 -1. + <_> + 10 12 2 5 2. + <_> + + <_> + 6 12 4 5 -1. + <_> + 8 12 2 5 2. + <_> + + <_> + 11 11 2 2 -1. + <_> + 12 11 1 1 2. + <_> + 11 12 1 1 2. + <_> + + <_> + 0 2 3 6 -1. + <_> + 0 4 3 2 3. + <_> + + <_> + 11 11 2 2 -1. + <_> + 12 11 1 1 2. + <_> + 11 12 1 1 2. + <_> + + <_> + 7 6 4 10 -1. + <_> + 7 11 4 5 2. + <_> + + <_> + 11 11 2 2 -1. + <_> + 12 11 1 1 2. + <_> + 11 12 1 1 2. + <_> + + <_> + 2 13 5 2 -1. + <_> + 2 14 5 1 2. + <_> + + <_> + 11 11 2 2 -1. + <_> + 12 11 1 1 2. + <_> + 11 12 1 1 2. + <_> + + <_> + 7 11 2 2 -1. + <_> + 7 11 1 1 2. + <_> + 8 12 1 1 2. + <_> + + <_> + 14 13 3 3 -1. + <_> + 14 14 3 1 3. + <_> + + <_> + 3 13 3 3 -1. + <_> + 3 14 3 1 3. + <_> + + <_> + 9 14 2 3 -1. + <_> + 9 15 2 1 3. + <_> + + <_> + 8 7 3 3 -1. + <_> + 8 8 3 1 3. + <_> + + <_> + 13 5 3 3 -1. + <_> + 13 6 3 1 3. + <_> + + <_> + 0 9 5 3 -1. + <_> + 0 10 5 1 3. + <_> + + <_> + 13 5 3 3 -1. + <_> + 13 6 3 1 3. + <_> + + <_> + 9 12 2 8 -1. + <_> + 9 12 1 4 2. + <_> + 10 16 1 4 2. + <_> + + <_> + 11 7 2 2 -1. + <_> + 12 7 1 1 2. + <_> + 11 8 1 1 2. + <_> + + <_> + 0 16 6 4 -1. + <_> + 3 16 3 4 2. + <_> + + <_> + 10 6 2 3 -1. + <_> + 10 7 2 1 3. + <_> + + <_> + 9 5 2 6 -1. + <_> + 9 7 2 2 3. + <_> + + <_> + 12 15 8 4 -1. + <_> + 12 15 4 4 2. + <_> + + <_> + 0 14 8 6 -1. + <_> + 4 14 4 6 2. + <_> + + <_> + 9 0 3 2 -1. + <_> + 10 0 1 2 3. + <_> + + <_> + 4 15 4 2 -1. + <_> + 6 15 2 2 2. + <_> + + <_> + 12 7 3 13 -1. + <_> + 13 7 1 13 3. + <_> + + <_> + 5 7 3 13 -1. + <_> + 6 7 1 13 3. + <_> + + <_> + 9 6 3 9 -1. + <_> + 9 9 3 3 3. + <_> + + <_> + 4 4 7 12 -1. + <_> + 4 10 7 6 2. + <_> + + <_> + 12 12 2 2 -1. + <_> + 13 12 1 1 2. + <_> + 12 13 1 1 2. + <_> + + <_> + 6 12 2 2 -1. + <_> + 6 12 1 1 2. + <_> + 7 13 1 1 2. + <_> + + <_> + 8 9 4 2 -1. + <_> + 10 9 2 1 2. + <_> + 8 10 2 1 2. + <_> + + <_> + 3 6 2 2 -1. + <_> + 3 6 1 1 2. + <_> + 4 7 1 1 2. + <_> + + <_> + 16 6 3 2 -1. + <_> + 16 7 3 1 2. + <_> + + <_> + 0 7 19 4 -1. + <_> + 0 9 19 2 2. + <_> + + <_> + 10 2 10 1 -1. + <_> + 10 2 5 1 2. + <_> + + <_> + 9 4 2 12 -1. + <_> + 9 10 2 6 2. + <_> + + <_> + 12 18 4 1 -1. + <_> + 12 18 2 1 2. + <_> + + <_> + 1 7 6 4 -1. + <_> + 1 7 3 2 2. + <_> + 4 9 3 2 2. + <_> + + <_> + 12 0 6 13 -1. + <_> + 14 0 2 13 3. + <_> + + <_> + 2 0 6 13 -1. + <_> + 4 0 2 13 3. + <_> + + <_> + 10 5 8 8 -1. + <_> + 10 9 8 4 2. + <_> + + <_> + 8 3 2 5 -1. + <_> + 9 3 1 5 2. + <_> + + <_> + 8 4 9 1 -1. + <_> + 11 4 3 1 3. + <_> + + <_> + 3 4 9 1 -1. + <_> + 6 4 3 1 3. + <_> + + <_> + 1 0 18 10 -1. + <_> + 7 0 6 10 3. + <_> + + <_> + 7 17 5 3 -1. + <_> + 7 18 5 1 3. + <_> + + <_> + 7 11 6 1 -1. + <_> + 9 11 2 1 3. + <_> + + <_> + 2 2 3 2 -1. + <_> + 2 3 3 1 2. + <_> + + <_> + 8 12 4 2 -1. + <_> + 8 13 4 1 2. + <_> + + <_> + 6 10 3 6 -1. + <_> + 6 13 3 3 2. + <_> + + <_> + 11 4 2 4 -1. + <_> + 11 4 1 4 2. + <_> + + <_> + 7 4 2 4 -1. + <_> + 8 4 1 4 2. + <_> + + <_> + 9 6 2 4 -1. + <_> + 9 6 1 4 2. + <_> + + <_> + 6 13 8 3 -1. + <_> + 6 14 8 1 3. + <_> + + <_> + 9 15 3 4 -1. + <_> + 10 15 1 4 3. + <_> + + <_> + 9 2 2 17 -1. + <_> + 10 2 1 17 2. + <_> + + <_> + 7 0 6 1 -1. + <_> + 9 0 2 1 3. + <_> + + <_> + 8 15 3 4 -1. + <_> + 9 15 1 4 3. + <_> + + <_> + 7 13 7 3 -1. + <_> + 7 14 7 1 3. + <_> + + <_> + 8 16 3 3 -1. + <_> + 9 16 1 3 3. + <_> + + <_> + 6 2 8 10 -1. + <_> + 6 7 8 5 2. + <_> + + <_> + 2 5 8 8 -1. + <_> + 2 9 8 4 2. + <_> + + <_> + 14 16 2 2 -1. + <_> + 14 17 2 1 2. + <_> + + <_> + 4 16 2 2 -1. + <_> + 4 17 2 1 2. + <_> + + <_> + 10 11 4 6 -1. + <_> + 10 14 4 3 2. + <_> + + <_> + 6 11 4 6 -1. + <_> + 6 14 4 3 2. + <_> + + <_> + 10 14 1 3 -1. + <_> + 10 15 1 1 3. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 10 0 4 6 -1. + <_> + 12 0 2 3 2. + <_> + 10 3 2 3 2. + <_> + + <_> + 0 3 20 2 -1. + <_> + 0 4 20 1 2. + <_> + + <_> + 12 0 8 2 -1. + <_> + 16 0 4 1 2. + <_> + 12 1 4 1 2. + <_> + + <_> + 2 12 10 8 -1. + <_> + 2 16 10 4 2. + <_> + + <_> + 17 7 2 10 -1. + <_> + 18 7 1 5 2. + <_> + 17 12 1 5 2. + <_> + + <_> + 1 7 2 10 -1. + <_> + 1 7 1 5 2. + <_> + 2 12 1 5 2. + <_> + + <_> + 15 10 3 6 -1. + <_> + 15 12 3 2 3. + <_> + + <_> + 4 4 6 2 -1. + <_> + 6 4 2 2 3. + <_> + + <_> + 0 5 20 6 -1. + <_> + 0 7 20 2 3. + <_> + + <_> + 0 0 8 2 -1. + <_> + 0 0 4 1 2. + <_> + 4 1 4 1 2. + <_> + + <_> + 1 0 18 4 -1. + <_> + 7 0 6 4 3. + <_> + + <_> + 1 13 6 2 -1. + <_> + 1 14 6 1 2. + <_> + + <_> + 10 8 3 4 -1. + <_> + 11 8 1 4 3. + <_> + + <_> + 6 1 6 1 -1. + <_> + 8 1 2 1 3. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 1 6 18 2 -1. + <_> + 10 6 9 2 2. + <_> + + <_> + 15 11 1 2 -1. + <_> + 15 12 1 1 2. + <_> + + <_> + 6 5 1 2 -1. + <_> + 6 6 1 1 2. + <_> + + <_> + 13 4 1 3 -1. + <_> + 13 5 1 1 3. + <_> + + <_> + 2 15 1 2 -1. + <_> + 2 16 1 1 2. + <_> + + <_> + 12 4 4 3 -1. + <_> + 12 5 4 1 3. + <_> + + <_> + 0 0 7 3 -1. + <_> + 0 1 7 1 3. + <_> + + <_> + 9 12 6 2 -1. + <_> + 9 12 3 2 2. + <_> + + <_> + 5 4 2 3 -1. + <_> + 5 5 2 1 3. + <_> + + <_> + 18 4 2 3 -1. + <_> + 18 5 2 1 3. + <_> + + <_> + 3 0 8 6 -1. + <_> + 3 2 8 2 3. + <_> + + <_> + 0 2 20 6 -1. + <_> + 10 2 10 3 2. + <_> + 0 5 10 3 2. + <_> + + <_> + 4 7 2 4 -1. + <_> + 5 7 1 4 2. + <_> + + <_> + 3 10 15 2 -1. + <_> + 8 10 5 2 3. + <_> + + <_> + 3 0 12 11 -1. + <_> + 9 0 6 11 2. + <_> + + <_> + 13 0 2 6 -1. + <_> + 13 0 1 6 2. + <_> + + <_> + 0 19 2 1 -1. + <_> + 1 19 1 1 2. + <_> + + <_> + 16 10 4 10 -1. + <_> + 18 10 2 5 2. + <_> + 16 15 2 5 2. + <_> + + <_> + 4 8 10 3 -1. + <_> + 4 9 10 1 3. + <_> + + <_> + 14 12 3 3 -1. + <_> + 14 13 3 1 3. + <_> + + <_> + 0 10 4 10 -1. + <_> + 0 10 2 5 2. + <_> + 2 15 2 5 2. + <_> + + <_> + 18 3 2 6 -1. + <_> + 18 5 2 2 3. + <_> + + <_> + 6 6 1 3 -1. + <_> + 6 7 1 1 3. + <_> + + <_> + 7 7 7 2 -1. + <_> + 7 8 7 1 2. + <_> + + <_> + 0 3 2 6 -1. + <_> + 0 5 2 2 3. + <_> + + <_> + 11 1 3 1 -1. + <_> + 12 1 1 1 3. + <_> + + <_> + 5 0 2 6 -1. + <_> + 6 0 1 6 2. + <_> + + <_> + 1 1 18 14 -1. + <_> + 7 1 6 14 3. + <_> + + <_> + 4 6 8 3 -1. + <_> + 8 6 4 3 2. + <_> + + <_> + 9 12 6 2 -1. + <_> + 9 12 3 2 2. + <_> + + <_> + 5 12 6 2 -1. + <_> + 8 12 3 2 2. + <_> + + <_> + 10 7 3 5 -1. + <_> + 11 7 1 5 3. + <_> + + <_> + 7 7 3 5 -1. + <_> + 8 7 1 5 3. + <_> + + <_> + 13 0 3 10 -1. + <_> + 14 0 1 10 3. + <_> + + <_> + 4 11 3 2 -1. + <_> + 4 12 3 1 2. + <_> + + <_> + 17 3 3 6 -1. + <_> + 18 3 1 6 3. + <_> + + <_> + 1 8 18 10 -1. + <_> + 1 13 18 5 2. + <_> + + <_> + 13 0 3 10 -1. + <_> + 14 0 1 10 3. + <_> + + <_> + 9 14 2 3 -1. + <_> + 9 15 2 1 3. + <_> + + <_> + 16 3 3 7 -1. + <_> + 17 3 1 7 3. + <_> + + <_> + 4 0 3 10 -1. + <_> + 5 0 1 10 3. + <_> + + <_> + 16 3 3 7 -1. + <_> + 17 3 1 7 3. + <_> + + <_> + 0 9 1 2 -1. + <_> + 0 10 1 1 2. + <_> + + <_> + 18 1 2 10 -1. + <_> + 18 1 1 10 2. + <_> + + <_> + 0 1 2 10 -1. + <_> + 1 1 1 10 2. + <_> + + <_> + 10 16 3 4 -1. + <_> + 11 16 1 4 3. + <_> + + <_> + 2 8 3 3 -1. + <_> + 3 8 1 3 3. + <_> + + <_> + 11 0 2 6 -1. + <_> + 12 0 1 3 2. + <_> + 11 3 1 3 2. + <_> + + <_> + 7 0 2 6 -1. + <_> + 7 0 1 3 2. + <_> + 8 3 1 3 2. + <_> + + <_> + 16 3 3 7 -1. + <_> + 17 3 1 7 3. + <_> + + <_> + 1 3 3 7 -1. + <_> + 2 3 1 7 3. + <_> + + <_> + 14 1 6 16 -1. + <_> + 16 1 2 16 3. + <_> + + <_> + 0 1 6 16 -1. + <_> + 2 1 2 16 3. + <_> + + <_> + 2 0 16 8 -1. + <_> + 10 0 8 4 2. + <_> + 2 4 8 4 2. + <_> + + <_> + 6 8 5 3 -1. + <_> + 6 9 5 1 3. + <_> + + <_> + 9 7 3 3 -1. + <_> + 10 7 1 3 3. + <_> + + <_> + 8 8 4 3 -1. + <_> + 8 9 4 1 3. + <_> + + <_> + 9 6 2 4 -1. + <_> + 9 6 1 4 2. + <_> + + <_> + 0 7 15 1 -1. + <_> + 5 7 5 1 3. + <_> + + <_> + 8 2 7 9 -1. + <_> + 8 5 7 3 3. + <_> + + <_> + 1 7 16 4 -1. + <_> + 1 7 8 2 2. + <_> + 9 9 8 2 2. + <_> + + <_> + 6 12 8 2 -1. + <_> + 6 13 8 1 2. + <_> + + <_> + 8 11 3 3 -1. + <_> + 8 12 3 1 3. + <_> + + <_> + 4 5 14 10 -1. + <_> + 11 5 7 5 2. + <_> + 4 10 7 5 2. + <_> + + <_> + 4 12 3 2 -1. + <_> + 4 13 3 1 2. + <_> + + <_> + 9 11 6 1 -1. + <_> + 11 11 2 1 3. + <_> + + <_> + 4 9 7 6 -1. + <_> + 4 11 7 2 3. + <_> + + <_> + 7 10 6 3 -1. + <_> + 7 11 6 1 3. + <_> + + <_> + 9 11 2 2 -1. + <_> + 9 12 2 1 2. + <_> + + <_> + 0 5 20 6 -1. + <_> + 0 7 20 2 3. + <_> + + <_> + 6 4 6 1 -1. + <_> + 8 4 2 1 3. + <_> + + <_> + 9 11 6 1 -1. + <_> + 11 11 2 1 3. + <_> + + <_> + 5 11 6 1 -1. + <_> + 7 11 2 1 3. + <_> + + <_> + 10 16 3 4 -1. + <_> + 11 16 1 4 3. + <_> + + <_> + 8 7 3 3 -1. + <_> + 9 7 1 3 3. + <_> + + <_> + 2 12 16 8 -1. + <_> + 2 16 16 4 2. + <_> + + <_> + 0 15 15 2 -1. + <_> + 0 16 15 1 2. + <_> + + <_> + 15 4 5 6 -1. + <_> + 15 6 5 2 3. + <_> + + <_> + 9 5 2 4 -1. + <_> + 10 5 1 4 2. + <_> + + <_> + 8 10 9 6 -1. + <_> + 8 12 9 2 3. + <_> + + <_> + 2 19 15 1 -1. + <_> + 7 19 5 1 3. + <_> + + <_> + 10 16 3 4 -1. + <_> + 11 16 1 4 3. + <_> + + <_> + 0 15 20 4 -1. + <_> + 0 17 20 2 2. + <_> + + <_> + 10 16 3 4 -1. + <_> + 11 16 1 4 3. + <_> + + <_> + 7 16 3 4 -1. + <_> + 8 16 1 4 3. + <_> + + <_> + 9 16 3 3 -1. + <_> + 9 17 3 1 3. + <_> + + <_> + 8 11 4 6 -1. + <_> + 8 14 4 3 2. + <_> + + <_> + 9 6 2 12 -1. + <_> + 9 10 2 4 3. + <_> + + <_> + 8 17 4 3 -1. + <_> + 8 18 4 1 3. + <_> + + <_> + 9 18 8 2 -1. + <_> + 13 18 4 1 2. + <_> + 9 19 4 1 2. + <_> + + <_> + 1 18 8 2 -1. + <_> + 1 19 8 1 2. + <_> + + <_> + 13 5 6 15 -1. + <_> + 15 5 2 15 3. + <_> + + <_> + 9 8 2 2 -1. + <_> + 9 9 2 1 2. + <_> + + <_> + 9 5 2 3 -1. + <_> + 9 5 1 3 2. + <_> + + <_> + 1 5 6 15 -1. + <_> + 3 5 2 15 3. + <_> + + <_> + 4 1 14 8 -1. + <_> + 11 1 7 4 2. + <_> + 4 5 7 4 2. + <_> + + <_> + 2 4 4 16 -1. + <_> + 2 4 2 8 2. + <_> + 4 12 2 8 2. + <_> + + <_> + 12 4 3 12 -1. + <_> + 12 10 3 6 2. + <_> + + <_> + 4 5 10 12 -1. + <_> + 4 5 5 6 2. + <_> + 9 11 5 6 2. + <_> + + <_> + 9 14 2 3 -1. + <_> + 9 15 2 1 3. + <_> + + <_> + 5 4 2 3 -1. + <_> + 5 5 2 1 3. + <_> + + <_> + 12 2 4 10 -1. + <_> + 14 2 2 5 2. + <_> + 12 7 2 5 2. + <_> + + <_> + 6 4 7 3 -1. + <_> + 6 5 7 1 3. + <_> + + <_> + 2 0 18 2 -1. + <_> + 11 0 9 1 2. + <_> + 2 1 9 1 2. + <_> + + <_> + 0 0 18 2 -1. + <_> + 0 0 9 1 2. + <_> + 9 1 9 1 2. + <_> + + <_> + 13 13 4 6 -1. + <_> + 15 13 2 3 2. + <_> + 13 16 2 3 2. + <_> + + <_> + 3 13 4 6 -1. + <_> + 3 13 2 3 2. + <_> + 5 16 2 3 2. + <_> + + <_> + 10 12 2 6 -1. + <_> + 10 15 2 3 2. + <_> + + <_> + 5 9 10 10 -1. + <_> + 5 9 5 5 2. + <_> + 10 14 5 5 2. + <_> + + <_> + 11 4 4 2 -1. + <_> + 13 4 2 1 2. + <_> + 11 5 2 1 2. + <_> + + <_> + 7 12 6 8 -1. + <_> + 10 12 3 8 2. + <_> + + <_> + 12 2 4 10 -1. + <_> + 14 2 2 5 2. + <_> + 12 7 2 5 2. + <_> + + <_> + 8 11 2 1 -1. + <_> + 9 11 1 1 2. + <_> + + <_> + 10 5 1 12 -1. + <_> + 10 9 1 4 3. + <_> + + <_> + 0 11 6 9 -1. + <_> + 3 11 3 9 2. + <_> + + <_> + 12 2 4 10 -1. + <_> + 14 2 2 5 2. + <_> + 12 7 2 5 2. + <_> + + <_> + 4 2 4 10 -1. + <_> + 4 2 2 5 2. + <_> + 6 7 2 5 2. + <_> + + <_> + 11 4 4 2 -1. + <_> + 13 4 2 1 2. + <_> + 11 5 2 1 2. + <_> + + <_> + 0 14 6 3 -1. + <_> + 0 15 6 1 3. + <_> + + <_> + 11 4 4 2 -1. + <_> + 13 4 2 1 2. + <_> + 11 5 2 1 2. + <_> + + <_> + 6 1 3 2 -1. + <_> + 7 1 1 2 3. + <_> + + <_> + 11 4 4 2 -1. + <_> + 13 4 2 1 2. + <_> + 11 5 2 1 2. + <_> + + <_> + 5 4 4 2 -1. + <_> + 5 4 2 1 2. + <_> + 7 5 2 1 2. + <_> + + <_> + 13 0 2 12 -1. + <_> + 14 0 1 6 2. + <_> + 13 6 1 6 2. + <_> + + <_> + 6 0 3 10 -1. + <_> + 7 0 1 10 3. + <_> + + <_> + 3 0 17 8 -1. + <_> + 3 4 17 4 2. + <_> + + <_> + 0 4 20 4 -1. + <_> + 0 6 20 2 2. + <_> + + <_> + 0 3 8 2 -1. + <_> + 4 3 4 2 2. + <_> + + <_> + 8 11 4 3 -1. + <_> + 8 12 4 1 3. + <_> + + <_> + 5 7 6 4 -1. + <_> + 5 7 3 2 2. + <_> + 8 9 3 2 2. + <_> + + <_> + 8 3 4 9 -1. + <_> + 8 6 4 3 3. + <_> + + <_> + 8 15 1 4 -1. + <_> + 8 17 1 2 2. + <_> + + <_> + 4 5 12 7 -1. + <_> + 8 5 4 7 3. + <_> + + <_> + 4 2 4 10 -1. + <_> + 4 2 2 5 2. + <_> + 6 7 2 5 2. + <_> + + <_> + 3 0 17 2 -1. + <_> + 3 1 17 1 2. + <_> + + <_> + 2 2 16 15 -1. + <_> + 2 7 16 5 3. + <_> + + <_> + 15 2 5 2 -1. + <_> + 15 3 5 1 2. + <_> + + <_> + 9 3 2 2 -1. + <_> + 10 3 1 2 2. + <_> + + <_> + 4 5 16 15 -1. + <_> + 4 10 16 5 3. + <_> + + <_> + 7 13 5 6 -1. + <_> + 7 16 5 3 2. + <_> + + <_> + 10 7 3 2 -1. + <_> + 11 7 1 2 3. + <_> + + <_> + 8 3 3 1 -1. + <_> + 9 3 1 1 3. + <_> + + <_> + 9 16 3 3 -1. + <_> + 9 17 3 1 3. + <_> + + <_> + 0 2 5 2 -1. + <_> + 0 3 5 1 2. + <_> + + <_> + 12 5 4 3 -1. + <_> + 12 6 4 1 3. + <_> + + <_> + 1 7 12 1 -1. + <_> + 5 7 4 1 3. + <_> + + <_> + 7 5 6 14 -1. + <_> + 7 12 6 7 2. + <_> + + <_> + 0 0 8 10 -1. + <_> + 0 0 4 5 2. + <_> + 4 5 4 5 2. + <_> + + <_> + 9 1 3 2 -1. + <_> + 10 1 1 2 3. + <_> + + <_> + 8 1 3 2 -1. + <_> + 9 1 1 2 3. + <_> + + <_> + 12 4 3 3 -1. + <_> + 12 5 3 1 3. + <_> + + <_> + 7 4 6 16 -1. + <_> + 7 12 6 8 2. + <_> + + <_> + 12 4 3 3 -1. + <_> + 12 5 3 1 3. + <_> + + <_> + 2 3 2 6 -1. + <_> + 2 5 2 2 3. + <_> + + <_> + 14 2 6 9 -1. + <_> + 14 5 6 3 3. + <_> + + <_> + 5 4 3 3 -1. + <_> + 5 5 3 1 3. + <_> + + <_> + 9 17 3 2 -1. + <_> + 10 17 1 2 3. + <_> + + <_> + 5 5 2 3 -1. + <_> + 5 6 2 1 3. + <_> + + <_> + 13 11 3 6 -1. + <_> + 13 13 3 2 3. + <_> + + <_> + 3 14 2 6 -1. + <_> + 3 17 2 3 2. + <_> + + <_> + 14 3 6 2 -1. + <_> + 14 4 6 1 2. + <_> + + <_> + 0 8 16 2 -1. + <_> + 0 9 16 1 2. + <_> + + <_> + 14 3 6 2 -1. + <_> + 14 4 6 1 2. + <_> + + <_> + 0 0 5 6 -1. + <_> + 0 2 5 2 3. + <_> + + <_> + 12 5 4 3 -1. + <_> + 12 6 4 1 3. + <_> + + <_> + 4 11 3 6 -1. + <_> + 4 13 3 2 3. + <_> + + <_> + 12 5 4 3 -1. + <_> + 12 6 4 1 3. + <_> + + <_> + 9 5 1 3 -1. + <_> + 9 6 1 1 3. + <_> + + <_> + 12 5 4 3 -1. + <_> + 12 6 4 1 3. + <_> + + <_> + 6 6 8 12 -1. + <_> + 6 12 8 6 2. + <_> + + <_> + 12 5 4 3 -1. + <_> + 12 6 4 1 3. + <_> + + <_> + 5 12 9 2 -1. + <_> + 8 12 3 2 3. + <_> + + <_> + 12 5 4 3 -1. + <_> + 12 6 4 1 3. + <_> + + <_> + 4 5 4 3 -1. + <_> + 4 6 4 1 3. + <_> + + <_> + 6 6 9 2 -1. + <_> + 9 6 3 2 3. + <_> + + <_> + 4 11 1 3 -1. + <_> + 4 12 1 1 3. + <_> + + <_> + 14 12 6 6 -1. + <_> + 14 12 3 6 2. + <_> + + <_> + 7 0 3 7 -1. + <_> + 8 0 1 7 3. + <_> + + <_> + 9 8 3 3 -1. + <_> + 10 8 1 3 3. + <_> + + <_> + 8 8 3 3 -1. + <_> + 9 8 1 3 3. + <_> + + <_> + 5 10 11 3 -1. + <_> + 5 11 11 1 3. + <_> + + <_> + 5 7 10 1 -1. + <_> + 10 7 5 1 2. + <_> + + <_> + 9 7 3 2 -1. + <_> + 10 7 1 2 3. + <_> + + <_> + 8 7 3 2 -1. + <_> + 9 7 1 2 3. + <_> + + <_> + 11 9 4 2 -1. + <_> + 11 9 2 2 2. + <_> + + <_> + 5 9 4 2 -1. + <_> + 7 9 2 2 2. + <_> + + <_> + 14 10 2 4 -1. + <_> + 14 12 2 2 2. + <_> + + <_> + 7 7 3 2 -1. + <_> + 8 7 1 2 3. + <_> + + <_> + 14 17 6 3 -1. + <_> + 14 18 6 1 3. + <_> + + <_> + 4 5 12 12 -1. + <_> + 4 5 6 6 2. + <_> + 10 11 6 6 2. + <_> + + <_> + 6 9 8 8 -1. + <_> + 10 9 4 4 2. + <_> + 6 13 4 4 2. + <_> + + <_> + 0 4 15 4 -1. + <_> + 5 4 5 4 3. + <_> + + <_> + 13 2 4 1 -1. + <_> + 13 2 2 1 2. + <_> + + <_> + 4 12 2 2 -1. + <_> + 4 13 2 1 2. + <_> + + <_> + 8 13 4 3 -1. + <_> + 8 14 4 1 3. + <_> + + <_> + 9 13 2 3 -1. + <_> + 9 14 2 1 3. + <_> + + <_> + 13 11 2 3 -1. + <_> + 13 12 2 1 3. + <_> + + <_> + 7 12 4 4 -1. + <_> + 7 12 2 2 2. + <_> + 9 14 2 2 2. + <_> + + <_> + 10 11 2 2 -1. + <_> + 11 11 1 1 2. + <_> + 10 12 1 1 2. + <_> + + <_> + 8 17 3 2 -1. + <_> + 9 17 1 2 3. + <_> + + <_> + 10 11 2 2 -1. + <_> + 11 11 1 1 2. + <_> + 10 12 1 1 2. + <_> + + <_> + 0 17 6 3 -1. + <_> + 0 18 6 1 3. + <_> + + <_> + 10 11 2 2 -1. + <_> + 11 11 1 1 2. + <_> + 10 12 1 1 2. + <_> + + <_> + 8 11 2 2 -1. + <_> + 8 11 1 1 2. + <_> + 9 12 1 1 2. + <_> + + <_> + 12 5 8 4 -1. + <_> + 12 5 4 4 2. + <_> + + <_> + 0 5 8 4 -1. + <_> + 4 5 4 4 2. + <_> + + <_> + 13 2 4 1 -1. + <_> + 13 2 2 1 2. + <_> + + <_> + 3 2 4 1 -1. + <_> + 5 2 2 1 2. + <_> + + <_> + 10 0 4 2 -1. + <_> + 12 0 2 1 2. + <_> + 10 1 2 1 2. + <_> + + <_> + 7 12 3 1 -1. + <_> + 8 12 1 1 3. + <_> + + <_> + 8 11 4 8 -1. + <_> + 10 11 2 4 2. + <_> + 8 15 2 4 2. + <_> + + <_> + 9 9 2 2 -1. + <_> + 9 10 2 1 2. + <_> + + <_> + 3 18 15 2 -1. + <_> + 3 19 15 1 2. + <_> + + <_> + 2 6 2 12 -1. + <_> + 2 6 1 6 2. + <_> + 3 12 1 6 2. + <_> + + <_> + 9 8 2 3 -1. + <_> + 9 9 2 1 3. + <_> + + <_> + 7 10 3 2 -1. + <_> + 8 10 1 2 3. + <_> + + <_> + 11 11 3 1 -1. + <_> + 12 11 1 1 3. + <_> + + <_> + 6 11 3 1 -1. + <_> + 7 11 1 1 3. + <_> + + <_> + 9 2 4 2 -1. + <_> + 11 2 2 1 2. + <_> + 9 3 2 1 2. + <_> + + <_> + 4 12 2 3 -1. + <_> + 4 13 2 1 3. + <_> + + <_> + 2 1 18 3 -1. + <_> + 8 1 6 3 3. + <_> + + <_> + 5 1 4 14 -1. + <_> + 7 1 2 14 2. + <_> + + <_> + 8 16 12 3 -1. + <_> + 8 16 6 3 2. + <_> + + <_> + 1 17 18 3 -1. + <_> + 7 17 6 3 3. + <_> + + <_> + 9 14 2 6 -1. + <_> + 9 17 2 3 2. + <_> + + <_> + 9 12 1 8 -1. + <_> + 9 16 1 4 2. + <_> + + <_> + 9 14 2 3 -1. + <_> + 9 15 2 1 3. + <_> + + <_> + 9 6 2 12 -1. + <_> + 9 10 2 4 3. + <_> + + <_> + 12 9 3 3 -1. + <_> + 12 10 3 1 3. + <_> + + <_> + 0 1 4 8 -1. + <_> + 2 1 2 8 2. + <_> + + <_> + 9 1 6 2 -1. + <_> + 12 1 3 1 2. + <_> + 9 2 3 1 2. + <_> + + <_> + 1 3 12 14 -1. + <_> + 1 10 12 7 2. + <_> + + <_> + 8 12 4 2 -1. + <_> + 10 12 2 1 2. + <_> + 8 13 2 1 2. + <_> + + <_> + 1 9 10 2 -1. + <_> + 1 9 5 1 2. + <_> + 6 10 5 1 2. + <_> + + <_> + 8 15 4 3 -1. + <_> + 8 16 4 1 3. + <_> + + <_> + 6 8 8 3 -1. + <_> + 6 9 8 1 3. + <_> + + <_> + 9 15 5 3 -1. + <_> + 9 16 5 1 3. + <_> + + <_> + 8 7 4 3 -1. + <_> + 8 8 4 1 3. + <_> + + <_> + 7 7 6 2 -1. + <_> + 7 8 6 1 2. + <_> + + <_> + 5 7 8 2 -1. + <_> + 5 7 4 1 2. + <_> + 9 8 4 1 2. + <_> + + <_> + 12 9 3 3 -1. + <_> + 12 10 3 1 3. + <_> + + <_> + 4 7 4 2 -1. + <_> + 4 8 4 1 2. + <_> + + <_> + 14 2 6 9 -1. + <_> + 14 5 6 3 3. + <_> + + <_> + 4 9 3 3 -1. + <_> + 5 9 1 3 3. + <_> + + <_> + 12 9 3 3 -1. + <_> + 12 10 3 1 3. + <_> + + <_> + 0 2 6 9 -1. + <_> + 0 5 6 3 3. + <_> + + <_> + 17 3 3 6 -1. + <_> + 18 3 1 6 3. + <_> + + <_> + 0 3 3 6 -1. + <_> + 1 3 1 6 3. + <_> + + <_> + 17 14 1 2 -1. + <_> + 17 15 1 1 2. + <_> + + <_> + 4 9 4 3 -1. + <_> + 6 9 2 3 2. + <_> + + <_> + 12 9 3 3 -1. + <_> + 12 10 3 1 3. + <_> + + <_> + 5 9 3 3 -1. + <_> + 5 10 3 1 3. + <_> + + <_> + 9 5 6 8 -1. + <_> + 12 5 3 4 2. + <_> + 9 9 3 4 2. + <_> + + <_> + 5 5 6 8 -1. + <_> + 5 5 3 4 2. + <_> + 8 9 3 4 2. + <_> + + <_> + 16 1 4 6 -1. + <_> + 16 4 4 3 2. + <_> + + <_> + 1 0 6 20 -1. + <_> + 3 0 2 20 3. + <_> + + <_> + 12 11 3 2 -1. + <_> + 13 11 1 2 3. + <_> + + <_> + 5 11 3 2 -1. + <_> + 6 11 1 2 3. + <_> + + <_> + 9 4 6 1 -1. + <_> + 11 4 2 1 3. + <_> + + <_> + 0 0 8 3 -1. + <_> + 4 0 4 3 2. + <_> + + <_> + 15 0 2 5 -1. + <_> + 15 0 1 5 2. + <_> + + <_> + 4 1 3 2 -1. + <_> + 5 1 1 2 3. + <_> + + <_> + 7 0 6 15 -1. + <_> + 9 0 2 15 3. + <_> + + <_> + 6 11 3 1 -1. + <_> + 7 11 1 1 3. + <_> + + <_> + 12 0 3 4 -1. + <_> + 13 0 1 4 3. + <_> + + <_> + 5 4 6 1 -1. + <_> + 7 4 2 1 3. + <_> + + <_> + 12 7 3 2 -1. + <_> + 12 8 3 1 2. + <_> + + <_> + 0 1 4 6 -1. + <_> + 0 4 4 3 2. + <_> + + <_> + 12 7 3 2 -1. + <_> + 12 8 3 1 2. + <_> + + <_> + 2 16 3 3 -1. + <_> + 2 17 3 1 3. + <_> + + <_> + 13 8 6 10 -1. + <_> + 16 8 3 5 2. + <_> + 13 13 3 5 2. + <_> + + <_> + 0 9 5 2 -1. + <_> + 0 10 5 1 2. + <_> + + <_> + 12 11 2 2 -1. + <_> + 13 11 1 1 2. + <_> + 12 12 1 1 2. + <_> + + <_> + 3 15 3 3 -1. + <_> + 3 16 3 1 3. + <_> + + <_> + 12 7 3 2 -1. + <_> + 12 8 3 1 2. + <_> + + <_> + 5 7 3 2 -1. + <_> + 5 8 3 1 2. + <_> + + <_> + 9 5 9 9 -1. + <_> + 9 8 9 3 3. + <_> + + <_> + 5 0 3 7 -1. + <_> + 6 0 1 7 3. + <_> + + <_> + 5 2 12 5 -1. + <_> + 9 2 4 5 3. + <_> + + <_> + 6 11 2 2 -1. + <_> + 6 11 1 1 2. + <_> + 7 12 1 1 2. + <_> + + <_> + 15 15 3 2 -1. + <_> + 15 16 3 1 2. + <_> + + <_> + 2 15 3 2 -1. + <_> + 2 16 3 1 2. + <_> + + <_> + 14 12 6 8 -1. + <_> + 17 12 3 4 2. + <_> + 14 16 3 4 2. + <_> + + <_> + 2 8 15 6 -1. + <_> + 7 8 5 6 3. + <_> + + <_> + 2 2 18 17 -1. + <_> + 8 2 6 17 3. + <_> + + <_> + 5 1 4 1 -1. + <_> + 7 1 2 1 2. + <_> + + <_> + 5 2 12 5 -1. + <_> + 9 2 4 5 3. + <_> + + <_> + 3 2 12 5 -1. + <_> + 7 2 4 5 3. + <_> + + <_> + 4 9 12 4 -1. + <_> + 10 9 6 2 2. + <_> + 4 11 6 2 2. + <_> + + <_> + 5 15 6 2 -1. + <_> + 5 15 3 1 2. + <_> + 8 16 3 1 2. + <_> + + <_> + 10 14 2 3 -1. + <_> + 10 15 2 1 3. + <_> + + <_> + 0 13 20 2 -1. + <_> + 0 13 10 1 2. + <_> + 10 14 10 1 2. + <_> + + <_> + 4 9 12 8 -1. + <_> + 10 9 6 4 2. + <_> + 4 13 6 4 2. + <_> + + <_> + 8 13 3 6 -1. + <_> + 8 16 3 3 2. + <_> + + <_> + 10 12 2 2 -1. + <_> + 10 13 2 1 2. + <_> + + <_> + 9 12 2 2 -1. + <_> + 9 12 1 1 2. + <_> + 10 13 1 1 2. + <_> + + <_> + 4 11 14 4 -1. + <_> + 11 11 7 2 2. + <_> + 4 13 7 2 2. + <_> + + <_> + 8 5 4 2 -1. + <_> + 8 6 4 1 2. + <_> + + <_> + 10 10 6 3 -1. + <_> + 12 10 2 3 3. + <_> + + <_> + 2 14 1 2 -1. + <_> + 2 15 1 1 2. + <_> + + <_> + 13 8 6 12 -1. + <_> + 16 8 3 6 2. + <_> + 13 14 3 6 2. + <_> + + <_> + 1 8 6 12 -1. + <_> + 1 8 3 6 2. + <_> + 4 14 3 6 2. + <_> + + <_> + 10 0 6 10 -1. + <_> + 12 0 2 10 3. + <_> + + <_> + 5 11 8 4 -1. + <_> + 5 11 4 2 2. + <_> + 9 13 4 2 2. + <_> + + <_> + 10 16 8 4 -1. + <_> + 14 16 4 2 2. + <_> + 10 18 4 2 2. + <_> + + <_> + 7 7 6 6 -1. + <_> + 9 7 2 6 3. + <_> + + <_> + 10 2 4 10 -1. + <_> + 10 2 2 10 2. + <_> + + <_> + 6 1 4 9 -1. + <_> + 8 1 2 9 2. + <_> + + <_> + 12 19 2 1 -1. + <_> + 12 19 1 1 2. + <_> + + <_> + 1 2 4 9 -1. + <_> + 3 2 2 9 2. + <_> + + <_> + 7 5 6 4 -1. + <_> + 9 5 2 4 3. + <_> + + <_> + 9 4 2 4 -1. + <_> + 9 6 2 2 2. + <_> + + <_> + 14 5 2 8 -1. + <_> + 14 9 2 4 2. + <_> + + <_> + 7 6 5 12 -1. + <_> + 7 12 5 6 2. + <_> + + <_> + 14 6 2 6 -1. + <_> + 14 9 2 3 2. + <_> + + <_> + 4 6 2 6 -1. + <_> + 4 9 2 3 2. + <_> + + <_> + 8 15 10 4 -1. + <_> + 13 15 5 2 2. + <_> + 8 17 5 2 2. + <_> + + <_> + 6 18 2 2 -1. + <_> + 7 18 1 2 2. + <_> + + <_> + 11 3 6 2 -1. + <_> + 11 4 6 1 2. + <_> + + <_> + 2 0 16 6 -1. + <_> + 2 2 16 2 3. + <_> + + <_> + 11 3 6 2 -1. + <_> + 11 4 6 1 2. + <_> + + <_> + 4 11 10 3 -1. + <_> + 4 12 10 1 3. + <_> + + <_> + 11 3 6 2 -1. + <_> + 11 4 6 1 2. + <_> + + <_> + 3 3 6 2 -1. + <_> + 3 4 6 1 2. + <_> + + <_> + 16 0 4 7 -1. + <_> + 16 0 2 7 2. + <_> + + <_> + 0 14 9 6 -1. + <_> + 0 16 9 2 3. + <_> + + <_> + 9 16 3 3 -1. + <_> + 9 17 3 1 3. + <_> + + <_> + 4 6 6 2 -1. + <_> + 6 6 2 2 3. + <_> + + <_> + 15 11 1 3 -1. + <_> + 15 12 1 1 3. + <_> + + <_> + 5 5 2 3 -1. + <_> + 5 6 2 1 3. + <_> + + <_> + 10 9 2 2 -1. + <_> + 10 10 2 1 2. + <_> + + <_> + 3 1 4 3 -1. + <_> + 5 1 2 3 2. + <_> + + <_> + 16 0 4 7 -1. + <_> + 16 0 2 7 2. + <_> + + <_> + 0 0 20 1 -1. + <_> + 10 0 10 1 2. + <_> + + <_> + 15 11 1 3 -1. + <_> + 15 12 1 1 3. + <_> + + <_> + 0 4 3 4 -1. + <_> + 1 4 1 4 3. + <_> + + <_> + 16 3 3 6 -1. + <_> + 16 5 3 2 3. + <_> + + <_> + 1 3 3 6 -1. + <_> + 1 5 3 2 3. + <_> + + <_> + 6 2 12 6 -1. + <_> + 12 2 6 3 2. + <_> + 6 5 6 3 2. + <_> + + <_> + 8 10 4 3 -1. + <_> + 8 11 4 1 3. + <_> + + <_> + 4 2 14 6 -1. + <_> + 11 2 7 3 2. + <_> + 4 5 7 3 2. + <_> + + <_> + 9 11 2 3 -1. + <_> + 9 12 2 1 3. + <_> + + <_> + 15 13 2 3 -1. + <_> + 15 14 2 1 3. + <_> + + <_> + 8 12 4 3 -1. + <_> + 8 13 4 1 3. + <_> + + <_> + 15 11 1 3 -1. + <_> + 15 12 1 1 3. + <_> + + <_> + 7 13 5 2 -1. + <_> + 7 14 5 1 2. + <_> + + <_> + 7 12 6 3 -1. + <_> + 7 13 6 1 3. + <_> + + <_> + 5 11 4 4 -1. + <_> + 5 13 4 2 2. + <_> + + <_> + 11 4 3 3 -1. + <_> + 12 4 1 3 3. + <_> + + <_> + 6 4 3 3 -1. + <_> + 7 4 1 3 3. + <_> + + <_> + 16 5 3 6 -1. + <_> + 17 5 1 6 3. + <_> + + <_> + 3 6 12 7 -1. + <_> + 7 6 4 7 3. + <_> + + <_> + 16 5 3 6 -1. + <_> + 17 5 1 6 3. + <_> + + <_> + 3 13 2 3 -1. + <_> + 3 14 2 1 3. + <_> + + <_> + 16 5 3 6 -1. + <_> + 17 5 1 6 3. + <_> + + <_> + 1 5 3 6 -1. + <_> + 2 5 1 6 3. + <_> + + <_> + 1 9 18 1 -1. + <_> + 7 9 6 1 3. + <_> + + <_> + 0 9 8 7 -1. + <_> + 4 9 4 7 2. + <_> + + <_> + 12 11 8 2 -1. + <_> + 12 12 8 1 2. + <_> + + <_> + 0 11 8 2 -1. + <_> + 0 12 8 1 2. + <_> + + <_> + 9 13 2 3 -1. + <_> + 9 14 2 1 3. + <_> + + <_> + 4 10 12 4 -1. + <_> + 4 10 6 2 2. + <_> + 10 12 6 2 2. + <_> + + <_> + 9 3 3 7 -1. + <_> + 10 3 1 7 3. + <_> + + <_> + 7 2 3 5 -1. + <_> + 8 2 1 5 3. + <_> + + <_> + 9 12 4 6 -1. + <_> + 11 12 2 3 2. + <_> + 9 15 2 3 2. + <_> + + <_> + 8 7 3 6 -1. + <_> + 9 7 1 6 3. + <_> + + <_> + 15 4 4 2 -1. + <_> + 15 5 4 1 2. + <_> + + <_> + 8 7 3 3 -1. + <_> + 9 7 1 3 3. + <_> + + <_> + 14 2 6 4 -1. + <_> + 14 4 6 2 2. + <_> + + <_> + 7 16 6 1 -1. + <_> + 9 16 2 1 3. + <_> + + <_> + 15 13 2 3 -1. + <_> + 15 14 2 1 3. + <_> + + <_> + 8 7 3 10 -1. + <_> + 9 7 1 10 3. + <_> + + <_> + 11 10 2 6 -1. + <_> + 11 12 2 2 3. + <_> + + <_> + 6 10 4 1 -1. + <_> + 8 10 2 1 2. + <_> + + <_> + 10 9 2 2 -1. + <_> + 10 10 2 1 2. + <_> + + <_> + 8 9 2 2 -1. + <_> + 8 10 2 1 2. + <_> + + <_> + 12 7 2 2 -1. + <_> + 13 7 1 1 2. + <_> + 12 8 1 1 2. + <_> + + <_> + 5 7 2 2 -1. + <_> + 5 7 1 1 2. + <_> + 6 8 1 1 2. + <_> + + <_> + 13 0 3 14 -1. + <_> + 14 0 1 14 3. + <_> + + <_> + 4 0 3 14 -1. + <_> + 5 0 1 14 3. + <_> + + <_> + 13 4 3 14 -1. + <_> + 14 4 1 14 3. + <_> + + <_> + 9 14 2 3 -1. + <_> + 9 15 2 1 3. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 4 2 3 16 -1. + <_> + 5 2 1 16 3. + <_> + + <_> + 7 2 8 10 -1. + <_> + 7 7 8 5 2. + <_> + + <_> + 6 14 7 3 -1. + <_> + 6 15 7 1 3. + <_> + + <_> + 9 2 10 12 -1. + <_> + 14 2 5 6 2. + <_> + 9 8 5 6 2. + <_> + + <_> + 6 7 8 2 -1. + <_> + 6 8 8 1 2. + <_> + + <_> + 8 13 4 6 -1. + <_> + 8 16 4 3 2. + <_> + + <_> + 6 6 1 3 -1. + <_> + 6 7 1 1 3. + <_> + + <_> + 16 2 4 6 -1. + <_> + 16 4 4 2 3. + <_> + + <_> + 6 6 4 2 -1. + <_> + 6 6 2 1 2. + <_> + 8 7 2 1 2. + <_> + + <_> + 16 2 4 6 -1. + <_> + 16 4 4 2 3. + <_> + + <_> + 0 2 4 6 -1. + <_> + 0 4 4 2 3. + <_> + + <_> + 9 6 2 6 -1. + <_> + 9 6 1 6 2. + <_> + + <_> + 3 4 6 10 -1. + <_> + 3 9 6 5 2. + <_> + + <_> + 9 5 2 6 -1. + <_> + 9 5 1 6 2. + <_> + + <_> + 3 13 2 3 -1. + <_> + 3 14 2 1 3. + <_> + + <_> + 13 13 3 2 -1. + <_> + 13 14 3 1 2. + <_> + + <_> + 2 16 10 4 -1. + <_> + 2 16 5 2 2. + <_> + 7 18 5 2 2. + <_> + + <_> + 5 6 10 6 -1. + <_> + 10 6 5 3 2. + <_> + 5 9 5 3 2. + <_> + + <_> + 7 14 1 3 -1. + <_> + 7 15 1 1 3. + <_> + + <_> + 14 16 6 3 -1. + <_> + 14 17 6 1 3. + <_> + + <_> + 5 4 3 3 -1. + <_> + 5 5 3 1 3. + <_> + + <_> + 7 4 10 3 -1. + <_> + 7 5 10 1 3. + <_> + + <_> + 0 4 5 4 -1. + <_> + 0 6 5 2 2. + <_> + + <_> + 13 11 3 9 -1. + <_> + 13 14 3 3 3. + <_> + + <_> + 4 11 3 9 -1. + <_> + 4 14 3 3 3. + <_> + + <_> + 9 7 2 1 -1. + <_> + 9 7 1 1 2. + <_> + + <_> + 5 0 6 17 -1. + <_> + 7 0 2 17 3. + <_> + + <_> + 10 3 6 3 -1. + <_> + 10 3 3 3 2. + <_> + + <_> + 2 2 15 4 -1. + <_> + 7 2 5 4 3. + <_> + + <_> + 8 2 8 2 -1. + <_> + 12 2 4 1 2. + <_> + 8 3 4 1 2. + <_> + + <_> + 8 1 3 6 -1. + <_> + 8 3 3 2 3. + <_> + + <_> + 9 17 2 2 -1. + <_> + 9 18 2 1 2. + <_> + + <_> + 0 0 2 14 -1. + <_> + 1 0 1 14 2. + <_> + + <_> + 12 0 7 3 -1. + <_> + 12 1 7 1 3. + <_> + + <_> + 1 14 1 2 -1. + <_> + 1 15 1 1 2. + <_> + + <_> + 14 12 2 8 -1. + <_> + 15 12 1 4 2. + <_> + 14 16 1 4 2. + <_> + + <_> + 1 0 7 3 -1. + <_> + 1 1 7 1 3. + <_> + + <_> + 14 12 2 8 -1. + <_> + 15 12 1 4 2. + <_> + 14 16 1 4 2. + <_> + + <_> + 6 0 8 12 -1. + <_> + 6 0 4 6 2. + <_> + 10 6 4 6 2. + <_> + + <_> + 6 1 8 9 -1. + <_> + 6 4 8 3 3. + <_> + + <_> + 5 2 2 2 -1. + <_> + 5 3 2 1 2. + <_> + + <_> + 13 14 6 6 -1. + <_> + 16 14 3 3 2. + <_> + 13 17 3 3 2. + <_> + + <_> + 0 17 20 2 -1. + <_> + 0 17 10 1 2. + <_> + 10 18 10 1 2. + <_> + + <_> + 10 3 2 6 -1. + <_> + 11 3 1 3 2. + <_> + 10 6 1 3 2. + <_> + + <_> + 5 12 6 2 -1. + <_> + 8 12 3 2 2. + <_> + + <_> + 10 7 6 13 -1. + <_> + 10 7 3 13 2. + <_> + + <_> + 5 15 10 5 -1. + <_> + 10 15 5 5 2. + <_> + + <_> + 10 4 4 10 -1. + <_> + 10 4 2 10 2. + <_> + + <_> + 5 7 2 1 -1. + <_> + 6 7 1 1 2. + <_> + + <_> + 10 3 6 7 -1. + <_> + 10 3 3 7 2. + <_> + + <_> + 4 3 6 7 -1. + <_> + 7 3 3 7 2. + <_> + + <_> + 1 7 18 5 -1. + <_> + 7 7 6 5 3. + <_> + + <_> + 3 17 4 3 -1. + <_> + 5 17 2 3 2. + <_> + + <_> + 8 14 12 6 -1. + <_> + 14 14 6 3 2. + <_> + 8 17 6 3 2. + <_> + + <_> + 0 13 20 4 -1. + <_> + 0 13 10 2 2. + <_> + 10 15 10 2 2. + <_> + + <_> + 4 5 14 2 -1. + <_> + 11 5 7 1 2. + <_> + 4 6 7 1 2. + <_> + + <_> + 1 2 10 12 -1. + <_> + 1 2 5 6 2. + <_> + 6 8 5 6 2. + <_> + + <_> + 6 1 14 3 -1. + <_> + 6 2 14 1 3. + <_> + + <_> + 8 16 2 3 -1. + <_> + 8 17 2 1 3. + <_> + + <_> + 9 17 3 2 -1. + <_> + 10 17 1 2 3. + <_> + + <_> + 5 15 4 2 -1. + <_> + 5 15 2 1 2. + <_> + 7 16 2 1 2. + <_> + + <_> + 10 15 1 3 -1. + <_> + 10 16 1 1 3. + <_> + + <_> + 8 16 4 4 -1. + <_> + 8 16 2 2 2. + <_> + 10 18 2 2 2. + <_> + + <_> + 6 11 8 6 -1. + <_> + 6 14 8 3 2. + <_> + + <_> + 2 13 5 2 -1. + <_> + 2 14 5 1 2. + <_> + + <_> + 13 14 6 6 -1. + <_> + 16 14 3 3 2. + <_> + 13 17 3 3 2. + <_> + + <_> + 1 9 18 4 -1. + <_> + 7 9 6 4 3. + <_> + + <_> + 13 14 6 6 -1. + <_> + 16 14 3 3 2. + <_> + 13 17 3 3 2. + <_> + + <_> + 0 2 1 6 -1. + <_> + 0 4 1 2 3. + <_> + + <_> + 5 0 15 20 -1. + <_> + 5 10 15 10 2. + <_> + + <_> + 1 14 6 6 -1. + <_> + 1 14 3 3 2. + <_> + 4 17 3 3 2. + <_> + + <_> + 8 14 4 6 -1. + <_> + 10 14 2 3 2. + <_> + 8 17 2 3 2. + <_> + + <_> + 7 11 2 1 -1. + <_> + 8 11 1 1 2. + <_> + + <_> + 9 17 3 2 -1. + <_> + 10 17 1 2 3. + <_> + + <_> + 8 17 3 2 -1. + <_> + 9 17 1 2 3. + <_> + + <_> + 12 14 4 6 -1. + <_> + 14 14 2 3 2. + <_> + 12 17 2 3 2. + <_> + + <_> + 4 14 4 6 -1. + <_> + 4 14 2 3 2. + <_> + 6 17 2 3 2. + <_> + + <_> + 13 14 2 6 -1. + <_> + 14 14 1 3 2. + <_> + 13 17 1 3 2. + <_> + + <_> + 5 14 2 6 -1. + <_> + 5 14 1 3 2. + <_> + 6 17 1 3 2. + <_> + + <_> + 7 0 6 12 -1. + <_> + 7 4 6 4 3. + <_> + + <_> + 0 7 12 2 -1. + <_> + 4 7 4 2 3. + <_> + + <_> + 10 3 3 13 -1. + <_> + 11 3 1 13 3. + <_> + + <_> + 7 3 3 13 -1. + <_> + 8 3 1 13 3. + <_> + + <_> + 10 8 6 3 -1. + <_> + 10 9 6 1 3. + <_> + + <_> + 3 11 3 2 -1. + <_> + 4 11 1 2 3. + <_> + + <_> + 13 12 6 8 -1. + <_> + 16 12 3 4 2. + <_> + 13 16 3 4 2. + <_> + + <_> + 7 6 6 5 -1. + <_> + 9 6 2 5 3. + <_> + + <_> + 17 11 2 7 -1. + <_> + 17 11 1 7 2. + <_> + + <_> + 3 13 8 2 -1. + <_> + 7 13 4 2 2. + <_> + + <_> + 6 9 8 3 -1. + <_> + 6 10 8 1 3. + <_> + + <_> + 4 3 4 3 -1. + <_> + 4 4 4 1 3. + <_> + + <_> + 11 3 4 3 -1. + <_> + 11 4 4 1 3. + <_> + + <_> + 1 4 17 12 -1. + <_> + 1 8 17 4 3. + <_> + + <_> + 11 3 4 3 -1. + <_> + 11 4 4 1 3. + <_> + + <_> + 4 8 6 3 -1. + <_> + 4 9 6 1 3. + <_> + + <_> + 12 3 5 3 -1. + <_> + 12 4 5 1 3. + <_> + + <_> + 1 11 2 7 -1. + <_> + 2 11 1 7 2. + <_> + + <_> + 15 12 2 8 -1. + <_> + 16 12 1 4 2. + <_> + 15 16 1 4 2. + <_> + + <_> + 4 8 11 3 -1. + <_> + 4 9 11 1 3. + <_> + + <_> + 9 13 6 2 -1. + <_> + 12 13 3 1 2. + <_> + 9 14 3 1 2. + <_> + + <_> + 6 13 4 3 -1. + <_> + 6 14 4 1 3. + <_> + + <_> + 9 12 3 3 -1. + <_> + 10 12 1 3 3. + <_> + + <_> + 5 3 3 3 -1. + <_> + 5 4 3 1 3. + <_> + + <_> + 9 4 2 3 -1. + <_> + 9 5 2 1 3. + <_> + + <_> + 0 2 16 3 -1. + <_> + 0 3 16 1 3. + <_> + + <_> + 15 12 2 8 -1. + <_> + 16 12 1 4 2. + <_> + 15 16 1 4 2. + <_> + + <_> + 3 12 2 8 -1. + <_> + 3 12 1 4 2. + <_> + 4 16 1 4 2. + <_> + + <_> + 14 13 3 6 -1. + <_> + 14 15 3 2 3. + <_> + + <_> + 3 13 3 6 -1. + <_> + 3 15 3 2 3. + <_> + + <_> + 6 5 10 2 -1. + <_> + 11 5 5 1 2. + <_> + 6 6 5 1 2. + <_> + + <_> + 2 14 14 6 -1. + <_> + 2 17 14 3 2. + <_> + + <_> + 10 14 1 3 -1. + <_> + 10 15 1 1 3. + <_> + + <_> + 4 16 2 2 -1. + <_> + 4 16 1 1 2. + <_> + 5 17 1 1 2. + <_> + + <_> + 10 6 2 3 -1. + <_> + 10 7 2 1 3. + <_> + + <_> + 0 17 20 2 -1. + <_> + 0 17 10 1 2. + <_> + 10 18 10 1 2. + <_> + + <_> + 13 6 1 3 -1. + <_> + 13 7 1 1 3. + <_> + + <_> + 8 13 3 2 -1. + <_> + 9 13 1 2 3. + <_> + + <_> + 12 2 3 3 -1. + <_> + 13 2 1 3 3. + <_> + + <_> + 3 18 2 2 -1. + <_> + 3 18 1 1 2. + <_> + 4 19 1 1 2. + <_> + + <_> + 9 16 3 4 -1. + <_> + 10 16 1 4 3. + <_> + + <_> + 6 6 1 3 -1. + <_> + 6 7 1 1 3. + <_> + + <_> + 13 1 5 2 -1. + <_> + 13 2 5 1 2. + <_> + + <_> + 7 14 6 2 -1. + <_> + 7 14 3 1 2. + <_> + 10 15 3 1 2. + <_> + + <_> + 11 3 3 4 -1. + <_> + 12 3 1 4 3. + <_> + + <_> + 1 13 12 6 -1. + <_> + 5 13 4 6 3. + <_> + + <_> + 14 11 5 2 -1. + <_> + 14 12 5 1 2. + <_> + + <_> + 2 15 14 4 -1. + <_> + 2 15 7 2 2. + <_> + 9 17 7 2 2. + <_> + + <_> + 3 7 14 2 -1. + <_> + 10 7 7 1 2. + <_> + 3 8 7 1 2. + <_> + + <_> + 1 11 4 2 -1. + <_> + 1 12 4 1 2. + <_> + + <_> + 14 0 6 14 -1. + <_> + 16 0 2 14 3. + <_> + + <_> + 4 11 1 3 -1. + <_> + 4 12 1 1 3. + <_> + + <_> + 14 0 6 14 -1. + <_> + 16 0 2 14 3. + <_> + + <_> + 1 10 3 7 -1. + <_> + 2 10 1 7 3. + <_> + + <_> + 8 12 9 2 -1. + <_> + 8 13 9 1 2. + <_> + + <_> + 0 6 20 1 -1. + <_> + 10 6 10 1 2. + <_> + + <_> + 8 4 4 4 -1. + <_> + 8 4 2 4 2. + <_> + + <_> + 0 0 2 2 -1. + <_> + 0 1 2 1 2. + <_> + + <_> + 5 3 10 9 -1. + <_> + 5 6 10 3 3. + <_> + + <_> + 15 2 4 10 -1. + <_> + 15 2 2 10 2. + <_> + + <_> + 8 2 2 7 -1. + <_> + 9 2 1 7 2. + <_> + + <_> + 7 4 12 1 -1. + <_> + 11 4 4 1 3. + <_> + + <_> + 3 4 9 1 -1. + <_> + 6 4 3 1 3. + <_> + + <_> + 15 10 1 4 -1. + <_> + 15 12 1 2 2. + <_> + + <_> + 4 10 6 4 -1. + <_> + 7 10 3 4 2. + <_> + + <_> + 15 9 1 6 -1. + <_> + 15 12 1 3 2. + <_> + + <_> + 7 17 6 3 -1. + <_> + 7 18 6 1 3. + <_> + + <_> + 14 3 2 16 -1. + <_> + 15 3 1 8 2. + <_> + 14 11 1 8 2. + <_> + + <_> + 4 9 1 6 -1. + <_> + 4 12 1 3 2. + <_> + + <_> + 12 1 5 2 -1. + <_> + 12 2 5 1 2. + <_> + + <_> + 6 18 4 2 -1. + <_> + 6 18 2 1 2. + <_> + 8 19 2 1 2. + <_> + + <_> + 2 4 16 10 -1. + <_> + 10 4 8 5 2. + <_> + 2 9 8 5 2. + <_> + + <_> + 6 5 1 10 -1. + <_> + 6 10 1 5 2. + <_> + + <_> + 4 8 15 2 -1. + <_> + 9 8 5 2 3. + <_> + + <_> + 1 8 15 2 -1. + <_> + 6 8 5 2 3. + <_> + + <_> + 9 5 3 6 -1. + <_> + 9 7 3 2 3. + <_> + + <_> + 5 7 8 2 -1. + <_> + 9 7 4 2 2. + <_> + + <_> + 9 11 2 3 -1. + <_> + 9 12 2 1 3. + <_> + + <_> + 1 0 16 3 -1. + <_> + 1 1 16 1 3. + <_> + + <_> + 11 2 7 2 -1. + <_> + 11 3 7 1 2. + <_> + + <_> + 5 1 10 18 -1. + <_> + 5 7 10 6 3. + <_> + + <_> + 17 4 3 2 -1. + <_> + 18 4 1 2 3. + <_> + + <_> + 8 13 1 3 -1. + <_> + 8 14 1 1 3. + <_> + + <_> + 3 14 14 6 -1. + <_> + 3 16 14 2 3. + <_> + + <_> + 0 2 3 4 -1. + <_> + 1 2 1 4 3. + <_> + + <_> + 12 1 5 2 -1. + <_> + 12 2 5 1 2. + <_> + + <_> + 3 1 5 2 -1. + <_> + 3 2 5 1 2. + <_> + + <_> + 10 13 2 3 -1. + <_> + 10 14 2 1 3. + <_> + + <_> + 8 13 2 3 -1. + <_> + 8 14 2 1 3. + <_> + + <_> + 14 12 2 3 -1. + <_> + 14 13 2 1 3. + <_> + + <_> + 7 2 2 3 -1. + <_> + 7 3 2 1 3. + <_> + + <_> + 5 6 10 4 -1. + <_> + 10 6 5 2 2. + <_> + 5 8 5 2 2. + <_> + + <_> + 9 13 1 6 -1. + <_> + 9 16 1 3 2. + <_> + + <_> + 10 12 2 2 -1. + <_> + 11 12 1 1 2. + <_> + 10 13 1 1 2. + <_> + + <_> + 4 12 2 3 -1. + <_> + 4 13 2 1 3. + <_> + + <_> + 14 4 6 6 -1. + <_> + 14 6 6 2 3. + <_> + + <_> + 8 17 2 3 -1. + <_> + 8 18 2 1 3. + <_> + + <_> + 16 4 4 6 -1. + <_> + 16 6 4 2 3. + <_> + + <_> + 0 4 4 6 -1. + <_> + 0 6 4 2 3. + <_> + + <_> + 14 6 2 3 -1. + <_> + 14 6 1 3 2. + <_> + + <_> + 4 9 8 1 -1. + <_> + 8 9 4 1 2. + <_> + + <_> + 8 12 4 3 -1. + <_> + 8 13 4 1 3. + <_> + + <_> + 5 12 10 6 -1. + <_> + 5 14 10 2 3. + <_> + + <_> + 11 12 1 2 -1. + <_> + 11 13 1 1 2. + <_> + + <_> + 8 15 4 2 -1. + <_> + 8 16 4 1 2. + <_> + + <_> + 6 9 8 8 -1. + <_> + 10 9 4 4 2. + <_> + 6 13 4 4 2. + <_> + + <_> + 7 12 4 6 -1. + <_> + 7 12 2 3 2. + <_> + 9 15 2 3 2. + <_> + + <_> + 10 11 3 1 -1. + <_> + 11 11 1 1 3. + <_> + + <_> + 9 7 2 10 -1. + <_> + 9 7 1 5 2. + <_> + 10 12 1 5 2. + <_> + + <_> + 8 0 6 6 -1. + <_> + 10 0 2 6 3. + <_> + + <_> + 3 11 2 6 -1. + <_> + 3 13 2 2 3. + <_> + + <_> + 16 12 1 2 -1. + <_> + 16 13 1 1 2. + <_> + + <_> + 1 14 6 6 -1. + <_> + 1 14 3 3 2. + <_> + 4 17 3 3 2. + <_> + + <_> + 13 1 3 6 -1. + <_> + 14 1 1 6 3. + <_> + + <_> + 8 8 2 2 -1. + <_> + 8 9 2 1 2. + <_> + + <_> + 9 9 3 3 -1. + <_> + 10 9 1 3 3. + <_> + + <_> + 8 7 3 3 -1. + <_> + 8 8 3 1 3. + <_> + + <_> + 14 0 2 3 -1. + <_> + 14 0 1 3 2. + <_> + + <_> + 1 0 18 9 -1. + <_> + 7 0 6 9 3. + <_> + + <_> + 11 5 4 15 -1. + <_> + 11 5 2 15 2. + <_> + + <_> + 5 5 4 15 -1. + <_> + 7 5 2 15 2. + <_> + + <_> + 14 0 2 3 -1. + <_> + 14 0 1 3 2. + <_> + + <_> + 4 0 2 3 -1. + <_> + 5 0 1 3 2. + <_> + + <_> + 11 12 2 2 -1. + <_> + 12 12 1 1 2. + <_> + 11 13 1 1 2. + <_> + + <_> + 7 12 2 2 -1. + <_> + 7 12 1 1 2. + <_> + 8 13 1 1 2. + <_> + + <_> + 12 0 3 4 -1. + <_> + 13 0 1 4 3. + <_> + + <_> + 4 11 3 3 -1. + <_> + 4 12 3 1 3. + <_> + + <_> + 12 7 4 2 -1. + <_> + 12 8 4 1 2. + <_> + + <_> + 8 10 3 2 -1. + <_> + 9 10 1 2 3. + <_> + + <_> + 9 9 3 2 -1. + <_> + 10 9 1 2 3. + <_> + + <_> + 8 9 3 2 -1. + <_> + 9 9 1 2 3. + <_> + + <_> + 12 0 3 4 -1. + <_> + 13 0 1 4 3. + <_> + + <_> + 5 0 3 4 -1. + <_> + 6 0 1 4 3. + <_> + + <_> + 4 14 12 4 -1. + <_> + 10 14 6 2 2. + <_> + 4 16 6 2 2. + <_> + + <_> + 8 13 2 3 -1. + <_> + 8 14 2 1 3. + <_> + + <_> + 10 10 3 8 -1. + <_> + 10 14 3 4 2. + <_> + + <_> + 8 10 4 8 -1. + <_> + 8 10 2 4 2. + <_> + 10 14 2 4 2. + <_> + + <_> + 10 8 3 1 -1. + <_> + 11 8 1 1 3. + <_> + + <_> + 9 12 1 6 -1. + <_> + 9 15 1 3 2. + <_> + + <_> + 10 8 3 1 -1. + <_> + 11 8 1 1 3. + <_> + + <_> + 7 8 3 1 -1. + <_> + 8 8 1 1 3. + <_> + + <_> + 5 2 15 14 -1. + <_> + 5 9 15 7 2. + <_> + + <_> + 2 1 2 10 -1. + <_> + 2 1 1 5 2. + <_> + 3 6 1 5 2. + <_> + + <_> + 14 14 2 3 -1. + <_> + 14 15 2 1 3. + <_> + + <_> + 2 7 3 3 -1. + <_> + 3 7 1 3 3. + <_> + + <_> + 17 4 3 3 -1. + <_> + 17 5 3 1 3. + <_> + + <_> + 0 4 3 3 -1. + <_> + 0 5 3 1 3. + <_> + + <_> + 13 5 6 2 -1. + <_> + 16 5 3 1 2. + <_> + 13 6 3 1 2. + <_> + + <_> + 4 19 12 1 -1. + <_> + 8 19 4 1 3. + <_> + + <_> + 12 12 2 4 -1. + <_> + 12 14 2 2 2. + <_> + + <_> + 3 15 1 3 -1. + <_> + 3 16 1 1 3. + <_> + + <_> + 11 16 6 4 -1. + <_> + 11 16 3 4 2. + <_> + + <_> + 2 10 3 10 -1. + <_> + 3 10 1 10 3. + <_> + + <_> + 12 8 2 4 -1. + <_> + 12 8 1 4 2. + <_> + + <_> + 6 8 2 4 -1. + <_> + 7 8 1 4 2. + <_> + + <_> + 10 14 2 3 -1. + <_> + 10 14 1 3 2. + <_> + + <_> + 5 1 10 3 -1. + <_> + 10 1 5 3 2. + <_> + + <_> + 10 7 3 2 -1. + <_> + 11 7 1 2 3. + <_> + + <_> + 5 6 9 2 -1. + <_> + 8 6 3 2 3. + <_> + + <_> + 9 8 2 2 -1. + <_> + 9 9 2 1 2. + <_> + + <_> + 2 11 16 6 -1. + <_> + 2 11 8 3 2. + <_> + 10 14 8 3 2. + <_> + + <_> + 12 7 2 2 -1. + <_> + 13 7 1 1 2. + <_> + 12 8 1 1 2. + <_> + + <_> + 9 5 2 3 -1. + <_> + 9 6 2 1 3. + <_> + + <_> + 9 7 3 2 -1. + <_> + 10 7 1 2 3. + <_> + + <_> + 5 1 8 12 -1. + <_> + 5 7 8 6 2. + <_> + + <_> + 13 5 2 2 -1. + <_> + 13 6 2 1 2. + <_> + + <_> + 5 5 2 2 -1. + <_> + 5 6 2 1 2. + <_> + + <_> + 12 4 3 3 -1. + <_> + 12 5 3 1 3. + <_> + + <_> + 4 14 2 3 -1. + <_> + 4 15 2 1 3. + <_> + + <_> + 12 4 3 3 -1. + <_> + 12 5 3 1 3. + <_> + + <_> + 5 4 3 3 -1. + <_> + 5 5 3 1 3. + <_> + + <_> + 9 14 2 6 -1. + <_> + 10 14 1 3 2. + <_> + 9 17 1 3 2. + <_> + + <_> + 8 14 3 2 -1. + <_> + 9 14 1 2 3. + <_> + + <_> + 9 5 6 6 -1. + <_> + 11 5 2 6 3. + <_> + + <_> + 5 5 6 6 -1. + <_> + 7 5 2 6 3. + <_> + + <_> + 13 13 1 2 -1. + <_> + 13 14 1 1 2. + <_> + + <_> + 0 2 10 2 -1. + <_> + 0 3 10 1 2. + <_> + + <_> + 13 13 1 2 -1. + <_> + 13 14 1 1 2. + <_> + + <_> + 5 7 2 2 -1. + <_> + 5 7 1 1 2. + <_> + 6 8 1 1 2. + <_> + + <_> + 13 5 2 7 -1. + <_> + 13 5 1 7 2. + <_> + + <_> + 6 13 1 2 -1. + <_> + 6 14 1 1 2. + <_> + + <_> + 11 0 3 7 -1. + <_> + 12 0 1 7 3. + <_> + + <_> + 0 3 2 16 -1. + <_> + 0 3 1 8 2. + <_> + 1 11 1 8 2. + <_> + + <_> + 11 0 3 7 -1. + <_> + 12 0 1 7 3. + <_> + + <_> + 6 0 3 7 -1. + <_> + 7 0 1 7 3. + <_> + + <_> + 11 16 8 4 -1. + <_> + 11 16 4 4 2. + <_> + + <_> + 1 16 8 4 -1. + <_> + 5 16 4 4 2. + <_> + + <_> + 13 5 2 7 -1. + <_> + 13 5 1 7 2. + <_> + + <_> + 5 5 2 7 -1. + <_> + 6 5 1 7 2. + <_> + + <_> + 18 6 2 14 -1. + <_> + 18 13 2 7 2. + <_> + + <_> + 6 10 3 4 -1. + <_> + 6 12 3 2 2. + <_> + + <_> + 14 7 1 2 -1. + <_> + 14 8 1 1 2. + <_> + + <_> + 0 1 18 6 -1. + <_> + 0 1 9 3 2. + <_> + 9 4 9 3 2. + <_> + + <_> + 14 7 1 2 -1. + <_> + 14 8 1 1 2. + <_> + + <_> + 0 6 2 14 -1. + <_> + 0 13 2 7 2. + <_> + + <_> + 17 0 3 12 -1. + <_> + 18 0 1 12 3. + <_> + + <_> + 0 6 18 3 -1. + <_> + 0 7 18 1 3. + <_> + + <_> + 6 0 14 16 -1. + <_> + 6 8 14 8 2. + <_> + + <_> + 0 0 3 12 -1. + <_> + 1 0 1 12 3. + <_> + + <_> + 13 0 3 7 -1. + <_> + 14 0 1 7 3. + <_> + + <_> + 5 7 1 2 -1. + <_> + 5 8 1 1 2. + <_> + + <_> + 14 4 6 6 -1. + <_> + 14 6 6 2 3. + <_> + + <_> + 5 7 7 2 -1. + <_> + 5 8 7 1 2. + <_> + + <_> + 8 6 6 9 -1. + <_> + 8 9 6 3 3. + <_> + + <_> + 5 4 6 1 -1. + <_> + 7 4 2 1 3. + <_> + + <_> + 13 0 6 4 -1. + <_> + 16 0 3 2 2. + <_> + 13 2 3 2 2. + <_> + + <_> + 1 2 18 12 -1. + <_> + 1 6 18 4 3. + <_> + + <_> + 3 2 17 12 -1. + <_> + 3 6 17 4 3. + <_> + + <_> + 5 14 7 3 -1. + <_> + 5 15 7 1 3. + <_> + + <_> + 10 14 1 3 -1. + <_> + 10 15 1 1 3. + <_> + + <_> + 3 14 3 3 -1. + <_> + 3 15 3 1 3. + <_> + + <_> + 14 4 6 6 -1. + <_> + 14 6 6 2 3. + <_> + + <_> + 0 4 6 6 -1. + <_> + 0 6 6 2 3. + <_> + + <_> + 12 5 4 3 -1. + <_> + 12 6 4 1 3. + <_> + + <_> + 4 5 4 3 -1. + <_> + 4 6 4 1 3. + <_> + + <_> + 18 0 2 6 -1. + <_> + 18 2 2 2 3. + <_> + + <_> + 8 1 4 9 -1. + <_> + 10 1 2 9 2. + <_> + + <_> + 6 6 8 2 -1. + <_> + 6 6 4 2 2. + <_> + + <_> + 6 5 4 2 -1. + <_> + 6 5 2 1 2. + <_> + 8 6 2 1 2. + <_> + + <_> + 10 5 2 3 -1. + <_> + 10 6 2 1 3. + <_> + + <_> + 9 5 1 3 -1. + <_> + 9 6 1 1 3. + <_> + + <_> + 9 10 2 2 -1. + <_> + 9 11 2 1 2. + <_> + + <_> + 0 8 4 3 -1. + <_> + 0 9 4 1 3. + <_> + + <_> + 6 0 8 6 -1. + <_> + 6 3 8 3 2. + <_> + + <_> + 1 0 6 4 -1. + <_> + 1 0 3 2 2. + <_> + 4 2 3 2 2. + <_> + + <_> + 13 0 3 7 -1. + <_> + 14 0 1 7 3. + <_> + + <_> + 9 16 2 2 -1. + <_> + 9 17 2 1 2. + <_> + + <_> + 11 4 6 10 -1. + <_> + 11 9 6 5 2. + <_> + + <_> + 0 10 19 2 -1. + <_> + 0 11 19 1 2. + <_> + + <_> + 9 5 8 9 -1. + <_> + 9 8 8 3 3. + <_> + + <_> + 4 0 3 7 -1. + <_> + 5 0 1 7 3. + <_> + + <_> + 8 6 4 12 -1. + <_> + 10 6 2 6 2. + <_> + 8 12 2 6 2. + <_> + + <_> + 0 2 6 4 -1. + <_> + 0 4 6 2 2. + <_> + + <_> + 8 15 4 3 -1. + <_> + 8 16 4 1 3. + <_> + + <_> + 8 0 3 7 -1. + <_> + 9 0 1 7 3. + <_> + + <_> + 9 5 3 4 -1. + <_> + 10 5 1 4 3. + <_> + + <_> + 8 5 3 4 -1. + <_> + 9 5 1 4 3. + <_> + + <_> + 7 6 6 1 -1. + <_> + 9 6 2 1 3. + <_> + + <_> + 7 14 4 4 -1. + <_> + 7 14 2 2 2. + <_> + 9 16 2 2 2. + <_> + + <_> + 13 14 4 6 -1. + <_> + 15 14 2 3 2. + <_> + 13 17 2 3 2. + <_> + + <_> + 7 8 1 8 -1. + <_> + 7 12 1 4 2. + <_> + + <_> + 16 0 2 8 -1. + <_> + 17 0 1 4 2. + <_> + 16 4 1 4 2. + <_> + + <_> + 2 0 2 8 -1. + <_> + 2 0 1 4 2. + <_> + 3 4 1 4 2. + <_> + + <_> + 6 1 14 3 -1. + <_> + 6 2 14 1 3. + <_> + + <_> + 7 9 3 10 -1. + <_> + 7 14 3 5 2. + <_> + + <_> + 9 14 2 2 -1. + <_> + 9 15 2 1 2. + <_> + + <_> + 7 7 6 8 -1. + <_> + 7 11 6 4 2. + <_> + + <_> + 9 7 3 6 -1. + <_> + 9 10 3 3 2. + <_> + + <_> + 7 13 3 3 -1. + <_> + 7 14 3 1 3. + <_> + + <_> + 9 9 2 2 -1. + <_> + 9 10 2 1 2. + <_> + + <_> + 0 1 18 2 -1. + <_> + 6 1 6 2 3. + <_> + + <_> + 7 1 6 14 -1. + <_> + 7 8 6 7 2. + <_> + + <_> + 1 9 18 1 -1. + <_> + 7 9 6 1 3. + <_> + + <_> + 9 7 2 2 -1. + <_> + 9 7 1 2 2. + <_> + + <_> + 9 3 2 9 -1. + <_> + 10 3 1 9 2. + <_> + + <_> + 18 14 2 3 -1. + <_> + 18 15 2 1 3. + <_> + + <_> + 7 11 3 1 -1. + <_> + 8 11 1 1 3. + <_> + + <_> + 10 8 3 4 -1. + <_> + 11 8 1 4 3. + <_> + + <_> + 7 14 3 6 -1. + <_> + 8 14 1 6 3. + <_> + + <_> + 10 8 3 4 -1. + <_> + 11 8 1 4 3. + <_> + + <_> + 7 8 3 4 -1. + <_> + 8 8 1 4 3. + <_> + + <_> + 7 9 6 9 -1. + <_> + 7 12 6 3 3. + <_> + + <_> + 0 14 2 3 -1. + <_> + 0 15 2 1 3. + <_> + + <_> + 11 12 1 2 -1. + <_> + 11 13 1 1 2. + <_> + + <_> + 4 3 8 3 -1. + <_> + 8 3 4 3 2. + <_> + + <_> + 0 4 20 6 -1. + <_> + 0 4 10 6 2. + <_> + + <_> + 9 14 1 3 -1. + <_> + 9 15 1 1 3. + <_> + + <_> + 8 14 4 3 -1. + <_> + 8 15 4 1 3. + <_> + + <_> + 0 15 14 4 -1. + <_> + 0 17 14 2 2. + <_> + + <_> + 1 14 18 6 -1. + <_> + 1 17 18 3 2. + <_> + + <_> + 0 0 10 6 -1. + <_> + 0 0 5 3 2. + <_> + 5 3 5 3 2. + \ No newline at end of file diff --git a/image-processing/src/main/resources/images/baeldung.png b/image-processing/src/main/resources/images/baeldung.png new file mode 100644 index 0000000000..86155fa3ec Binary files /dev/null and b/image-processing/src/main/resources/images/baeldung.png differ diff --git a/image-processing/src/main/resources/images/multiLanguageText.png b/image-processing/src/main/resources/images/multiLanguageText.png new file mode 100644 index 0000000000..af15783eb8 Binary files /dev/null and b/image-processing/src/main/resources/images/multiLanguageText.png differ diff --git a/image-processing/src/main/resources/images/output.txt b/image-processing/src/main/resources/images/output.txt new file mode 100644 index 0000000000..8f5ad715a0 --- /dev/null +++ b/image-processing/src/main/resources/images/output.txt @@ -0,0 +1,9 @@ +Der ,.schnelle” braune Fuchs springt +iiber den faulen Hund. Le renard brun +«rapide» saute par-dessus le chien +paresseux. La volpe marrone rapida +salta sopra il cane pigro. El zorro +marron rapido salta sobre el perro +perezoso. A raposa marrom rapida +salta sobre 0 cao preguicoso. + \ No newline at end of file diff --git a/intelliJ/remote-debugging/.idea/runConfigurations/Remote_Debugger.xml b/intelliJ/remote-debugging/.idea/runConfigurations/Remote_Debugger.xml deleted file mode 100644 index ca11791a08..0000000000 --- a/intelliJ/remote-debugging/.idea/runConfigurations/Remote_Debugger.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - \ No newline at end of file diff --git a/intelliJ/remote-debugging/CONTRIBUTING.adoc b/intelliJ/remote-debugging/CONTRIBUTING.adoc deleted file mode 100644 index a97e428a48..0000000000 --- a/intelliJ/remote-debugging/CONTRIBUTING.adoc +++ /dev/null @@ -1,2 +0,0 @@ -If you have not previously done so, please fill out and -submit the https://cla.pivotal.io/sign/spring[Contributor License Agreement]. \ No newline at end of file diff --git a/intelliJ/remote-debugging/LICENSE.code.txt b/intelliJ/remote-debugging/LICENSE.code.txt deleted file mode 100644 index 4b5cde9fd2..0000000000 --- a/intelliJ/remote-debugging/LICENSE.code.txt +++ /dev/null @@ -1,16 +0,0 @@ - All code in this repository is: - ======================================================================= - Copyright (c) 2013 GoPivotal, Inc. All Rights Reserved - - 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 - - https://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. - diff --git a/intelliJ/remote-debugging/LICENSE.writing.txt b/intelliJ/remote-debugging/LICENSE.writing.txt deleted file mode 100644 index 9d21229f84..0000000000 --- a/intelliJ/remote-debugging/LICENSE.writing.txt +++ /dev/null @@ -1 +0,0 @@ -Except where otherwise noted, this work is licensed under https://creativecommons.org/licenses/by-nd/3.0/ diff --git a/intelliJ/remote-debugging/README.adoc b/intelliJ/remote-debugging/README.adoc deleted file mode 100644 index 6a4b80959f..0000000000 --- a/intelliJ/remote-debugging/README.adoc +++ /dev/null @@ -1,84 +0,0 @@ -:toc: -:spring_version: current -:icons: font -:source-highlighter: prettify -:project_id: gs-scheduling-tasks -This guide walks you through the steps for scheduling tasks with Spring. - -== What you'll build - -You'll build an application that prints out the current time every five seconds using Spring's `@Scheduled` annotation. - -== What you'll need - -:java_version: 1.8 -include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/prereq_editor_jdk_buildtools.adoc[] - - -include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/how_to_complete_this_guide.adoc[] - - -include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-gradle.adoc[] - -include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-maven.adoc[] - -include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-sts.adoc[] - - - -[[initial]] -== Create a scheduled task -Now that you've set up your project, you can create a scheduled task. - -`src/main/java/hello/ScheduledTasks.java` -[source,java] ----- -include::complete/src/main/java/hello/ScheduledTasks.java[] ----- - -The `Scheduled` annotation defines when a particular method runs. -NOTE: This example uses `fixedRate`, which specifies the interval between method invocations measured from the start time of each invocation. There are https://docs.spring.io/spring/docs/{spring_version}/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-scheduled[other options], like `fixedDelay`, which specifies the interval between invocations measured from the completion of the task. You can also https://docs.spring.io/spring/docs/{spring_version}/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html[use `@Scheduled(cron=". . .")` expressions for more sophisticated task scheduling]. - -== Enable Scheduling - -Although scheduled tasks can be embedded in web apps and WAR files, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java `main()` method. - -`src/main/java/hello/Application.java` -[source,java] ----- -include::complete/src/main/java/hello/Application.java[] ----- - -include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/spring-boot-application.adoc[] - -https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#scheduling-enable-annotation-support[`@EnableScheduling`] ensures that a background task executor is created. Without it, nothing gets scheduled. - - -include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/build_an_executable_jar_subhead.adoc[] - -include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/build_an_executable_jar_with_both.adoc[] - - - -Logging output is displayed and you can see from the logs that it is on a background thread. You should see your scheduled task fire every 5 seconds: - -.... -[...] -2016-08-25 13:10:00.143 INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:00 -2016-08-25 13:10:05.143 INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:05 -2016-08-25 13:10:10.143 INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:10 -2016-08-25 13:10:15.143 INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:15 -.... - -== Summary - -Congratulations! You created an application with a scheduled task. Heck, the actual code was shorter than the build file! This technique works in any type of application. - -== See Also - -The following guides may also be helpful: - -* https://spring.io/guides/gs/spring-boot/[Building an Application with Spring Boot] -* https://spring.io/guides/gs/batch-processing/[Creating a Batch Service] - -include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/footer.adoc[] diff --git a/intelliJ/remote-debugging/pom.xml b/intelliJ/remote-debugging/pom.xml deleted file mode 100644 index d18625e8f6..0000000000 --- a/intelliJ/remote-debugging/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - 4.0.0 - - com.baeldung - gs-scheduling-tasks - 0.1.0 - gs-scheduling-tasks - - - org.springframework.boot - spring-boot-starter-parent - 2.1.6.RELEASE - - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-test - test - - - org.awaitility - awaitility - 3.1.2 - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/intelliJ/remote-debugging/src/main/java/hello/Application.java b/intelliJ/remote-debugging/src/main/java/hello/Application.java deleted file mode 100644 index 73b55f933b..0000000000 --- a/intelliJ/remote-debugging/src/main/java/hello/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package hello; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.scheduling.annotation.EnableScheduling; - -@SpringBootApplication -@EnableScheduling -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class); - } -} diff --git a/intelliJ/remote-debugging/src/main/java/hello/ScheduledTasks.java b/intelliJ/remote-debugging/src/main/java/hello/ScheduledTasks.java deleted file mode 100644 index de1f6eebeb..0000000000 --- a/intelliJ/remote-debugging/src/main/java/hello/ScheduledTasks.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2012-2015 the original author or authors. - * - * 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 - * - * https://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 hello; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -@Component -public class ScheduledTasks { - - private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); - - private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); - - @Scheduled(fixedRate = 5000) - public void reportCurrentTime() { - log.info("The time is now {}", dateFormat.format(new Date())); - } -} diff --git a/jackson-annotations/pom.xml b/jackson-annotations/pom.xml deleted file mode 100644 index a259d895da..0000000000 --- a/jackson-annotations/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - 4.0.0 - jackson-annotations - 0.0.1-SNAPSHOT - jackson-annotations - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson.version} - - - com.fasterxml.jackson.module - jackson-module-jsonSchema - ${jackson.version} - - - io.rest-assured - json-path - ${rest-assured.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - jackson-annotations - - - src/main/resources - true - - - - - - 3.11.0 - 3.1.1 - - - diff --git a/jackson-conversions-2/pom.xml b/jackson-conversions-2/pom.xml deleted file mode 100644 index 732c89c1e5..0000000000 --- a/jackson-conversions-2/pom.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - 4.0.0 - jackson-conversions-2 - 0.0.1-SNAPSHOT - jackson-conversions-2 - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson.version} - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-yaml - ${jackson.version} - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - 2.9.8 - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-csv - ${jackson.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - jackson-conversions-2 - - - src/main/resources - true - - - - - - 3.11.0 - - - diff --git a/jackson-conversions/pom.xml b/jackson-conversions/pom.xml deleted file mode 100644 index c45d88bedd..0000000000 --- a/jackson-conversions/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - 4.0.0 - jackson-conversions - 0.0.1-SNAPSHOT - jackson-conversions - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson.version} - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson.version} - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson.version} - - - - - jackson-conversions - - - src/main/resources - true - - - - - diff --git a/jackson-custom-conversions/pom.xml b/jackson-custom-conversions/pom.xml deleted file mode 100644 index 68c785e972..0000000000 --- a/jackson-custom-conversions/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - 4.0.0 - jackson-custom-conversions - 0.0.1-SNAPSHOT - jackson-custom-conversions - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson.version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson.version} - - - - - jackson-custom-conversions - - - src/main/resources - true - - - - - diff --git a/jackson-exceptions/pom.xml b/jackson-exceptions/pom.xml deleted file mode 100644 index 3cf4796fa7..0000000000 --- a/jackson-exceptions/pom.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - 4.0.0 - jackson-exceptions - 0.0.1-SNAPSHOT - jackson-exceptions - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - - jackson-exceptions - - - src/main/resources - true - - - - - diff --git a/jackson-annotations/README.md b/jackson-modules/jackson-annotations/README.md similarity index 100% rename from jackson-annotations/README.md rename to jackson-modules/jackson-annotations/README.md diff --git a/jackson-modules/jackson-annotations/pom.xml b/jackson-modules/jackson-annotations/pom.xml new file mode 100644 index 0000000000..e4a41a5825 --- /dev/null +++ b/jackson-modules/jackson-annotations/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + jackson-annotations + 0.0.1-SNAPSHOT + jackson-annotations + + + com.baeldung + jackson-modules + 0.0.1-SNAPSHOT + + + + + com.fasterxml.jackson.module + jackson-module-jsonSchema + ${jackson.version} + + + io.rest-assured + json-path + ${rest-assured.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + jackson-annotations + + + src/main/resources + true + + + + + + 3.11.0 + 3.1.1 + + + diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/CustomListDeserializer.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/CustomListDeserializer.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/CustomListDeserializer.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/CustomListDeserializer.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/CustomListSerializer.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/CustomListSerializer.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/CustomListSerializer.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/CustomListSerializer.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/Item.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/Item.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/Item.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/Item.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithIdentity.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithIdentity.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithIdentity.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithIdentity.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithIgnore.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithIgnore.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithIgnore.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithIgnore.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithRef.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithRef.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithRef.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithRef.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithSerializer.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithSerializer.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithSerializer.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithSerializer.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithView.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithView.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithView.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/ItemWithView.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/User.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/User.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/User.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/User.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithIdentity.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithIdentity.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithIdentity.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithIdentity.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithIgnore.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithIgnore.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithIgnore.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithIgnore.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithRef.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithRef.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithRef.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithRef.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithSerializer.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithSerializer.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithSerializer.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithSerializer.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithView.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithView.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithView.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/UserWithView.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/jsonview/Views.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/jsonview/Views.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/jsonview/Views.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/bidirection/jsonview/Views.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/domain/Person.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/domain/Person.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/domain/Person.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/domain/Person.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/Item.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/Item.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/Item.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/Item.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/MyBeanSerializerModifier.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/MyBeanSerializerModifier.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/MyBeanSerializerModifier.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/MyBeanSerializerModifier.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/UpperCasingWriter.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/UpperCasingWriter.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/UpperCasingWriter.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/UpperCasingWriter.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/User.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/User.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/User.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/User.java diff --git a/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/Views.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/Views.java similarity index 100% rename from jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/Views.java rename to jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonview/Views.java diff --git a/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/AdvancedAnnotationsUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/AdvancedAnnotationsUnitTest.java similarity index 100% rename from jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/AdvancedAnnotationsUnitTest.java rename to jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/AdvancedAnnotationsUnitTest.java diff --git a/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/AppendBeans.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/AppendBeans.java similarity index 100% rename from jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/AppendBeans.java rename to jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/AppendBeans.java diff --git a/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/IdentityReferenceBeans.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/IdentityReferenceBeans.java similarity index 100% rename from jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/IdentityReferenceBeans.java rename to jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/IdentityReferenceBeans.java diff --git a/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/NamingBean.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/NamingBean.java similarity index 100% rename from jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/NamingBean.java rename to jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/NamingBean.java diff --git a/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/POJOBuilderBean.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/POJOBuilderBean.java similarity index 100% rename from jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/POJOBuilderBean.java rename to jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/POJOBuilderBean.java diff --git a/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/PropertyDescriptionBean.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/PropertyDescriptionBean.java similarity index 100% rename from jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/PropertyDescriptionBean.java rename to jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/PropertyDescriptionBean.java diff --git a/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/TypeIdBean.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/TypeIdBean.java similarity index 100% rename from jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/TypeIdBean.java rename to jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/TypeIdBean.java diff --git a/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/TypeIdResolverStructure.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/TypeIdResolverStructure.java similarity index 100% rename from jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/TypeIdResolverStructure.java rename to jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/advancedannotations/TypeIdResolverStructure.java diff --git a/jackson-annotations/src/test/java/com/baeldung/jackson/bidirection/JacksonBidirectionRelationUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/bidirection/JacksonBidirectionRelationUnitTest.java similarity index 100% rename from jackson-annotations/src/test/java/com/baeldung/jackson/bidirection/JacksonBidirectionRelationUnitTest.java rename to jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/bidirection/JacksonBidirectionRelationUnitTest.java diff --git a/jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java similarity index 100% rename from jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java rename to jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java diff --git a/jackson-annotations/src/test/java/com/baeldung/jackson/jsonview/JacksonJsonViewUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/jsonview/JacksonJsonViewUnitTest.java similarity index 100% rename from jackson-annotations/src/test/java/com/baeldung/jackson/jsonview/JacksonJsonViewUnitTest.java rename to jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/jsonview/JacksonJsonViewUnitTest.java diff --git a/jackson-conversions-2/README.md b/jackson-modules/jackson-conversions-2/README.md similarity index 100% rename from jackson-conversions-2/README.md rename to jackson-modules/jackson-conversions-2/README.md diff --git a/jackson-modules/jackson-conversions-2/pom.xml b/jackson-modules/jackson-conversions-2/pom.xml new file mode 100644 index 0000000000..43c9d1478b --- /dev/null +++ b/jackson-modules/jackson-conversions-2/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + jackson-conversions-2 + 0.0.1-SNAPSHOT + jackson-conversions-2 + + + com.baeldung + jackson-modules + 0.0.1-SNAPSHOT + + + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + ${jackson.version} + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + 2.9.8 + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-csv + ${jackson.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + jackson-conversions-2 + + + src/main/resources + true + + + + + + 3.11.0 + + + diff --git a/jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/JsonCsvConverter.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/JsonCsvConverter.java similarity index 100% rename from jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/JsonCsvConverter.java rename to jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/JsonCsvConverter.java diff --git a/jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/OrderLine.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/OrderLine.java similarity index 100% rename from jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/OrderLine.java rename to jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/OrderLine.java diff --git a/jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/OrderLineForCsv.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/OrderLineForCsv.java similarity index 100% rename from jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/OrderLineForCsv.java rename to jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/csv/OrderLineForCsv.java diff --git a/jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/Product.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/Product.java similarity index 100% rename from jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/Product.java rename to jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/Product.java diff --git a/jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/ProductJsonNode.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/ProductJsonNode.java similarity index 100% rename from jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/ProductJsonNode.java rename to jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/ProductJsonNode.java diff --git a/jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/ProductMap.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/ProductMap.java similarity index 100% rename from jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/ProductMap.java rename to jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/dynamicobject/ProductMap.java diff --git a/jackson-conversions-2/src/main/java/com/baeldung/jackson/multiplefields/Weather.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/multiplefields/Weather.java similarity index 100% rename from jackson-conversions-2/src/main/java/com/baeldung/jackson/multiplefields/Weather.java rename to jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/multiplefields/Weather.java diff --git a/jackson-conversions-2/src/main/java/com/baeldung/jackson/xmlToJson/Color.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/xmlToJson/Color.java similarity index 100% rename from jackson-conversions-2/src/main/java/com/baeldung/jackson/xmlToJson/Color.java rename to jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/xmlToJson/Color.java diff --git a/jackson-conversions-2/src/main/java/com/baeldung/jackson/xmlToJson/Flower.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/xmlToJson/Flower.java similarity index 100% rename from jackson-conversions-2/src/main/java/com/baeldung/jackson/xmlToJson/Flower.java rename to jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/xmlToJson/Flower.java diff --git a/jackson-conversions-2/src/main/java/com/baeldung/jackson/yaml/Order.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/yaml/Order.java similarity index 100% rename from jackson-conversions-2/src/main/java/com/baeldung/jackson/yaml/Order.java rename to jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/yaml/Order.java diff --git a/jackson-conversions-2/src/main/java/com/baeldung/jackson/yaml/OrderLine.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/yaml/OrderLine.java similarity index 100% rename from jackson-conversions-2/src/main/java/com/baeldung/jackson/yaml/OrderLine.java rename to jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/yaml/OrderLine.java diff --git a/jackson-conversions-2/src/main/resources/csv/orderLines.csv b/jackson-modules/jackson-conversions-2/src/main/resources/csv/orderLines.csv similarity index 100% rename from jackson-conversions-2/src/main/resources/csv/orderLines.csv rename to jackson-modules/jackson-conversions-2/src/main/resources/csv/orderLines.csv diff --git a/jackson-conversions-2/src/main/resources/csv/orderLines.json b/jackson-modules/jackson-conversions-2/src/main/resources/csv/orderLines.json similarity index 100% rename from jackson-conversions-2/src/main/resources/csv/orderLines.json rename to jackson-modules/jackson-conversions-2/src/main/resources/csv/orderLines.json diff --git a/jackson-conversions-2/src/test/java/com/baeldung/jackson/csv/CsvUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/csv/CsvUnitTest.java similarity index 100% rename from jackson-conversions-2/src/test/java/com/baeldung/jackson/csv/CsvUnitTest.java rename to jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/csv/CsvUnitTest.java diff --git a/jackson-conversions-2/src/test/java/com/baeldung/jackson/dynamicobject/DynamicObjectDeserializationUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/dynamicobject/DynamicObjectDeserializationUnitTest.java similarity index 100% rename from jackson-conversions-2/src/test/java/com/baeldung/jackson/dynamicobject/DynamicObjectDeserializationUnitTest.java rename to jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/dynamicobject/DynamicObjectDeserializationUnitTest.java diff --git a/jackson-conversions-2/src/test/java/com/baeldung/jackson/multiplefields/MapMultipleFieldsToSingleFieldUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/multiplefields/MapMultipleFieldsToSingleFieldUnitTest.java similarity index 100% rename from jackson-conversions-2/src/test/java/com/baeldung/jackson/multiplefields/MapMultipleFieldsToSingleFieldUnitTest.java rename to jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/multiplefields/MapMultipleFieldsToSingleFieldUnitTest.java diff --git a/jackson-conversions-2/src/test/java/com/baeldung/jackson/streaming/StreamingAPIUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/streaming/StreamingAPIUnitTest.java similarity index 100% rename from jackson-conversions-2/src/test/java/com/baeldung/jackson/streaming/StreamingAPIUnitTest.java rename to jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/streaming/StreamingAPIUnitTest.java diff --git a/jackson-conversions-2/src/test/java/com/baeldung/jackson/xmlToJson/XmlToJsonUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/xmlToJson/XmlToJsonUnitTest.java similarity index 100% rename from jackson-conversions-2/src/test/java/com/baeldung/jackson/xmlToJson/XmlToJsonUnitTest.java rename to jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/xmlToJson/XmlToJsonUnitTest.java diff --git a/jackson-conversions-2/src/test/java/com/baeldung/jackson/yaml/YamlUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/yaml/YamlUnitTest.java similarity index 100% rename from jackson-conversions-2/src/test/java/com/baeldung/jackson/yaml/YamlUnitTest.java rename to jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/yaml/YamlUnitTest.java diff --git a/jackson-conversions-2/src/test/resources/csv/expectedCsvFromJson.csv b/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedCsvFromJson.csv similarity index 100% rename from jackson-conversions-2/src/test/resources/csv/expectedCsvFromJson.csv rename to jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedCsvFromJson.csv diff --git a/jackson-conversions-2/src/test/resources/csv/expectedFormattedCsvFromJson.csv b/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedFormattedCsvFromJson.csv similarity index 100% rename from jackson-conversions-2/src/test/resources/csv/expectedFormattedCsvFromJson.csv rename to jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedFormattedCsvFromJson.csv diff --git a/jackson-conversions-2/src/test/resources/csv/expectedJsonFromCsv.json b/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedJsonFromCsv.json similarity index 100% rename from jackson-conversions-2/src/test/resources/csv/expectedJsonFromCsv.json rename to jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedJsonFromCsv.json diff --git a/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/embedded.json b/jackson-modules/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/embedded.json similarity index 100% rename from jackson-conversions-2/src/test/resources/deserialize-dynamic-object/embedded.json rename to jackson-modules/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/embedded.json diff --git a/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/flat.json b/jackson-modules/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/flat.json similarity index 100% rename from jackson-conversions-2/src/test/resources/deserialize-dynamic-object/flat.json rename to jackson-modules/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/flat.json diff --git a/jackson-conversions-2/src/test/resources/yaml/orderInput.yaml b/jackson-modules/jackson-conversions-2/src/test/resources/yaml/orderInput.yaml similarity index 100% rename from jackson-conversions-2/src/test/resources/yaml/orderInput.yaml rename to jackson-modules/jackson-conversions-2/src/test/resources/yaml/orderInput.yaml diff --git a/jackson-conversions/README.md b/jackson-modules/jackson-conversions/README.md similarity index 100% rename from jackson-conversions/README.md rename to jackson-modules/jackson-conversions/README.md diff --git a/jackson-modules/jackson-conversions/pom.xml b/jackson-modules/jackson-conversions/pom.xml new file mode 100644 index 0000000000..fafb731cc9 --- /dev/null +++ b/jackson-modules/jackson-conversions/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + jackson-conversions + 0.0.1-SNAPSHOT + jackson-conversions + + + com.baeldung + jackson-modules + 0.0.1-SNAPSHOT + + + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson.version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson.version} + + + + + jackson-conversions + + + src/main/resources + true + + + + + diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateDeserializer.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateDeserializer.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateDeserializer.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateDeserializer.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateSerializer.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateSerializer.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateSerializer.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateTimeSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateTimeSerializer.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateTimeSerializer.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomDateTimeSerializer.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/date/Event.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/Event.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/date/Event.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/Event.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithFormat.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithFormat.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithFormat.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithFormat.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithJodaTime.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithJodaTime.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithJodaTime.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithJodaTime.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithLocalDateTime.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithLocalDateTime.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithLocalDateTime.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithLocalDateTime.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithSerializer.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithSerializer.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/date/EventWithSerializer.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/City.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/City.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/City.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/City.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/Distance.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/Distance.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/Distance.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/City.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/City.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/City.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/City.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/CustomEnumDeserializer.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/CustomEnumDeserializer.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/CustomEnumDeserializer.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/CustomEnumDeserializer.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/Distance.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/Distance.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/customdeserializer/Distance.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsoncreator/City.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsoncreator/City.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsoncreator/City.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsoncreator/City.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsoncreator/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsoncreator/Distance.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsoncreator/Distance.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsoncreator/Distance.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonproperty/City.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonproperty/City.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonproperty/City.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonproperty/City.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonproperty/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonproperty/Distance.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonproperty/Distance.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonproperty/Distance.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonvalue/City.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonvalue/City.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonvalue/City.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonvalue/City.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonvalue/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonvalue/Distance.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonvalue/Distance.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/deserialization/jsonvalue/Distance.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/serialization/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/serialization/Distance.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/serialization/Distance.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/serialization/Distance.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/serialization/DistanceSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/serialization/DistanceSerializer.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/serialization/DistanceSerializer.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/serialization/DistanceSerializer.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumSimple.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumSimple.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumSimple.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumSimple.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumWithJsonFormat.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumWithJsonFormat.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumWithJsonFormat.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumWithJsonFormat.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumWithValue.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumWithValue.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumWithValue.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/DistanceEnumWithValue.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/MyDtoWithEnumCustom.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/MyDtoWithEnumCustom.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/MyDtoWithEnumCustom.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/MyDtoWithEnumCustom.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/MyDtoWithEnumJsonFormat.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/MyDtoWithEnumJsonFormat.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/MyDtoWithEnumJsonFormat.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/enums/withEnum/MyDtoWithEnumJsonFormat.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDto.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDto.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDto.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDto.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoAccessLevel.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoAccessLevel.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoAccessLevel.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoAccessLevel.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoWithGetter.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoWithGetter.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoWithGetter.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoWithGetter.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoWithSetter.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoWithSetter.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoWithSetter.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/field/MyDtoWithSetter.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/immutable/Employee.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/immutable/Employee.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/immutable/Employee.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/immutable/Employee.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/immutable/Person.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/immutable/Person.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/immutable/Person.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/immutable/Person.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/map/ClassWithAMap.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/ClassWithAMap.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/map/ClassWithAMap.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/ClassWithAMap.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPair.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPair.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPair.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPair.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPairDeserializer.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPairDeserializer.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPairDeserializer.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPairDeserializer.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPairSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPairSerializer.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPairSerializer.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/MyPairSerializer.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/mapnull/MyDto.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/mapnull/MyDto.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/mapnull/MyDto.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/mapnull/MyDto.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/mapnull/MyDtoNullKeySerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/mapnull/MyDtoNullKeySerializer.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/mapnull/MyDtoNullKeySerializer.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/mapnull/MyDtoNullKeySerializer.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/tocollection/MyDto.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/tocollection/MyDto.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/tocollection/MyDto.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/tocollection/MyDto.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/xml/Address.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/xml/Address.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/xml/Address.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/xml/Address.java diff --git a/jackson-conversions/src/main/java/com/baeldung/jackson/xml/Person.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/xml/Person.java similarity index 100% rename from jackson-conversions/src/main/java/com/baeldung/jackson/xml/Person.java rename to jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/xml/Person.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java similarity index 88% rename from jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java index a264dd52f2..924ec1162f 100644 --- a/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java +++ b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.jackson.date; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @@ -8,6 +9,8 @@ import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; import java.util.Date; import java.util.TimeZone; @@ -30,7 +33,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; public class JacksonDateUnitTest { @Test - public void whenSerializingDateWithJackson_thenSerializedToNumber() throws JsonProcessingException, ParseException { + public void whenSerializingDateWithJackson_thenSerializedToTimestamp() throws JsonProcessingException, ParseException { final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); df.setTimeZone(TimeZone.getTimeZone("UTC")); @@ -61,6 +64,21 @@ public class JacksonDateUnitTest { final String result = mapper.writeValueAsString(event); assertThat(result, containsString("1970-01-01T02:30:00.000+00:00")); } + + @Test + public void whenDeserialisingZonedDateTimeWithDefaults_thenNotCorrect() + throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC")); + String converted = objectMapper.writeValueAsString(now); + + ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); + System.out.println("serialized: " + now); + System.out.println("restored: " + restored); + assertThat(now, is(restored)); + } @Test public void whenSettingObjectMapperDateFormat_thenCorrect() throws JsonProcessingException, ParseException { diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/DefaultEnumDeserializationUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/DefaultEnumDeserializationUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/DefaultEnumDeserializationUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/DefaultEnumDeserializationUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/customdeserializer/EnumCustomDeserializationUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/customdeserializer/EnumCustomDeserializationUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/customdeserializer/EnumCustomDeserializationUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/customdeserializer/EnumCustomDeserializationUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/deserialization/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/enums/serialization/JacksonEnumSerializationUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/serialization/JacksonEnumSerializationUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/enums/serialization/JacksonEnumSerializationUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/serialization/JacksonEnumSerializationUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/enums/serialization/JacksonSerializationEnumsUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/serialization/JacksonSerializationEnumsUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/enums/serialization/JacksonSerializationEnumsUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/enums/serialization/JacksonSerializationEnumsUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/field/JacksonFieldUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/field/JacksonFieldUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/field/JacksonFieldUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/field/JacksonFieldUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/immutable/ImmutableObjectDeserializationUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/immutable/ImmutableObjectDeserializationUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/immutable/ImmutableObjectDeserializationUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/immutable/ImmutableObjectDeserializationUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/map/JacksonMapDeserializeUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/map/JacksonMapDeserializeUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/map/JacksonMapDeserializeUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/map/JacksonMapDeserializeUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/map/JacksonMapSerializeUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/map/JacksonMapSerializeUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/map/JacksonMapSerializeUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/map/JacksonMapSerializeUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/mapnull/JacksonMapNullUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/mapnull/JacksonMapNullUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/mapnull/JacksonMapNullUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/mapnull/JacksonMapNullUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/nested/DeserializeWithNestedPropertiesUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/nested/DeserializeWithNestedPropertiesUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/nested/DeserializeWithNestedPropertiesUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/nested/DeserializeWithNestedPropertiesUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/nested/Product.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/nested/Product.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/nested/Product.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/nested/Product.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/nested/ProductDeserializer.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/nested/ProductDeserializer.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/nested/ProductDeserializer.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/nested/ProductDeserializer.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/tocollection/JacksonCollectionDeserializationUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/tocollection/JacksonCollectionDeserializationUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/tocollection/JacksonCollectionDeserializationUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/tocollection/JacksonCollectionDeserializationUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/tojsonnode/StringToJsonNodeUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/tojsonnode/StringToJsonNodeUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/tojsonnode/StringToJsonNodeUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/tojsonnode/StringToJsonNodeUnitTest.java diff --git a/jackson-conversions/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java similarity index 100% rename from jackson-conversions/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java rename to jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java diff --git a/jackson-conversions/src/test/resources/simple_bean.xml b/jackson-modules/jackson-conversions/src/test/resources/simple_bean.xml similarity index 100% rename from jackson-conversions/src/test/resources/simple_bean.xml rename to jackson-modules/jackson-conversions/src/test/resources/simple_bean.xml diff --git a/jackson-custom-conversions/README.md b/jackson-modules/jackson-custom-conversions/README.md similarity index 100% rename from jackson-custom-conversions/README.md rename to jackson-modules/jackson-custom-conversions/README.md diff --git a/jackson-modules/jackson-custom-conversions/pom.xml b/jackson-modules/jackson-custom-conversions/pom.xml new file mode 100644 index 0000000000..c319891da9 --- /dev/null +++ b/jackson-modules/jackson-custom-conversions/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + jackson-custom-conversions + 0.0.1-SNAPSHOT + jackson-custom-conversions + + + com.baeldung + jackson-modules + 0.0.1-SNAPSHOT + + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson.version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson.version} + + + + + jackson-custom-conversions + + + src/main/resources + true + + + + + diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/File.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/File.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/File.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/File.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/Folder.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/Folder.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/Folder.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/Folder.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderBeanSerializerModifier.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderBeanSerializerModifier.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderBeanSerializerModifier.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderBeanSerializerModifier.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializer.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializer.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializer.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithCallingOwnSerializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithCallingOwnSerializer.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithCallingOwnSerializer.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithCallingOwnSerializer.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithDefaultSerializerStored.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithDefaultSerializerStored.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithDefaultSerializerStored.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithDefaultSerializerStored.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithInternalObjectMapper.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithInternalObjectMapper.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithInternalObjectMapper.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithInternalObjectMapper.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithSerializerProvider.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithSerializerProvider.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithSerializerProvider.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithSerializerProvider.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ActorJackson.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ActorJackson.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ActorJackson.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ActorJackson.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Item.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Item.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Item.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Item.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializer.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializer.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializer.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializerOnClass.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializerOnClass.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializerOnClass.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializerOnClass.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemWithDeserializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemWithDeserializer.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemWithDeserializer.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemWithDeserializer.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Movie.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Movie.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Movie.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Movie.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/User.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/User.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/deserialization/User.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/User.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/serialization/Item.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/Item.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/serialization/Item.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/Item.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializer.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializer.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializer.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializerOnClass.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializerOnClass.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializerOnClass.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializerOnClass.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemWithSerializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemWithSerializer.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemWithSerializer.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemWithSerializer.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/serialization/User.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/User.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/serialization/User.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/User.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Address.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Address.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Address.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Address.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Hidable.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Hidable.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Hidable.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Hidable.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/HidableSerializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/HidableSerializer.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/skipfields/HidableSerializer.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/HidableSerializer.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/MyDtoWithFilter.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/MyDtoWithFilter.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/skipfields/MyDtoWithFilter.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/MyDtoWithFilter.java diff --git a/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Person.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Person.java similarity index 100% rename from jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Person.java rename to jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Person.java diff --git a/jackson-custom-conversions/src/test/java/com/baeldung/defaultserializercustomserializer/CallingDefaultSerializerUnitTest.java b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/defaultserializercustomserializer/CallingDefaultSerializerUnitTest.java similarity index 100% rename from jackson-custom-conversions/src/test/java/com/baeldung/defaultserializercustomserializer/CallingDefaultSerializerUnitTest.java rename to jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/defaultserializercustomserializer/CallingDefaultSerializerUnitTest.java diff --git a/jackson-custom-conversions/src/test/java/com/baeldung/deserialization/CustomDeserializationUnitTest.java b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/deserialization/CustomDeserializationUnitTest.java similarity index 100% rename from jackson-custom-conversions/src/test/java/com/baeldung/deserialization/CustomDeserializationUnitTest.java rename to jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/deserialization/CustomDeserializationUnitTest.java diff --git a/jackson-custom-conversions/src/test/java/com/baeldung/serialization/CustomSerializationUnitTest.java b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/serialization/CustomSerializationUnitTest.java similarity index 100% rename from jackson-custom-conversions/src/test/java/com/baeldung/serialization/CustomSerializationUnitTest.java rename to jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/serialization/CustomSerializationUnitTest.java diff --git a/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/IgnoreFieldsWithFilterUnitTest.java b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/IgnoreFieldsWithFilterUnitTest.java similarity index 100% rename from jackson-custom-conversions/src/test/java/com/baeldung/skipfields/IgnoreFieldsWithFilterUnitTest.java rename to jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/IgnoreFieldsWithFilterUnitTest.java diff --git a/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/JacksonDynamicIgnoreUnitTest.java b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/JacksonDynamicIgnoreUnitTest.java similarity index 100% rename from jackson-custom-conversions/src/test/java/com/baeldung/skipfields/JacksonDynamicIgnoreUnitTest.java rename to jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/JacksonDynamicIgnoreUnitTest.java diff --git a/jackson-exceptions/README.md b/jackson-modules/jackson-exceptions/README.md similarity index 100% rename from jackson-exceptions/README.md rename to jackson-modules/jackson-exceptions/README.md diff --git a/jackson-modules/jackson-exceptions/pom.xml b/jackson-modules/jackson-exceptions/pom.xml new file mode 100644 index 0000000000..1a52892523 --- /dev/null +++ b/jackson-modules/jackson-exceptions/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + jackson-exceptions + 0.0.1-SNAPSHOT + jackson-exceptions + + + com.baeldung + jackson-modules + 0.0.1-SNAPSHOT + + + + jackson-exceptions + + + src/main/resources + true + + + + + diff --git a/jackson-exceptions/src/main/java/com/baeldung/exceptions/User.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/User.java similarity index 100% rename from jackson-exceptions/src/main/java/com/baeldung/exceptions/User.java rename to jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/User.java diff --git a/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithConflict.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithConflict.java similarity index 100% rename from jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithConflict.java rename to jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithConflict.java diff --git a/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithNoDefaultConstructor.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithNoDefaultConstructor.java similarity index 100% rename from jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithNoDefaultConstructor.java rename to jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithNoDefaultConstructor.java diff --git a/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithPrivateFields.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithPrivateFields.java similarity index 100% rename from jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithPrivateFields.java rename to jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithPrivateFields.java diff --git a/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithRoot.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithRoot.java similarity index 100% rename from jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithRoot.java rename to jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithRoot.java diff --git a/jackson-exceptions/src/main/java/com/baeldung/exceptions/Zoo.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Zoo.java similarity index 100% rename from jackson-exceptions/src/main/java/com/baeldung/exceptions/Zoo.java rename to jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Zoo.java diff --git a/jackson-exceptions/src/main/java/com/baeldung/exceptions/ZooConfigured.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/ZooConfigured.java similarity index 100% rename from jackson-exceptions/src/main/java/com/baeldung/exceptions/ZooConfigured.java rename to jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/ZooConfigured.java diff --git a/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessors.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessors.java similarity index 100% rename from jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessors.java rename to jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessors.java diff --git a/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessorsAndFieldVisibility.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessorsAndFieldVisibility.java similarity index 100% rename from jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessorsAndFieldVisibility.java rename to jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessorsAndFieldVisibility.java diff --git a/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java similarity index 100% rename from jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java rename to jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java diff --git a/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java similarity index 100% rename from jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java rename to jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java diff --git a/jackson/README.md b/jackson-modules/jackson/README.md similarity index 100% rename from jackson/README.md rename to jackson-modules/jackson/README.md diff --git a/jackson-modules/jackson/pom.xml b/jackson-modules/jackson/pom.xml new file mode 100644 index 0000000000..615076fc93 --- /dev/null +++ b/jackson-modules/jackson/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + jackson + 0.0.1-SNAPSHOT + jackson + + + com.baeldung + jackson-modules + 0.0.1-SNAPSHOT + + + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson.version} + + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson.version} + + + + com.fasterxml.jackson.module + jackson-module-jsonSchema + ${jackson.version} + + + + com.fasterxml.jackson.datatype + jackson-datatype-jdk8 + ${jackson.version} + + + + + + io.rest-assured + json-schema-validator + ${rest-assured.version} + test + + + + io.rest-assured + json-path + ${rest-assured.version} + test + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + jackson + + + src/main/resources + true + + + + + + + 3.1.1 + 3.11.0 + + + diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Person.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/domain/Person.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/domain/Person.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/domain/Person.java diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/Event.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/Event.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/inheritance/Event.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/Event.java diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/IgnoranceAnnotationStructure.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/IgnoranceAnnotationStructure.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/inheritance/IgnoranceAnnotationStructure.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/IgnoranceAnnotationStructure.java diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/IgnoranceMixinOrIntrospection.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/IgnoranceMixinOrIntrospection.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/inheritance/IgnoranceMixinOrIntrospection.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/IgnoranceMixinOrIntrospection.java diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/SubTypeConstructorStructure.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/SubTypeConstructorStructure.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/inheritance/SubTypeConstructorStructure.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/SubTypeConstructorStructure.java diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/SubTypeConversionStructure.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/SubTypeConversionStructure.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/inheritance/SubTypeConversionStructure.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/SubTypeConversionStructure.java diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/TypeInfoAnnotatedStructure.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/TypeInfoAnnotatedStructure.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/inheritance/TypeInfoAnnotatedStructure.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/TypeInfoAnnotatedStructure.java diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/TypeInfoStructure.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/TypeInfoStructure.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/inheritance/TypeInfoStructure.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/inheritance/TypeInfoStructure.java diff --git a/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/ActorJackson.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/ActorJackson.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/ActorJackson.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/ActorJackson.java diff --git a/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/ActorJacksonSerializer.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/ActorJacksonSerializer.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/ActorJacksonSerializer.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/ActorJacksonSerializer.java diff --git a/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/Movie.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/Movie.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/Movie.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/Movie.java diff --git a/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/MovieWithNullValue.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/MovieWithNullValue.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/MovieWithNullValue.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/jacksonvsgson/MovieWithNullValue.java diff --git a/jackson/src/main/java/com/baeldung/jackson/node/JsonNodeIterator.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/node/JsonNodeIterator.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/node/JsonNodeIterator.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/node/JsonNodeIterator.java diff --git a/jackson/src/main/java/com/baeldung/jackson/optionalwithjackson/Book.java b/jackson-modules/jackson/src/main/java/com/baeldung/jackson/optionalwithjackson/Book.java similarity index 100% rename from jackson/src/main/java/com/baeldung/jackson/optionalwithjackson/Book.java rename to jackson-modules/jackson/src/main/java/com/baeldung/jackson/optionalwithjackson/Book.java diff --git a/jackson/src/main/resources/example1.json b/jackson-modules/jackson/src/main/resources/example1.json similarity index 100% rename from jackson/src/main/resources/example1.json rename to jackson-modules/jackson/src/main/resources/example1.json diff --git a/jackson/src/main/resources/example2.json b/jackson-modules/jackson/src/main/resources/example2.json similarity index 100% rename from jackson/src/main/resources/example2.json rename to jackson-modules/jackson/src/main/resources/example2.json diff --git a/core-java-modules/core-java-lang-oop/src/main/resources/logback.xml b/jackson-modules/jackson/src/main/resources/logback.xml similarity index 100% rename from core-java-modules/core-java-lang-oop/src/main/resources/logback.xml rename to jackson-modules/jackson/src/main/resources/logback.xml diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/Address.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/dtos/Address.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/dtos/Address.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/dtos/Address.java diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/MyDto.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/dtos/MyDto.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/dtos/MyDto.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/dtos/MyDto.java diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/Person.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/dtos/Person.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/dtos/Person.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/dtos/Person.java diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/User.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/dtos/User.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/dtos/User.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/dtos/User.java diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/IgnoranceUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/inheritance/IgnoranceUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/inheritance/IgnoranceUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/inheritance/IgnoranceUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/jacksonvsgson/JacksonDeserializeUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/jacksonvsgson/JacksonDeserializeUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/jacksonvsgson/JacksonDeserializeUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/jacksonvsgson/JacksonDeserializeUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/jacksonvsgson/JacksonSerializeUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/jacksonvsgson/JacksonSerializeUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/jacksonvsgson/JacksonSerializeUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/jacksonvsgson/JacksonSerializeUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/jsoncompare/JsonCompareUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/jsoncompare/JsonCompareUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/jsoncompare/JsonCompareUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/jsoncompare/JsonCompareUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java diff --git a/jackson/src/test/java/com/baeldung/jackson/node/JsonNodeIteratorUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/node/JsonNodeIteratorUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/node/JsonNodeIteratorUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/node/JsonNodeIteratorUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/node/NodeBean.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/node/NodeBean.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/node/NodeBean.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/node/NodeBean.java diff --git a/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/optionalwithjackson/OptionalTypeUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/optionalwithjackson/OptionalTypeUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/optionalwithjackson/OptionalTypeUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/optionalwithjackson/OptionalTypeUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/sandbox/TestElement.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/sandbox/TestElement.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/sandbox/TestElement.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/sandbox/TestElement.java diff --git a/jackson/src/test/java/com/baeldung/jackson/test/UnitTestSuite.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/test/UnitTestSuite.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/test/UnitTestSuite.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/test/UnitTestSuite.java diff --git a/jackson/src/test/java/com/baeldung/jackson/try1/IEntity.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/try1/IEntity.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/try1/IEntity.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/try1/IEntity.java diff --git a/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequest.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequest.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequest.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequest.java diff --git a/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java b/jackson-modules/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java similarity index 100% rename from jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java rename to jackson-modules/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java diff --git a/jackson/src/test/resources/author-jsonpropertyorder-schema.json b/jackson-modules/jackson/src/test/resources/author-jsonpropertyorder-schema.json similarity index 100% rename from jackson/src/test/resources/author-jsonpropertyorder-schema.json rename to jackson-modules/jackson/src/test/resources/author-jsonpropertyorder-schema.json diff --git a/jackson/src/test/resources/node_example.json b/jackson-modules/jackson/src/test/resources/node_example.json similarity index 100% rename from jackson/src/test/resources/node_example.json rename to jackson-modules/jackson/src/test/resources/node_example.json diff --git a/jackson-modules/pom.xml b/jackson-modules/pom.xml new file mode 100644 index 0000000000..4281710ac9 --- /dev/null +++ b/jackson-modules/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + jackson-modules + jackson-modules + pom + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + jackson + jackson-annotations + jackson-conversions + jackson-conversions-2 + jackson-custom-conversions + jackson-exceptions + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ${jackson.version} + + + + \ No newline at end of file diff --git a/jackson-simple/README.md b/jackson-simple/README.md index ffc76ead22..41aee8cac9 100644 --- a/jackson-simple/README.md +++ b/jackson-simple/README.md @@ -16,4 +16,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### NOTE: -Since this is a module tied to an e-book, it should **not** be used to store the code for any further article. +Since this is a module tied to an e-book, it should **not** be moved or used to store the code for any further article. diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml index cdda031e0f..f41df7085c 100644 --- a/jackson-simple/pom.xml +++ b/jackson-simple/pom.xml @@ -3,7 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jackson-simple - 0.1-SNAPSHOT + 0.0.1-SNAPSHOT jackson-simple @@ -20,7 +20,6 @@ jackson-dataformat-xml ${jackson.version} - org.assertj diff --git a/jackson/pom.xml b/jackson/pom.xml deleted file mode 100644 index d7fc3aac9a..0000000000 --- a/jackson/pom.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - 4.0.0 - jackson - 0.1-SNAPSHOT - jackson - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson.version} - - - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson.version} - - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson.version} - - - - com.fasterxml.jackson.module - jackson-module-jsonSchema - ${jackson.version} - - - - com.fasterxml.jackson.datatype - jackson-datatype-jdk8 - ${jackson.version} - - - - - - io.rest-assured - json-schema-validator - ${rest-assured.version} - test - - - - io.rest-assured - json-path - ${rest-assured.version} - test - - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - jackson - - - src/main/resources - true - - - - - - - 3.1.1 - 3.11.0 - - - diff --git a/java-collections-conversions-2/pom.xml b/java-collections-conversions-2/pom.xml index b04d764719..0f7cdadeb2 100644 --- a/java-collections-conversions-2/pom.xml +++ b/java-collections-conversions-2/pom.xml @@ -20,6 +20,23 @@ commons-lang3 ${commons-lang3.version} + + org.modelmapper + modelmapper + ${modelmapper.version} + + + junit + junit + ${junit.version} + test + + + org.hamcrest + hamcrest + ${hamcrest.version} + test + diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/MapperUtil.java b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/MapperUtil.java new file mode 100644 index 0000000000..23a549e652 --- /dev/null +++ b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/MapperUtil.java @@ -0,0 +1,32 @@ +package com.baeldung.modelmapper; + +import org.modelmapper.ModelMapper; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * This is a helper class that contains method for custom mapping of the users list. + * Initially, an instance of ModelMapper was created. + * + * @author Sasa Milenkovic + */ +public class MapperUtil { + + private static ModelMapper modelMapper = new ModelMapper(); + + + private MapperUtil() { + + + } + + public static List mapList(List source, Class targetClass) { + + return source + .stream() + .map(element -> modelMapper.map(element, targetClass)) + .collect(Collectors.toList()); + } + +} diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/User.java b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/User.java new file mode 100644 index 0000000000..8ed674d86a --- /dev/null +++ b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/User.java @@ -0,0 +1,70 @@ +package com.baeldung.modelmapper; + +/** + * User model entity class + * + * @author Sasa Milenkovic + */ +public class User { + + private String userId; + private String username; + private String email; + private String contactNumber; + private String userType; + + // Standard constructors, getters and setters + + public User() { + } + + public User(String userId, String username, String email, String contactNumber, String userType) { + this.userId = userId; + this.username = username; + this.email = email; + this.contactNumber = contactNumber; + this.userType = userType; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getUsername() { + return username; + } + + public void setUsername(String userName) { + this.username = userName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getContactNumber() { + return contactNumber; + } + + public void setContactNumber(String contactNumber) { + this.contactNumber = contactNumber; + } + + public String getUserType() { + return userType; + } + + public void setUserType(String userType) { + this.userType = userType; + } + + +} diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserDTO.java b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserDTO.java new file mode 100644 index 0000000000..b67bb58ef4 --- /dev/null +++ b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserDTO.java @@ -0,0 +1,41 @@ +package com.baeldung.modelmapper; + +/** + * UserDTO model class + * + * @author Sasa Milenkovic + */ +public class UserDTO { + + private String userId; + private String username; + private String email; + + // getters and setters + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + +} diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserList.java b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserList.java new file mode 100644 index 0000000000..7b6bed807b --- /dev/null +++ b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserList.java @@ -0,0 +1,21 @@ +package com.baeldung.modelmapper; + +import java.util.Collection; + +/** + * UserList class that contain collection of users + * + * @author Sasa Milenkovic + */ +public class UserList { + + private Collection users; + + public Collection getUsers() { + return users; + } + + public void setUsers(Collection users) { + this.users = users; + } +} diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserListDTO.java b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserListDTO.java new file mode 100644 index 0000000000..c001cbbc3c --- /dev/null +++ b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserListDTO.java @@ -0,0 +1,21 @@ +package com.baeldung.modelmapper; + +import java.util.List; + +/** + * UserListDTO class that contain list of username properties + * + * @author Sasa Milenkovic + */ +public class UserListDTO { + + private List usernames; + + public List getUsernames() { + return usernames; + } + + public void setUsernames(List usernames) { + this.usernames = usernames; + } +} diff --git a/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UsersListConverter.java b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UsersListConverter.java new file mode 100644 index 0000000000..19423713e2 --- /dev/null +++ b/java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UsersListConverter.java @@ -0,0 +1,23 @@ +package com.baeldung.modelmapper; + +import org.modelmapper.AbstractConverter; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * UsersListConverter class map the property data from the list of users into the list of user names. + * + * @author Sasa Milenkovic + */ +public class UsersListConverter extends AbstractConverter, List> { + + @Override + protected List convert(List users) { + + return users + .stream() + .map(User::getUsername) + .collect(Collectors.toList()); + } +} diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/modelmapper/UsersListMappingUnitTest.java b/java-collections-conversions-2/src/test/java/com/baeldung/modelmapper/UsersListMappingUnitTest.java new file mode 100644 index 0000000000..a8a72b12f7 --- /dev/null +++ b/java-collections-conversions-2/src/test/java/com/baeldung/modelmapper/UsersListMappingUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.modelmapper; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Test; +import org.modelmapper.ModelMapper; +import org.modelmapper.TypeMap; +import org.modelmapper.TypeToken; + +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasProperty; +import static org.junit.Assert.assertThat; + + +/** + * This class has test methods of mapping Integer to Character list, + * mapping users list to DTO list using MapperUtil custom type method and property mapping using converter class + * + * @author Sasa Milenkovic + */ +public class UsersListMappingUnitTest { + + private ModelMapper modelMapper; + private List users; + + @Before + public void init() { + + modelMapper = new ModelMapper(); + + TypeMap typeMap = modelMapper.createTypeMap(UserList.class, UserListDTO.class); + + typeMap.addMappings(mapper -> mapper.using(new UsersListConverter()) + .map(UserList::getUsers, UserListDTO::setUsernames)); + + users = new ArrayList(); + users.add(new User("b100", "user1", "user1@baeldung.com", "111-222", "USER")); + users.add(new User("b101", "user2", "user2@baeldung.com", "111-333", "USER")); + users.add(new User("b102", "user3", "user3@baeldung.com", "111-444", "ADMIN")); + + } + + @Test + public void whenInteger_thenMapToCharacter() { + + List integers = new ArrayList(); + + integers.add(1); + integers.add(2); + integers.add(3); + + List characters = modelMapper.map(integers, new TypeToken>() { + }.getType()); + + assertThat(characters, hasItems('1', '2', '3')); + + } + + @Test + public void givenUsersList_whenUseGenericType_thenMapToUserDTO() { + + // Mapping lists using custom (generic) type mapping + + List userDtoList = MapperUtil.mapList(users, UserDTO.class); + + assertThat(userDtoList, Matchers.hasItem( + Matchers.both(hasProperty("userId", equalTo("b100"))) + .and(hasProperty("email", equalTo("user1@baeldung.com"))) + .and(hasProperty("username", equalTo("user1"))))); + + + } + + @Test + public void givenUsersList_whenUseConverter_thenMapToUsernames() { + + // Mapping lists using property mapping and converter + + UserList userList = new UserList(); + userList.setUsers(users); + UserListDTO dtos = new UserListDTO(); + modelMapper.map(userList, dtos); + + assertThat(dtos.getUsernames(), hasItems("user1", "user2", "user3")); + + } + +} \ No newline at end of file diff --git a/java-collections-maps-2/README.md b/java-collections-maps-2/README.md deleted file mode 100644 index 8b33276f56..0000000000 --- a/java-collections-maps-2/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## Java Collections Cookbooks and Examples - -This module contains articles about Map data structures in Java. - -### Relevant Articles: -- [Map of Primitives in Java](https://www.baeldung.com/java-map-primitives) -- [Copying a HashMap in Java](https://www.baeldung.com/java-copy-hashmap) -- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) -- [Guide to WeakHashMap in Java](https://www.baeldung.com/java-weakhashmap) -- [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion) -- [Iterate over a Map in Java](https://www.baeldung.com/java-iterate-map) -- [Merging Two Maps with Java 8](https://www.baeldung.com/java-merge-maps) -- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort) -- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max) -- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap) -- More articles: [[<-- prev>]](/../java-collections-maps) diff --git a/java-collections-maps-2/pom.xml b/java-collections-maps-2/pom.xml deleted file mode 100644 index a246559f61..0000000000 --- a/java-collections-maps-2/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - 4.0.0 - java-collections-maps-2 - 0.1.0-SNAPSHOT - java-collections-maps-2 - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - org.eclipse.collections - eclipse-collections - ${eclipse-collections.version} - - - net.sf.trove4j - trove4j - ${trove4j.version} - - - it.unimi.dsi - fastutil - ${fastutil.version} - - - colt - colt - ${colt.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - one.util - streamex - ${streamex.version} - - - com.jayway.awaitility - awaitility - ${avaitility.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - 0.6.5 - 4.1 - 1.7.0 - 8.2.0 - 3.0.2 - 8.1.0 - 1.2.0 - 3.11.1 - - - \ No newline at end of file diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md new file mode 100644 index 0000000000..4da8547824 --- /dev/null +++ b/java-collections-maps-3/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys) diff --git a/java-collections-maps-3/pom.xml b/java-collections-maps-3/pom.xml new file mode 100644 index 0000000000..3888623a7f --- /dev/null +++ b/java-collections-maps-3/pom.xml @@ -0,0 +1,43 @@ + + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + 4.0.0 + java-collections-maps-3 + 0.1.0-SNAPSHOT + java-collections-maps-3 + jar + + + + org.springframework + spring-core + ${spring.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + + + 4.1 + 3.6.1 + 5.2.5.RELEASE + + diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java new file mode 100644 index 0000000000..833807c692 --- /dev/null +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -0,0 +1,94 @@ +package com.baeldung.map.caseinsensitivekeys; + +import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.junit.Test; +import org.springframework.util.LinkedCaseInsensitiveMap; +import java.util.Map; +import java.util.TreeMap; +import static org.junit.Assert.*; + +public class CaseInsensitiveMapUnitTest { + @Test + public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + assertEquals(1, treeMap.size()); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + Map commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(1, commonsHashMap.size()); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + assertEquals(1, linkedHashMap.size()); + } + + @Test + public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + assertEquals(2, treeMap.get("aBc").intValue()); + assertEquals(2, treeMap.get("ABc").intValue()); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + Map commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(2, commonsHashMap.get("aBc").intValue()); + assertEquals(2, commonsHashMap.get("ABc").intValue()); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + assertEquals(2, linkedHashMap.get("aBc").intValue()); + assertEquals(2, linkedHashMap.get("ABc").intValue()); + } + + @Test + public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 3); + treeMap.remove("aBC"); + + assertEquals(0, treeMap.size()); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + Map commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 3); + commonsHashMap.remove("aBC"); + + assertEquals(0, commonsHashMap.size()); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 3); + linkedHashMap.remove("aBC"); + + assertEquals(0, linkedHashMap.size()); + } +} diff --git a/java-collections-maps/README.md b/java-collections-maps/README.md deleted file mode 100644 index dfd0d47dbc..0000000000 --- a/java-collections-maps/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## Java Collections Cookbooks and Examples - -This module contains articles about Map data structures in Java. - -### Relevant Articles: -- [Guide to the Guava BiMap](https://www.baeldung.com/guava-bimap) -- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) -- [A Guide to LinkedHashMap in Java](https://www.baeldung.com/java-linked-hashmap) -- [A Guide to TreeMap in Java](https://www.baeldung.com/java-treemap) -- [How to Store Duplicate Keys in a Map in Java?](https://www.baeldung.com/java-map-duplicate-keys) -- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value) -- [How to Check If a Key Exists in a Map](https://www.baeldung.com/java-map-key-exists) -- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) -- [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps) -- [Guide to Apache Commons MultiValuedMap](https://www.baeldung.com/apache-commons-multi-valued-map) -- [The Java HashMap Under the Hood](https://www.baeldung.com/java-hashmap-advanced) -- More articles: [[next -->]](/../java-collections-maps-2) diff --git a/java-collections-maps/pom.xml b/java-collections-maps/pom.xml deleted file mode 100644 index 38cf1c38ad..0000000000 --- a/java-collections-maps/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - 4.0.0 - java-collections-maps - 0.1.0-SNAPSHOT - java-collections-maps - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - 4.1 - 3.6.1 - - diff --git a/java-ee-8-security-api/README.md b/java-ee-8-security-api/README.md index b01a073e35..17142f8102 100644 --- a/java-ee-8-security-api/README.md +++ b/java-ee-8-security-api/README.md @@ -4,4 +4,4 @@ This module contains articles about the Security API in Java EE 8. ### Relevant articles - - [Java EE 8 Security API](https://www.baeldung.com/java-ee-8-security) + - [Jakarta EE 8 Security API](https://www.baeldung.com/java-ee-8-security) 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 index 912a2cabac..f8d19b5750 100644 --- 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 @@ -1,7 +1,8 @@ - + 4.0.0 app-auth-form-store-ldap app-auth-form-store-ldap @@ -17,7 +18,7 @@ com.unboundid unboundid-ldapsdk - 4.0.4 + ${unboundid.ldapsdk.version} @@ -48,4 +49,8 @@ + + 4.0.4 + + diff --git a/java-math-2/README.md b/java-math-2/README.md deleted file mode 100644 index ca809e8623..0000000000 --- a/java-math-2/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Java Math - -This module contains articles about math in Java. - -### Relevant articles: - -- [Basic Calculator in Java](https://www.baeldung.com/basic-calculator-in-java) -- More articles: [[<-- prev]](/../java-math) diff --git a/java-math-2/pom.xml b/java-math-2/pom.xml deleted file mode 100644 index e22dcc2b31..0000000000 --- a/java-math-2/pom.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - 4.0.0 - java-math-2 - 0.0.1-SNAPSHOT - java-math-2 - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - \ No newline at end of file diff --git a/java-math/README.md b/java-math/README.md deleted file mode 100644 index d80a07258a..0000000000 --- a/java-math/README.md +++ /dev/null @@ -1,18 +0,0 @@ -## Java Math - -This module contains articles about math in Java. - -### Relevant articles: - -- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial) -- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm) -- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap) -- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points) -- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines) -- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred) -- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage) -- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude) -- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging) -- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication) -- [Calculating Logarithms in Java](https://www.baeldung.com/java-logarithms) -- [Finding Greatest Common Divisor in Java](https://www.baeldung.com/java-greatest-common-divisor) diff --git a/java-math/pom.xml b/java-math/pom.xml deleted file mode 100644 index 9b4af4c13d..0000000000 --- a/java-math/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - 4.0.0 - java-math - 0.0.1-SNAPSHOT - java-math - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.apache.commons - commons-math3 - ${commons-math3.version} - - - org.ejml - ejml-all - ${ejml.version} - - - org.nd4j - nd4j-native - ${nd4j.version} - - - org.la4j - la4j - ${la4j.version} - - - colt - colt - ${colt.version} - - - com.google.guava - guava - ${guava.version} - - - org.assertj - assertj-core - ${org.assertj.core.version} - test - - - com.github.dpaukov - combinatoricslib3 - ${combinatoricslib3.version} - - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh.version} - - - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - - - - - - 3.6.1 - 3.9.0 - 27.0.1-jre - 3.3.0 - 0.38 - 1.0.0-beta4 - 1.2.0 - 0.6.0 - 1.19 - - - \ No newline at end of file diff --git a/java-numbers-2/README.md b/java-numbers-2/README.md index e200c4aa03..1d996e32cc 100644 --- a/java-numbers-2/README.md +++ b/java-numbers-2/README.md @@ -13,6 +13,4 @@ This module contains articles about numbers in Java. - [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers) - [Finding the Least Common Multiple in Java](https://www.baeldung.com/java-least-common-multiple) - [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers) -- [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers) -- [Listing Numbers Within a Range in Java](https://www.baeldung.com/java-listing-numbers-within-a-range) -- More articles: [[<-- prev]](/../java-numbers) +- More articles: [[<-- prev]](/java-numbers) [[next -->]](/java-numbers-3) diff --git a/java-numbers-2/pom.xml b/java-numbers-2/pom.xml index ba40ef0a38..5c81b00756 100644 --- a/java-numbers-2/pom.xml +++ b/java-numbers-2/pom.xml @@ -21,6 +21,11 @@ jmh-generator-annprocess ${jmh-generator.version} + + it.unimi.dsi + dsiutils + ${dsiutils.version} + @@ -33,4 +38,8 @@ + + 2.6.0 + + diff --git a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java index 68382c26ea..7af8c5d58d 100644 --- a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java +++ b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java @@ -7,7 +7,7 @@ public class BruteForcePrimeChecker implements PrimeChecker { @Override public boolean isPrime(Integer number) { - return number > 2 ? IntStream.range(2, number) + return number > 1 ? IntStream.range(2, number) .noneMatch(n -> (number % n == 0)) : false; } diff --git a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java index 3dc372ad22..3019c76eb4 100644 --- a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java +++ b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java @@ -6,7 +6,7 @@ public class OptimisedPrimeChecker implements PrimeChecker { @Override public boolean isPrime(Integer number) { - return number > 2 ? IntStream.rangeClosed(2, (int) Math.sqrt(number)) + return number > 1 ? IntStream.rangeClosed(2, (int) Math.sqrt(number)) .noneMatch(n -> (number % n == 0)) : false; } diff --git a/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java index 9f8ba8defd..6e425b3051 100644 --- a/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java +++ b/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java @@ -11,22 +11,24 @@ public class PrimeCheckerUnitTest { @Test public void whenCheckIsPrime_thenTrue() { - assertTrue(primeChecker.isPrime(13l)); + assertTrue(primeChecker.isPrime(2L)); + assertTrue(primeChecker.isPrime(13L)); assertTrue(primeChecker.isPrime(1009L)); assertTrue(primeChecker.isPrime(74207281L)); } @Test public void whenCheckIsPrime_thenFalse() { - assertTrue(!primeChecker.isPrime(50L)); - assertTrue(!primeChecker.isPrime(1001L)); - assertTrue(!primeChecker.isPrime(74207282L)); + assertFalse(primeChecker.isPrime(50L)); + assertFalse(primeChecker.isPrime(1001L)); + assertFalse(primeChecker.isPrime(74207282L)); } private final BruteForcePrimeChecker bfPrimeChecker = new BruteForcePrimeChecker(); @Test public void whenBFCheckIsPrime_thenTrue() { + assertTrue(bfPrimeChecker.isPrime(2)); assertTrue(bfPrimeChecker.isPrime(13)); assertTrue(bfPrimeChecker.isPrime(1009)); } @@ -41,6 +43,7 @@ public class PrimeCheckerUnitTest { @Test public void whenOptCheckIsPrime_thenTrue() { + assertTrue(optimisedPrimeChecker.isPrime(2)); assertTrue(optimisedPrimeChecker.isPrime(13)); assertTrue(optimisedPrimeChecker.isPrime(1009)); } @@ -55,6 +58,7 @@ public class PrimeCheckerUnitTest { @Test public void whenPrimesCheckIsPrime_thenTrue() { + assertTrue(primesPrimeChecker.isPrime(2)); assertTrue(primesPrimeChecker.isPrime(13)); assertTrue(primesPrimeChecker.isPrime(1009)); } diff --git a/java-numbers-3/README.md b/java-numbers-3/README.md new file mode 100644 index 0000000000..f818bdb675 --- /dev/null +++ b/java-numbers-3/README.md @@ -0,0 +1,14 @@ +## Java Number Cookbooks and Examples + +This module contains articles about numbers in Java. + +### Relevant Articles: + +- [Generating Random Numbers](https://www.baeldung.com/java-generating-random-numbers) +- [Convert Double to Long in Java](https://www.baeldung.com/java-convert-double-long) +- [Check for null Before Calling Parse in Double.parseDouble](https://www.baeldung.com/java-check-null-parse-double) +- [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers-in-range) +- [Listing Numbers Within a Range in Java](https://www.baeldung.com/java-listing-numbers-within-a-range) +- [Fibonacci Series in Java](https://www.baeldung.com/java-fibonacci) +- [Guide to the Number Class in Java](https://www.baeldung.com/java-number-class) +- More articles: [[<-- prev]](/java-numbers-2) diff --git a/java-numbers-3/pom.xml b/java-numbers-3/pom.xml new file mode 100644 index 0000000000..495618885a --- /dev/null +++ b/java-numbers-3/pom.xml @@ -0,0 +1,58 @@ + + 4.0.0 + java-numbers-3 + java-numbers-3 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + it.unimi.dsi + dsiutils + ${dsiutils.version} + + + io.vavr + vavr + ${vavr.version} + + + org.apache.commons + commons-lang3 + ${commons.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + java-numbers-3 + + + src/main/resources + true + + + + + + 2.6.0 + 0.10.2 + 3.9 + 3.6.1 + + + diff --git a/java-numbers-2/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java b/java-numbers-3/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java similarity index 96% rename from java-numbers-2/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java rename to java-numbers-3/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java index 943fcffa56..616f3ab28f 100644 --- a/java-numbers-2/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java +++ b/java-numbers-3/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java @@ -1,7 +1,5 @@ package com.baeldung.fibonacci; -import static java.lang.Math.pow; - public class FibonacciSeriesUtils { public static int nthFibonacciTermRecursiveMethod(int n) { diff --git a/java-numbers-2/src/main/java/com/baeldung/numbersinrange/NumbersInARange.java b/java-numbers-3/src/main/java/com/baeldung/numbersinrange/NumbersInARange.java similarity index 100% rename from java-numbers-2/src/main/java/com/baeldung/numbersinrange/NumbersInARange.java rename to java-numbers-3/src/main/java/com/baeldung/numbersinrange/NumbersInARange.java diff --git a/java-numbers-2/src/main/java/com/baeldung/numbersinrange/RandomNumbersInARange.java b/java-numbers-3/src/main/java/com/baeldung/numbersinrange/RandomNumbersInARange.java similarity index 100% rename from java-numbers-2/src/main/java/com/baeldung/numbersinrange/RandomNumbersInARange.java rename to java-numbers-3/src/main/java/com/baeldung/numbersinrange/RandomNumbersInARange.java diff --git a/java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java b/java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java new file mode 100644 index 0000000000..50a072371e --- /dev/null +++ b/java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java @@ -0,0 +1,103 @@ +package com.baeldung.randomnumbers; + +import java.security.SecureRandom; +import java.util.Random; +import java.util.SplittableRandom; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.IntStream; + +import org.apache.commons.math3.random.RandomDataGenerator; + +import it.unimi.dsi.util.XoRoShiRo128PlusRandom; + +public class RandomNumbersGenerator { + + public Integer generateRandomWithMathRandom(int max, int min) { + return (int) ((Math.random() * (max - min)) + min); + } + + public Integer generateRandomWithNextInt() { + Random random = new Random(); + int randomWithNextInt = random.nextInt(); + return randomWithNextInt; + } + + public Integer generateRandomWithNextIntWithinARange(int min, int max) { + Random random = new Random(); + int randomWintNextIntWithinARange = random.nextInt(max - min) + min; + return randomWintNextIntWithinARange; + } + + public IntStream generateRandomUnlimitedIntStream() { + Random random = new Random(); + IntStream unlimitedIntStream = random.ints(); + return unlimitedIntStream; + } + + public IntStream generateRandomLimitedIntStream(long streamSize) { + Random random = new Random(); + IntStream limitedIntStream = random.ints(streamSize); + return limitedIntStream; + } + + public IntStream generateRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) { + Random random = new Random(); + IntStream limitedIntStreamWithinARange = random.ints(streamSize, min, max); + return limitedIntStreamWithinARange; + } + + public Integer generateRandomWithThreadLocalRandom() { + int randomWithThreadLocalRandom = ThreadLocalRandom.current() + .nextInt(); + return randomWithThreadLocalRandom; + } + + public Integer generateRandomWithThreadLocalRandomInARange(int min, int max) { + int randomWithThreadLocalRandomInARange = ThreadLocalRandom.current() + .nextInt(min, max); + return randomWithThreadLocalRandomInARange; + } + + public Integer generateRandomWithThreadLocalRandomFromZero(int max) { + int randomWithThreadLocalRandomFromZero = ThreadLocalRandom.current() + .nextInt(max); + return randomWithThreadLocalRandomFromZero; + } + + public Integer generateRandomWithSplittableRandom(int min, int max) { + SplittableRandom splittableRandom = new SplittableRandom(); + int randomWithSplittableRandom = splittableRandom.nextInt(min, max); + return randomWithSplittableRandom; + } + + public IntStream generateRandomWithSplittableRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) { + SplittableRandom splittableRandom = new SplittableRandom(); + IntStream limitedIntStreamWithinARangeWithSplittableRandom = splittableRandom.ints(streamSize, min, max); + return limitedIntStreamWithinARangeWithSplittableRandom; + } + + public Integer generateRandomWithSecureRandom() { + SecureRandom secureRandom = new SecureRandom(); + int randomWithSecureRandom = secureRandom.nextInt(); + return randomWithSecureRandom; + } + + public Integer generateRandomWithSecureRandomWithinARange(int min, int max) { + SecureRandom secureRandom = new SecureRandom(); + int randomWithSecureRandomWithinARange = secureRandom.nextInt(max - min) + min; + return randomWithSecureRandomWithinARange; + } + + public Integer generateRandomWithRandomDataGenerator(int min, int max) { + RandomDataGenerator randomDataGenerator = new RandomDataGenerator(); + int randomWithRandomDataGenerator = randomDataGenerator.nextInt(min, max); + return randomWithRandomDataGenerator; + } + + public Integer generateRandomWithXoRoShiRo128PlusRandom(int min, int max) { + XoRoShiRo128PlusRandom xoroRandom = new XoRoShiRo128PlusRandom(); + int randomWithXoRoShiRo128PlusRandom = xoroRandom.nextInt(max - min) + min; + return randomWithXoRoShiRo128PlusRandom; + } + +} diff --git a/java-numbers-3/src/test/java/com/baeldung/abstractnumber/AbstractNumberUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/abstractnumber/AbstractNumberUnitTest.java new file mode 100644 index 0000000000..521f2d37a6 --- /dev/null +++ b/java-numbers-3/src/test/java/com/baeldung/abstractnumber/AbstractNumberUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.abstractnumber; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class AbstractNumberUnitTest { + + private final static double DOUBLE_VALUE = 9999.999; + private final static float FLOAT_VALUE = 101.99F; + private final static long LONG_VALUE = 1000L; + private final static int INTEGER_VALUE = 100; + private final static short SHORT_VALUE = 127; + private final static byte BYTE_VALUE = 120; + + @Test + public void givenDoubleValue_whenShortValueUsed_thenShortValueReturned() { + Double doubleValue = Double.valueOf(DOUBLE_VALUE); + assertEquals(9999, doubleValue.shortValue()); + } + + @Test + public void givenFloatValue_whenByteValueUsed_thenByteValueReturned() { + Float floatValue = Float.valueOf(FLOAT_VALUE); + assertEquals(101, floatValue.byteValue()); + } + + @Test + public void givenLongValue_whenInitValueUsed_thenInitValueReturned() { + Long longValue = Long.valueOf(LONG_VALUE); + assertEquals(1000, longValue.intValue()); + } + + @Test + public void givenIntegerValue_whenLongValueUsed_thenLongValueReturned() { + Integer integerValue = Integer.valueOf(INTEGER_VALUE); + assertEquals(100, integerValue.longValue()); + } + + @Test + public void givenShortValue_whenFloatValueUsed_thenFloatValueReturned() { + Short shortValue = Short.valueOf(SHORT_VALUE); + assertEquals(127.0F, shortValue.floatValue(), 0); + } + + @Test + public void givenByteValue_whenDoubleValueUsed_thenDoubleValueReturned() { + Byte byteValue = Byte.valueOf(BYTE_VALUE); + assertEquals(120.0, byteValue.doubleValue(), 0); + } + +} diff --git a/java-numbers-3/src/test/java/com/baeldung/doubletolong/DoubleToLongUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/doubletolong/DoubleToLongUnitTest.java new file mode 100644 index 0000000000..702c59c12b --- /dev/null +++ b/java-numbers-3/src/test/java/com/baeldung/doubletolong/DoubleToLongUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.doubletolong; + +import org.junit.Assert; +import org.junit.Test; + +public class DoubleToLongUnitTest { + + final static double VALUE = 9999.999; + + @Test + public void givenDoubleValue_whenLongValueCalled_thenLongValueReturned() { + Assert.assertEquals(9999L, Double.valueOf(VALUE).longValue()); + } + + @Test + public void givenDoubleValue_whenMathRoundUsed_thenRoundUp() { + Assert.assertEquals(10000L, Math.round(VALUE)); + } + + @Test + public void givenDoubleValue_whenMathRoundUsed_thenRoundDown() { + Assert.assertEquals(9999L, Math.round(9999.444)); + } + + @Test + public void givenDoubleValue_whenMathRoundUsed_thenSameValueReturned() { + Assert.assertEquals(9999L, Math.round(9999.0)); + } + + @Test + public void givenDoubleValue_whenMathCeilUsed_thenLongValueReturned() { + Assert.assertEquals(10000L, Math.ceil(VALUE), 0); + } + + @Test + public void givenDoubleValue_whenMathCeilUsed_thenSameValueReturned() { + Assert.assertEquals(9999L, Math.ceil(9999.0), 0); + } + + @Test + public void givenDoubleValue_whenMathCeilUsed_thenDifferentThanRound() { + Assert.assertEquals(10000L, Math.ceil(9999.444), 0); + } + + @Test + public void givenDoubleValue_whenMathFloorUsed_thenLongValueReturned() { + Assert.assertEquals(9999L, Math.floor(VALUE), 0); + } + + @Test + public void givenDoubleValue_whenMathFloorUsed_thenSameValueReturned() { + Assert.assertEquals(9999L, Math.floor(9999.0), 0); + } + + @Test + public void givenDoubleValue_whenMathFloorUsed_thenDifferentThanCeil() { + Assert.assertEquals(9999L, Math.floor(9999.444), 0); + } + + @Test + public void givenDoubleValue_whenTypeCasted_thenLongValueReturned() { + Assert.assertEquals(9999L, (long) VALUE); + } +} diff --git a/java-numbers-2/src/test/java/com/baeldung/fibonacci/FibonacciSeriesUtilsUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/fibonacci/FibonacciSeriesUtilsUnitTest.java similarity index 100% rename from java-numbers-2/src/test/java/com/baeldung/fibonacci/FibonacciSeriesUtilsUnitTest.java rename to java-numbers-3/src/test/java/com/baeldung/fibonacci/FibonacciSeriesUtilsUnitTest.java diff --git a/java-numbers-2/src/test/java/com/baeldung/numbersinrange/NumbersInARangeUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/numbersinrange/NumbersInARangeUnitTest.java similarity index 100% rename from java-numbers-2/src/test/java/com/baeldung/numbersinrange/NumbersInARangeUnitTest.java rename to java-numbers-3/src/test/java/com/baeldung/numbersinrange/NumbersInARangeUnitTest.java diff --git a/java-numbers-2/src/test/java/com/baeldung/numbersinrange/RandomNumbersInARangeUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/numbersinrange/RandomNumbersInARangeUnitTest.java similarity index 100% rename from java-numbers-2/src/test/java/com/baeldung/numbersinrange/RandomNumbersInARangeUnitTest.java rename to java-numbers-3/src/test/java/com/baeldung/numbersinrange/RandomNumbersInARangeUnitTest.java diff --git a/java-numbers-3/src/test/java/com/baeldung/parsedouble/StringToDoubleParserUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/parsedouble/StringToDoubleParserUnitTest.java new file mode 100644 index 0000000000..b3dec3d14f --- /dev/null +++ b/java-numbers-3/src/test/java/com/baeldung/parsedouble/StringToDoubleParserUnitTest.java @@ -0,0 +1,149 @@ +package com.baeldung.parsedouble; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Optional; + +import org.apache.commons.lang3.math.NumberUtils; +import org.junit.Test; + +import com.google.common.base.MoreObjects; +import com.google.common.primitives.Doubles; + +import io.vavr.control.Try; + +public class StringToDoubleParserUnitTest { + + @Test + public void givenNullValue_whenParseStringToDouble_thenDefaultNaNValueIsReturned() { + assertThat(parseStringToDouble(null)).isNaN(); + } + + @Test + public void givenEmptyStringValue_whenParseStringToDouble_thenDefaultNaNValueIsReturned() { + assertThat(parseStringToDouble("")).isNaN(); + } + + @Test + public void givenStringValue_whenParseStringToDouble_thenDoubleValueIsReturned() { + assertThat(parseStringToDouble("1")).isEqualTo(1.0d); + } + + @Test + public void givenStringValue_whenParseStringToDoubleWithDefault_thenDoubleValueIsReturned() { + assertThat(parseStringToDouble("1", 2.0d)).isEqualTo(1.0d); + } + + @Test + public void givenEmptyStringValue_whenParseStringToDoubleWithDefault_thenDefaultValueIsReturned() { + assertThat(parseStringToDouble("", 1.0d)).isEqualTo(1.0d); + } + + @Test + public void givenNullValue_whenParseStringToDoubleWithDefault_thenDefaultValueIsReturned() { + assertThat(parseStringToDouble(null, 1.0d)).isEqualTo(1.0d); + } + + @Test + public void givenStringValue_whenParseStringToOptionalDouble_thenOptionalValueIsReturned() { + assertThat(parseStringToOptionalDouble("1")).isEqualTo(Optional.of(1.0d)); + } + + @Test + public void givenNullValue_whenParseStringToOptionalDouble_thenOptionalValueIsEmpty() { + assertThat(parseStringToOptionalDouble(null)).isEqualTo(Optional.empty()); + } + + @Test + public void givenEmptyStringValue_whenParseStringToOptionalDouble_thenOptionalValueIsEmpty() { + assertThat(parseStringToOptionalDouble("")).isEqualTo(Optional.empty()); + } + + @Test + public void givenEmptyStringValue_whenParseStringToOptionalDouble_thenDefaulOptionalValueIsReturned() { + assertThat(parseStringToOptionalDouble("").orElse(1.0d)).isEqualTo(1.0d); + } + + @Test + public void givenNullValue_whenParseStringToOptionalDouble_thenDefaulOptionalValueIsReturned() { + assertThat(parseStringToOptionalDouble(null).orElse(1.0d)).isEqualTo(1.0d); + } + + @Test + public void givenStringValue_whenTryStringToDouble_thenDoubleValueIsReturned() { + assertThat(tryStringToDouble("1", 2.0d)).isEqualTo(1.0d); + } + + @Test + public void givenNullValue_whenTryStringToDoubleWithDefault_thenDoubleValueIsReturned() { + assertThat(tryStringToDouble(null, 2.0d)).isEqualTo(2.0d); + } + + @Test + public void givenEmptyStringValue_whenTryStringToDoubleWithDefault_thenDoubleValueIsReturned() { + assertThat(tryStringToDouble("", 2.0d)).isEqualTo(2.0d); + } + + @Test + public void givenTwoStringValues_whenTryParseFirstNonNull_thenDoubleValueIsReturned() { + assertThat(Doubles.tryParse(MoreObjects.firstNonNull("1.0", "2.0"))).isEqualTo(1.0d); + } + + @Test + public void givenNullStringValue_whenTryParseFirstNonNull_thenSecondDoubleValueIsReturned() { + assertThat(Doubles.tryParse(MoreObjects.firstNonNull(null, "2.0"))).isEqualTo(2.0d); + } + + @Test + public void givenEmptyStringValue_whenTryParseFirstNonNull_thenNullIsReturned() { + assertThat(Doubles.tryParse(MoreObjects.firstNonNull("", "2.0"))).isEqualTo(null); + } + + @Test + public void givenStringValue_whenToDouble_thenDoubleValueIsReturned() { + assertThat(NumberUtils.toDouble("1.0")).isEqualTo(1.0d); + } + + @Test + public void givenNullValue_whenToDouble_thenLibraryDefaultDoubleValueIsReturned() { + String nullString = null; + assertThat(NumberUtils.toDouble(nullString)).isEqualTo(0.0d); + } + + @Test + public void givenEmptyStringValue_whenToDouble_thenLibraryDefaultDoubleValueIsReturned() { + assertThat(NumberUtils.toDouble("")).isEqualTo(0.0d); + } + + @Test + public void givenEmptyStringValue_whenToDoubleWithDefault_thenDoubleValueIsReturned() { + assertThat(NumberUtils.toDouble("", 2.0d)).isEqualTo(2.0d); + } + + @Test + public void givenNullValue_whenToDoubleWithDefault_thenDoubleValueIsReturned() { + String nullString = null; + assertThat(NumberUtils.toDouble(nullString, 2.0d)).isEqualTo(2.0d); + } + + @Test + public void givenStringValue_whenToDoubleWithDefault_thenDoubleValueIsReturned() { + assertThat(NumberUtils.toDouble("1.0", 2.0d)).isEqualTo(1.0d); + } + + private static Optional parseStringToOptionalDouble(String value) { + return value == null || value.isEmpty() ? Optional.empty() : Optional.of(Double.valueOf(value)); + } + + private static double parseStringToDouble(String value) { + return value == null || value.isEmpty() ? Double.NaN : Double.parseDouble(value); + } + + private static double parseStringToDouble(String value, double defaultValue) { + return value == null || value.isEmpty() ? defaultValue : Double.parseDouble(value); + } + + private static double tryStringToDouble(String value, double defaultValue) { + return Try.of(() -> Double.parseDouble(value)).getOrElse(defaultValue); + } +} diff --git a/java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java new file mode 100644 index 0000000000..bdd955a4ee --- /dev/null +++ b/java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java @@ -0,0 +1,154 @@ +package com.baeldung.randomnumbers; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.stream.IntStream; + +import org.junit.Test; + +public class RandomNumbersGeneratorUnitTest { + + private static final int MIN_RANGE = 1; + private static final int MAX_RANGE = 10; + private static final int MIN_RANGE_NEGATIVE = -10; + private static final int ITERATIONS = 50; + private static final long STREAM_SIZE = 50; + + @Test + public void whenGenerateRandomWithMathRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumer = generator.generateRandomWithMathRandom(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumer, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithNextInt_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithNextInt(); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + } + + @Test + public void whenGenerateRandomWithNextIntWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithNextIntWithinARange(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomUnlimitedIntStream_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + IntStream stream = generator.generateRandomUnlimitedIntStream(); + assertNotNull(stream); + Integer randomNumber = stream.findFirst() + .getAsInt(); + assertNotNull(randomNumber); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + + @Test + public void whenGenerateRandomLimitedIntStream_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + generator.generateRandomLimitedIntStream(STREAM_SIZE) + .forEach(randomNumber -> assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE))); + } + + @Test + public void whenGenerateRandomLimitedIntStreamWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + generator.generateRandomLimitedIntStreamWithinARange(MIN_RANGE, MAX_RANGE, STREAM_SIZE) + .forEach(randomNumber -> assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE))); + } + + @Test + public void whenGenerateRandomWithThreadLocalRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithThreadLocalRandom(); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + } + + @Test + public void whenGenerateRandomWithThreadLocalRandomInARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithThreadLocalRandomInARange(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithThreadLocalRandomFromZero_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithThreadLocalRandomFromZero(MAX_RANGE); + assertTrue(isInRange(randomNumber, 0, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithSplittableRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithSplittableRandom(MIN_RANGE_NEGATIVE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE_NEGATIVE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithSplittableRandomLimitedIntStreamWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + generator.generateRandomWithSplittableRandomLimitedIntStreamWithinARange(MIN_RANGE, MAX_RANGE, STREAM_SIZE) + .forEach(randomNumber -> assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE))); + } + + @Test + public void whenGenerateRandomWithSecureRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithSecureRandom(); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + } + + @Test + public void whenGenerateRandomWithSecureRandomWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithSecureRandomWithinARange(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithRandomDataGenerator_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithRandomDataGenerator(MIN_RANGE, MAX_RANGE); + // RandomDataGenerator top is inclusive + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE + 1)); + } + } + + @Test + public void whenGenerateRandomWithXoRoShiRo128PlusRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithXoRoShiRo128PlusRandom(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + private boolean isInRange(int number, int min, int max) { + return min <= number && number < max; + } + +} diff --git a/java-numbers/README.md b/java-numbers/README.md index eee6fceab1..f4b76c3c98 100644 --- a/java-numbers/README.md +++ b/java-numbers/README.md @@ -8,9 +8,9 @@ This module contains articles about numbers in Java. - [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) -- [Using Math.sin with Degrees](https://www.baeldung.com/java-math-sin-degrees) - [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat) - [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root) - [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string) - [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order) +- [Using Math.sin with Degrees](https://www.baeldung.com/java-math-sin-degrees) - More articles: [[next -->]](/../java-numbers-2) diff --git a/javax-servlets/README.md b/javax-servlets/README.md index 085cc04f87..7dbe1a02ad 100644 --- a/javax-servlets/README.md +++ b/javax-servlets/README.md @@ -9,6 +9,6 @@ This module contains articles about Servlets. - [Uploading Files with Servlets and JSP](https://www.baeldung.com/upload-file-servlet) - [Example of Downloading File in a Servlet](https://www.baeldung.com/servlet-download-file) - [Returning a JSON Response from a Servlet](https://www.baeldung.com/servlet-json-response) -- [Java EE Servlet Exception Handling](https://www.baeldung.com/servlet-exceptions) +- [Jakarta EE Servlet Exception Handling](https://www.baeldung.com/servlet-exceptions) - [Context and Servlet Initialization Parameters](https://www.baeldung.com/context-servlet-initialization-param) - [The Difference between getRequestURI and getPathInfo in HttpServletRequest](https://www.baeldung.com/http-servlet-request-requesturi-pathinfo) diff --git a/javaxval/src/main/java/com/baeldung/javaxval/beanvalidation/User.java b/javaxval/src/main/java/com/baeldung/javaxval/beanvalidation/User.java new file mode 100644 index 0000000000..d583ac51d2 --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/beanvalidation/User.java @@ -0,0 +1,93 @@ +package com.baeldung.javaxval.beanvalidation; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +import javax.validation.constraints.AssertTrue; +import javax.validation.constraints.Email; +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Past; +import javax.validation.constraints.Size; + +public class User { + + @NotNull(message = "Name cannot be null") + private String name; + + @AssertTrue + private boolean working; + + @Size(min = 10, max = 200, message = "Number of characters should be in between 10 and 200 inclusive") + private String aboutMe; + + @Min(value = 18, message = "Age should not be less than 18") + @Max(value = 150, message = "Age should not be more than 150") + private int age; + + @Email(message = "Email should be valid") + private String email; + + private List<@NotBlank String> preferences; + + private LocalDate dateOfBirth; + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public boolean isWorking() { + return working; + } + + public void setWorking(boolean working) { + this.working = working; + } + + public String getAboutMe() { + return aboutMe; + } + + public void setAboutMe(String aboutMe) { + this.aboutMe = aboutMe; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Optional<@Past LocalDate> getDateOfBirth() { + return Optional.ofNullable(dateOfBirth); + } + + public void setDateOfBirth(LocalDate dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public List getPreferences() { + return preferences; + } + + public void setPreferences(List preferences) { + this.preferences = preferences; + } +} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/bigdecimal/Invoice.java b/javaxval/src/main/java/com/baeldung/javaxval/bigdecimal/Invoice.java similarity index 91% rename from javaxval/src/main/java/org/baeldung/javaxval/bigdecimal/Invoice.java rename to javaxval/src/main/java/com/baeldung/javaxval/bigdecimal/Invoice.java index 087701f166..c14a6bd2b1 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/bigdecimal/Invoice.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/bigdecimal/Invoice.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.bigdecimal; +package com.baeldung.javaxval.bigdecimal; import java.math.BigDecimal; diff --git a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java new file mode 100644 index 0000000000..03811635ee --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java @@ -0,0 +1,66 @@ +package com.baeldung.javaxval.container.validation; + +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.PositiveOrZero; + +public class Customer { + + @NotBlank(message = "Name cannot be empty") + private String name; + + private List<@NotBlank(message = "Address must not be blank") String> addresses; + + private Integer age; + + @PositiveOrZero + private OptionalInt numberOfOrders; + + @NotBlank + private Profile profile; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getAddresses() { + return addresses; + } + + public void setAddresses(List addresses) { + this.addresses = addresses; + } + + public Optional<@Min(18) Integer> getAge() { + return Optional.ofNullable(age); + } + + public void setAge(Integer age) { + this.age = age; + } + + public OptionalInt getNumberOfOrders() { + return numberOfOrders; + } + + public void setNumberOfOrders(OptionalInt numberOfOrders) { + this.numberOfOrders = numberOfOrders; + } + + public Profile getProfile() { + return profile; + } + + public void setProfile(Profile profile) { + this.profile = profile; + } + +} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/container/validation/CustomerMap.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/CustomerMap.java similarity index 89% rename from javaxval/src/main/java/org/baeldung/javaxval/container/validation/CustomerMap.java rename to javaxval/src/main/java/com/baeldung/javaxval/container/validation/CustomerMap.java index 82cf0f2b0c..554285fbae 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/container/validation/CustomerMap.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/CustomerMap.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.container.validation; +package com.baeldung.javaxval.container.validation; import java.util.Map; diff --git a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Profile.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Profile.java new file mode 100644 index 0000000000..252e671250 --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Profile.java @@ -0,0 +1,13 @@ +package com.baeldung.javaxval.container.validation; + +public class Profile { + private String companyName; + + public String getCompanyName() { + return companyName; + } + + public void setCompanyName(String companyName) { + this.companyName = companyName; + } +} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java similarity index 79% rename from javaxval/src/main/java/org/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java rename to javaxval/src/main/java/com/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java index ebc618e80e..03e0c7aac4 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java @@ -1,10 +1,10 @@ -package org.baeldung.javaxval.container.validation.valueextractors; +package com.baeldung.javaxval.container.validation.valueextractors; import javax.validation.valueextraction.ExtractedValue; import javax.validation.valueextraction.UnwrapByDefault; import javax.validation.valueextraction.ValueExtractor; -import org.baeldung.javaxval.container.validation.Profile; +import com.baeldung.javaxval.container.validation.Profile; @UnwrapByDefault public class ProfileValueExtractor implements ValueExtractor<@ExtractedValue(type = String.class) Profile> { diff --git a/javaxval/src/main/java/org/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java similarity index 79% rename from javaxval/src/main/java/org/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java rename to javaxval/src/main/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java index c730cb937f..c91f449bad 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java @@ -1,12 +1,12 @@ -package org.baeldung.javaxval.enums; +package com.baeldung.javaxval.enums; import java.util.Arrays; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import org.baeldung.javaxval.enums.constraints.CustomerTypeSubset; -import org.baeldung.javaxval.enums.demo.CustomerType; +import com.baeldung.javaxval.enums.constraints.CustomerTypeSubset; +import com.baeldung.javaxval.enums.demo.CustomerType; public class CustomerTypeSubSetValidator implements ConstraintValidator { private CustomerType[] subset; diff --git a/javaxval/src/main/java/org/baeldung/javaxval/enums/EnumNamePatternValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumNamePatternValidator.java similarity index 89% rename from javaxval/src/main/java/org/baeldung/javaxval/enums/EnumNamePatternValidator.java rename to javaxval/src/main/java/com/baeldung/javaxval/enums/EnumNamePatternValidator.java index a279813461..3d56d40563 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/enums/EnumNamePatternValidator.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumNamePatternValidator.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.enums; +package com.baeldung.javaxval.enums; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -7,7 +7,7 @@ import java.util.regex.PatternSyntaxException; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import org.baeldung.javaxval.enums.constraints.EnumNamePattern; +import com.baeldung.javaxval.enums.constraints.EnumNamePattern; public class EnumNamePatternValidator implements ConstraintValidator> { private Pattern pattern; diff --git a/javaxval/src/main/java/org/baeldung/javaxval/enums/EnumSubSetValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumSubSetValidator.java similarity index 94% rename from javaxval/src/main/java/org/baeldung/javaxval/enums/EnumSubSetValidator.java rename to javaxval/src/main/java/com/baeldung/javaxval/enums/EnumSubSetValidator.java index 339b4fb03b..04cccb8b0c 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/enums/EnumSubSetValidator.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumSubSetValidator.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.enums; +package com.baeldung.javaxval.enums; import java.lang.annotation.Annotation; import java.util.Arrays; diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/InheritedCustomerTypeSubSetValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/InheritedCustomerTypeSubSetValidator.java new file mode 100644 index 0000000000..b49bc11541 --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/InheritedCustomerTypeSubSetValidator.java @@ -0,0 +1,11 @@ +package com.baeldung.javaxval.enums; + +import com.baeldung.javaxval.enums.constraints.CustomerTypeSubset; +import com.baeldung.javaxval.enums.demo.CustomerType; + +public class InheritedCustomerTypeSubSetValidator extends EnumSubSetValidator { + @Override + public void initialize(CustomerTypeSubset constraint) { + super.initialize(constraint.anyOf()); + } +} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/enums/ValueOfEnumValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/ValueOfEnumValidator.java similarity index 89% rename from javaxval/src/main/java/org/baeldung/javaxval/enums/ValueOfEnumValidator.java rename to javaxval/src/main/java/com/baeldung/javaxval/enums/ValueOfEnumValidator.java index 7184dae49b..0203d63923 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/enums/ValueOfEnumValidator.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/ValueOfEnumValidator.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.enums; +package com.baeldung.javaxval.enums; import java.util.List; import java.util.stream.Collectors; @@ -7,7 +7,7 @@ import java.util.stream.Stream; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import org.baeldung.javaxval.enums.constraints.ValueOfEnum; +import com.baeldung.javaxval.enums.constraints.ValueOfEnum; public class ValueOfEnumValidator implements ConstraintValidator { private List acceptedValues; diff --git a/javaxval/src/main/java/org/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java similarity index 88% rename from javaxval/src/main/java/org/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java rename to javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java index 44009e6723..97c2137f6a 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.enums.constraints; +package com.baeldung.javaxval.enums.constraints; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; @@ -15,8 +15,8 @@ import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; -import org.baeldung.javaxval.enums.CustomerTypeSubSetValidator; -import org.baeldung.javaxval.enums.demo.CustomerType; +import com.baeldung.javaxval.enums.CustomerTypeSubSetValidator; +import com.baeldung.javaxval.enums.demo.CustomerType; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) diff --git a/javaxval/src/main/java/org/baeldung/javaxval/enums/constraints/EnumNamePattern.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/EnumNamePattern.java similarity index 91% rename from javaxval/src/main/java/org/baeldung/javaxval/enums/constraints/EnumNamePattern.java rename to javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/EnumNamePattern.java index 403cdcd0b4..29fff857c8 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/enums/constraints/EnumNamePattern.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/EnumNamePattern.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.enums.constraints; +package com.baeldung.javaxval.enums.constraints; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; @@ -15,7 +15,7 @@ import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; -import org.baeldung.javaxval.enums.EnumNamePatternValidator; +import com.baeldung.javaxval.enums.EnumNamePatternValidator; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) diff --git a/javaxval/src/main/java/org/baeldung/javaxval/enums/constraints/ValueOfEnum.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/ValueOfEnum.java similarity index 92% rename from javaxval/src/main/java/org/baeldung/javaxval/enums/constraints/ValueOfEnum.java rename to javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/ValueOfEnum.java index 0f9677d982..29b44a1793 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/enums/constraints/ValueOfEnum.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/ValueOfEnum.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.enums.constraints; +package com.baeldung.javaxval.enums.constraints; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; @@ -15,7 +15,7 @@ import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; -import org.baeldung.javaxval.enums.ValueOfEnumValidator; +import com.baeldung.javaxval.enums.ValueOfEnumValidator; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/Customer.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/Customer.java new file mode 100644 index 0000000000..15cd9e0da7 --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/Customer.java @@ -0,0 +1,77 @@ +package com.baeldung.javaxval.enums.demo; + +import javax.validation.constraints.NotNull; + +import com.baeldung.javaxval.enums.constraints.CustomerTypeSubset; +import com.baeldung.javaxval.enums.constraints.EnumNamePattern; +import com.baeldung.javaxval.enums.constraints.ValueOfEnum; + +public class Customer { + @ValueOfEnum(enumClass = CustomerType.class) + private String customerTypeString; + + @NotNull + @CustomerTypeSubset(anyOf = { CustomerType.NEW, CustomerType.OLD }) + private CustomerType customerTypeOfSubset; + + @EnumNamePattern(regexp = "NEW|DEFAULT") + private CustomerType customerTypeMatchesPattern; + + public Customer() { + } + + public Customer(String customerTypeString, CustomerType customerTypeOfSubset, CustomerType customerTypeMatchesPattern) { + this.customerTypeString = customerTypeString; + this.customerTypeOfSubset = customerTypeOfSubset; + this.customerTypeMatchesPattern = customerTypeMatchesPattern; + } + + public String getCustomerTypeString() { + return customerTypeString; + } + + public void setCustomerTypeString(String customerTypeString) { + this.customerTypeString = customerTypeString; + } + + public CustomerType getCustomerTypeOfSubset() { + return customerTypeOfSubset; + } + + public void setCustomerTypeOfSubset(CustomerType customerTypeOfSubset) { + this.customerTypeOfSubset = customerTypeOfSubset; + } + + public CustomerType getCustomerTypeMatchesPattern() { + return customerTypeMatchesPattern; + } + + public void setCustomerTypeMatchesPattern(CustomerType customerTypeMatchesPattern) { + this.customerTypeMatchesPattern = customerTypeMatchesPattern; + } + + public static class Builder { + private String customerTypeString; + private CustomerType customerTypeOfSubset = CustomerType.NEW; + private CustomerType customerTypeMatchesPattern; + + public Builder withCustomerTypeString(String customerTypeString) { + this.customerTypeString = customerTypeString; + return this; + } + + public Builder withCustomerTypeOfSubset(CustomerType customerTypeOfSubset) { + this.customerTypeOfSubset = customerTypeOfSubset; + return this; + } + + public Builder withCustomerTypeMatchesPattern(CustomerType customerTypeMatchesPattern) { + this.customerTypeMatchesPattern = customerTypeMatchesPattern; + return this; + } + + public Customer build() { + return new Customer(customerTypeString, customerTypeOfSubset, customerTypeMatchesPattern); + } + } +} diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/CustomerType.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/CustomerType.java new file mode 100644 index 0000000000..88eb1b359f --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/CustomerType.java @@ -0,0 +1,5 @@ +package com.baeldung.javaxval.enums.demo; + +public enum CustomerType { + NEW, OLD, DEFAULT +} diff --git a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/application/Application.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/application/Application.java new file mode 100644 index 0000000000..22157f351c --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/application/Application.java @@ -0,0 +1,18 @@ +package com.baeldung.javaxval.javabeanconstraints.application; + +import javax.validation.Validation; +import javax.validation.Validator; + +import com.baeldung.javaxval.javabeanconstraints.entities.UserNotBlank; + +public class Application { + + public static void main(String[] args) { + Validator validator = Validation.buildDefaultValidatorFactory() + .getValidator(); + UserNotBlank user = new UserNotBlank(" "); + validator.validate(user) + .stream() + .forEach(violation -> System.out.println(violation.getMessage())); + } +} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java similarity index 86% rename from javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java rename to javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java index d86b6a65d2..5542be8c25 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.javabeanconstraints.entities; +package com.baeldung.javaxval.javabeanconstraints.entities; import javax.validation.constraints.NotBlank; diff --git a/javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java similarity index 86% rename from javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java rename to javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java index 2082265145..e3dbe27b0e 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.javabeanconstraints.entities; +package com.baeldung.javaxval.javabeanconstraints.entities; import javax.validation.constraints.NotEmpty; diff --git a/javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java similarity index 86% rename from javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java rename to javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java index e2f9e7ec57..b3a0f90d36 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.javabeanconstraints.entities; +package com.baeldung.javaxval.javabeanconstraints.entities; import javax.validation.constraints.NotNull; diff --git a/javaxval/src/main/java/com/baeldung/javaxval/messageinterpolator/Person.java b/javaxval/src/main/java/com/baeldung/javaxval/messageinterpolator/Person.java new file mode 100644 index 0000000000..387af48c20 --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/messageinterpolator/Person.java @@ -0,0 +1,42 @@ +package com.baeldung.javaxval.messageinterpolator; + +import javax.validation.constraints.Email; +import javax.validation.constraints.Min; +import javax.validation.constraints.Size; + +public class Person { + + @Size(min = 10, max = 100, message = "Name should be between {min} and {max} characters") + private String name; + + @Min(value = 18, message = "Age should not be less than {value}") + private int age; + + @Email(message = "Email address should be in a correct format: ${validatedValue}") + private String email; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/MethodValidationConfig.java b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/MethodValidationConfig.java similarity index 82% rename from javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/MethodValidationConfig.java rename to javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/MethodValidationConfig.java index 817f2370ef..d4046bf5f9 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/MethodValidationConfig.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/MethodValidationConfig.java @@ -1,9 +1,9 @@ -package org.baeldung.javaxval.methodvalidation; +package com.baeldung.javaxval.methodvalidation; import java.time.LocalDate; -import org.baeldung.javaxval.methodvalidation.model.Customer; -import org.baeldung.javaxval.methodvalidation.model.Reservation; +import com.baeldung.javaxval.methodvalidation.model.Customer; +import com.baeldung.javaxval.methodvalidation.model.Reservation; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -12,7 +12,7 @@ import org.springframework.context.annotation.Scope; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; @Configuration -@ComponentScan({ "org.baeldung.javaxval.methodvalidation.model" }) +@ComponentScan({ "com.baeldung.javaxval.methodvalidation.model" }) public class MethodValidationConfig { @Bean diff --git a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameterValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameterValidator.java similarity index 94% rename from javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameterValidator.java rename to javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameterValidator.java index df09cfa906..6b48046b5c 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameterValidator.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameterValidator.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.methodvalidation.constraints; +package com.baeldung.javaxval.methodvalidation.constraints; import java.time.LocalDate; diff --git a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameters.java b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameters.java similarity index 92% rename from javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameters.java rename to javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameters.java index bdfabe05ba..83f551d45f 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameters.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ConsistentDateParameters.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.methodvalidation.constraints; +package com.baeldung.javaxval.methodvalidation.constraints; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.METHOD; diff --git a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ValidReservation.java b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ValidReservation.java similarity index 92% rename from javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ValidReservation.java rename to javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ValidReservation.java index 842f9e0621..c28cc79004 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ValidReservation.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ValidReservation.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.methodvalidation.constraints; +package com.baeldung.javaxval.methodvalidation.constraints; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.METHOD; diff --git a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ValidReservationValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ValidReservationValidator.java similarity index 88% rename from javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ValidReservationValidator.java rename to javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ValidReservationValidator.java index c139d1affc..541fc15e9c 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/constraints/ValidReservationValidator.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/constraints/ValidReservationValidator.java @@ -1,11 +1,11 @@ -package org.baeldung.javaxval.methodvalidation.constraints; +package com.baeldung.javaxval.methodvalidation.constraints; import java.time.LocalDate; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import org.baeldung.javaxval.methodvalidation.model.Reservation; +import com.baeldung.javaxval.methodvalidation.model.Reservation; public class ValidReservationValidator implements ConstraintValidator { diff --git a/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/model/Customer.java b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/model/Customer.java new file mode 100644 index 0000000000..e0b7fcf917 --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/model/Customer.java @@ -0,0 +1,41 @@ +package com.baeldung.javaxval.methodvalidation.model; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +import org.springframework.validation.annotation.Validated; + +@Validated +public class Customer { + + @Size(min = 5, max = 200) + private String firstName; + + @Size(min = 5, max = 200) + private String lastName; + + public Customer(@Size(min = 5, max = 200) @NotNull String firstName, @Size(min = 5, max = 200) @NotNull String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public Customer() { + + } + + 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; + } +} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/model/Reservation.java b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/model/Reservation.java similarity index 86% rename from javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/model/Reservation.java rename to javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/model/Reservation.java index 5775bdd66b..49cf1306a9 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/model/Reservation.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/model/Reservation.java @@ -1,12 +1,12 @@ -package org.baeldung.javaxval.methodvalidation.model; +package com.baeldung.javaxval.methodvalidation.model; import java.time.LocalDate; import javax.validation.Valid; import javax.validation.constraints.Positive; -import org.baeldung.javaxval.methodvalidation.constraints.ConsistentDateParameters; -import org.baeldung.javaxval.methodvalidation.constraints.ValidReservation; +import com.baeldung.javaxval.methodvalidation.constraints.ValidReservation; +import com.baeldung.javaxval.methodvalidation.constraints.ConsistentDateParameters; import org.springframework.validation.annotation.Validated; @Validated diff --git a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/model/ReservationManagement.java b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/model/ReservationManagement.java similarity index 91% rename from javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/model/ReservationManagement.java rename to javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/model/ReservationManagement.java index e480e7912d..41fc4c3840 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/model/ReservationManagement.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/methodvalidation/model/ReservationManagement.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.methodvalidation.model; +package com.baeldung.javaxval.methodvalidation.model; import java.time.LocalDate; import java.util.List; @@ -9,7 +9,7 @@ import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; -import org.baeldung.javaxval.methodvalidation.constraints.ConsistentDateParameters; +import com.baeldung.javaxval.methodvalidation.constraints.ConsistentDateParameters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; diff --git a/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/AdvanceInfo.java b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/AdvanceInfo.java new file mode 100644 index 0000000000..0be96f1341 --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/AdvanceInfo.java @@ -0,0 +1,5 @@ +package com.baeldung.javaxval.validationgroup; + +public interface AdvanceInfo { + +} diff --git a/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/BasicInfo.java b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/BasicInfo.java new file mode 100644 index 0000000000..7413c10cda --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/BasicInfo.java @@ -0,0 +1,5 @@ +package com.baeldung.javaxval.validationgroup; + +public interface BasicInfo { + +} diff --git a/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/CompleteInfo.java b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/CompleteInfo.java new file mode 100644 index 0000000000..4ecdc3c5f1 --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/CompleteInfo.java @@ -0,0 +1,8 @@ +package com.baeldung.javaxval.validationgroup; + +import javax.validation.GroupSequence; + +@GroupSequence({ BasicInfo.class, AdvanceInfo.class }) +public interface CompleteInfo { + +} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/validationgroup/RegistrationForm.java b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/RegistrationForm.java similarity index 98% rename from javaxval/src/main/java/org/baeldung/javaxval/validationgroup/RegistrationForm.java rename to javaxval/src/main/java/com/baeldung/javaxval/validationgroup/RegistrationForm.java index 190a0c1280..a30a074556 100644 --- a/javaxval/src/main/java/org/baeldung/javaxval/validationgroup/RegistrationForm.java +++ b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/RegistrationForm.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.validationgroup; +package com.baeldung.javaxval.validationgroup; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; diff --git a/javaxval/src/main/java/org/baeldung/javaxval/beanvalidation/User.java b/javaxval/src/main/java/org/baeldung/javaxval/beanvalidation/User.java deleted file mode 100644 index 8303edd033..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/beanvalidation/User.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.baeldung.javaxval.beanvalidation; - -import java.time.LocalDate; -import java.util.List; -import java.util.Optional; - -import javax.validation.constraints.AssertTrue; -import javax.validation.constraints.Email; -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Past; -import javax.validation.constraints.Size; - -public class User { - - @NotNull(message = "Name cannot be null") - private String name; - - @AssertTrue - private boolean working; - - @Size(min = 10, max = 200, message = "Number of characters should be in between 10 and 200 inclusive") - private String aboutMe; - - @Min(value = 18, message = "Age should not be less than 18") - @Max(value = 150, message = "Age should not be more than 150") - private int age; - - @Email(message = "Email should be valid") - private String email; - - private List<@NotBlank String> preferences; - - private LocalDate dateOfBirth; - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public boolean isWorking() { - return working; - } - - public void setWorking(boolean working) { - this.working = working; - } - - public String getAboutMe() { - return aboutMe; - } - - public void setAboutMe(String aboutMe) { - this.aboutMe = aboutMe; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Optional<@Past LocalDate> getDateOfBirth() { - return Optional.ofNullable(dateOfBirth); - } - - public void setDateOfBirth(LocalDate dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public List getPreferences() { - return preferences; - } - - public void setPreferences(List preferences) { - this.preferences = preferences; - } -} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/container/validation/Customer.java b/javaxval/src/main/java/org/baeldung/javaxval/container/validation/Customer.java deleted file mode 100644 index 6ca5ba3ee1..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/container/validation/Customer.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.baeldung.javaxval.container.validation; - -import java.util.List; -import java.util.Optional; -import java.util.OptionalInt; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.PositiveOrZero; - -public class Customer { - - @NotBlank(message = "Name cannot be empty") - private String name; - - private List<@NotBlank(message = "Address must not be blank") String> addresses; - - private Integer age; - - @PositiveOrZero - private OptionalInt numberOfOrders; - - @NotBlank - private Profile profile; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getAddresses() { - return addresses; - } - - public void setAddresses(List addresses) { - this.addresses = addresses; - } - - public Optional<@Min(18) Integer> getAge() { - return Optional.ofNullable(age); - } - - public void setAge(Integer age) { - this.age = age; - } - - public OptionalInt getNumberOfOrders() { - return numberOfOrders; - } - - public void setNumberOfOrders(OptionalInt numberOfOrders) { - this.numberOfOrders = numberOfOrders; - } - - public Profile getProfile() { - return profile; - } - - public void setProfile(Profile profile) { - this.profile = profile; - } - -} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/container/validation/Profile.java b/javaxval/src/main/java/org/baeldung/javaxval/container/validation/Profile.java deleted file mode 100644 index 41260540fc..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/container/validation/Profile.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.javaxval.container.validation; - -public class Profile { - private String companyName; - - public String getCompanyName() { - return companyName; - } - - public void setCompanyName(String companyName) { - this.companyName = companyName; - } -} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/enums/InheritedCustomerTypeSubSetValidator.java b/javaxval/src/main/java/org/baeldung/javaxval/enums/InheritedCustomerTypeSubSetValidator.java deleted file mode 100644 index 1cd31c4187..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/enums/InheritedCustomerTypeSubSetValidator.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.baeldung.javaxval.enums; - -import org.baeldung.javaxval.enums.constraints.CustomerTypeSubset; -import org.baeldung.javaxval.enums.demo.CustomerType; - -public class InheritedCustomerTypeSubSetValidator extends EnumSubSetValidator { - @Override - public void initialize(CustomerTypeSubset constraint) { - super.initialize(constraint.anyOf()); - } -} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/enums/demo/Customer.java b/javaxval/src/main/java/org/baeldung/javaxval/enums/demo/Customer.java deleted file mode 100644 index db3486ab5f..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/enums/demo/Customer.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.baeldung.javaxval.enums.demo; - -import javax.validation.constraints.NotNull; - -import org.baeldung.javaxval.enums.constraints.CustomerTypeSubset; -import org.baeldung.javaxval.enums.constraints.EnumNamePattern; -import org.baeldung.javaxval.enums.constraints.ValueOfEnum; - -public class Customer { - @ValueOfEnum(enumClass = CustomerType.class) - private String customerTypeString; - - @NotNull - @CustomerTypeSubset(anyOf = { CustomerType.NEW, CustomerType.OLD }) - private CustomerType customerTypeOfSubset; - - @EnumNamePattern(regexp = "NEW|DEFAULT") - private CustomerType customerTypeMatchesPattern; - - public Customer() { - } - - public Customer(String customerTypeString, CustomerType customerTypeOfSubset, CustomerType customerTypeMatchesPattern) { - this.customerTypeString = customerTypeString; - this.customerTypeOfSubset = customerTypeOfSubset; - this.customerTypeMatchesPattern = customerTypeMatchesPattern; - } - - public String getCustomerTypeString() { - return customerTypeString; - } - - public void setCustomerTypeString(String customerTypeString) { - this.customerTypeString = customerTypeString; - } - - public CustomerType getCustomerTypeOfSubset() { - return customerTypeOfSubset; - } - - public void setCustomerTypeOfSubset(CustomerType customerTypeOfSubset) { - this.customerTypeOfSubset = customerTypeOfSubset; - } - - public CustomerType getCustomerTypeMatchesPattern() { - return customerTypeMatchesPattern; - } - - public void setCustomerTypeMatchesPattern(CustomerType customerTypeMatchesPattern) { - this.customerTypeMatchesPattern = customerTypeMatchesPattern; - } - - public static class Builder { - private String customerTypeString; - private CustomerType customerTypeOfSubset = CustomerType.NEW; - private CustomerType customerTypeMatchesPattern; - - public Builder withCustomerTypeString(String customerTypeString) { - this.customerTypeString = customerTypeString; - return this; - } - - public Builder withCustomerTypeOfSubset(CustomerType customerTypeOfSubset) { - this.customerTypeOfSubset = customerTypeOfSubset; - return this; - } - - public Builder withCustomerTypeMatchesPattern(CustomerType customerTypeMatchesPattern) { - this.customerTypeMatchesPattern = customerTypeMatchesPattern; - return this; - } - - public Customer build() { - return new Customer(customerTypeString, customerTypeOfSubset, customerTypeMatchesPattern); - } - } -} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/enums/demo/CustomerType.java b/javaxval/src/main/java/org/baeldung/javaxval/enums/demo/CustomerType.java deleted file mode 100644 index 937f3a3817..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/enums/demo/CustomerType.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.javaxval.enums.demo; - -public enum CustomerType { - NEW, OLD, DEFAULT -} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/application/Application.java b/javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/application/Application.java deleted file mode 100644 index 22095084c5..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/javabeanconstraints/application/Application.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.javaxval.javabeanconstraints.application; - -import javax.validation.Validation; -import javax.validation.Validator; - -import org.baeldung.javaxval.javabeanconstraints.entities.UserNotBlank; - -public class Application { - - public static void main(String[] args) { - Validator validator = Validation.buildDefaultValidatorFactory() - .getValidator(); - UserNotBlank user = new UserNotBlank(" "); - validator.validate(user) - .stream() - .forEach(violation -> System.out.println(violation.getMessage())); - } -} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/messageinterpolator/Person.java b/javaxval/src/main/java/org/baeldung/javaxval/messageinterpolator/Person.java deleted file mode 100644 index b9fcfdf4d4..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/messageinterpolator/Person.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.javaxval.messageinterpolator; - -import javax.validation.constraints.Email; -import javax.validation.constraints.Min; -import javax.validation.constraints.Size; - -public class Person { - - @Size(min = 10, max = 100, message = "Name should be between {min} and {max} characters") - private String name; - - @Min(value = 18, message = "Age should not be less than {value}") - private int age; - - @Email(message = "Email address should be in a correct format: ${validatedValue}") - private String email; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - -} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/model/Customer.java b/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/model/Customer.java deleted file mode 100644 index 99a32d6277..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/methodvalidation/model/Customer.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.javaxval.methodvalidation.model; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; - -import org.springframework.validation.annotation.Validated; - -@Validated -public class Customer { - - @Size(min = 5, max = 200) - private String firstName; - - @Size(min = 5, max = 200) - private String lastName; - - public Customer(@Size(min = 5, max = 200) @NotNull String firstName, @Size(min = 5, max = 200) @NotNull String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - - public Customer() { - - } - - 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; - } -} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/validationgroup/AdvanceInfo.java b/javaxval/src/main/java/org/baeldung/javaxval/validationgroup/AdvanceInfo.java deleted file mode 100644 index 9a398e9e7e..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/validationgroup/AdvanceInfo.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.javaxval.validationgroup; - -public interface AdvanceInfo { - -} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/validationgroup/BasicInfo.java b/javaxval/src/main/java/org/baeldung/javaxval/validationgroup/BasicInfo.java deleted file mode 100644 index 6959f52bfa..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/validationgroup/BasicInfo.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.javaxval.validationgroup; - -public interface BasicInfo { - -} diff --git a/javaxval/src/main/java/org/baeldung/javaxval/validationgroup/CompleteInfo.java b/javaxval/src/main/java/org/baeldung/javaxval/validationgroup/CompleteInfo.java deleted file mode 100644 index e34f318b5f..0000000000 --- a/javaxval/src/main/java/org/baeldung/javaxval/validationgroup/CompleteInfo.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.javaxval.validationgroup; - -import javax.validation.GroupSequence; - -@GroupSequence({ BasicInfo.class, AdvanceInfo.class }) -public interface CompleteInfo { - -} diff --git a/javaxval/src/main/resources/META-INF/services/javax.validation.valueextraction.ValueExtractor b/javaxval/src/main/resources/META-INF/services/javax.validation.valueextraction.ValueExtractor index 16bacf1097..0c1fcddd9b 100644 --- a/javaxval/src/main/resources/META-INF/services/javax.validation.valueextraction.ValueExtractor +++ b/javaxval/src/main/resources/META-INF/services/javax.validation.valueextraction.ValueExtractor @@ -1 +1 @@ -org.baeldung.javaxval.container.validation.valueextractors.ProfileValueExtractor \ No newline at end of file +com.baeldung.javaxval.container.validation.valueextractors.ProfileValueExtractor \ No newline at end of file diff --git a/javaxval/src/test/java/org/baeldung/javaxval/LocaleAwareUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/LocaleAwareUnitTest.java similarity index 93% rename from javaxval/src/test/java/org/baeldung/javaxval/LocaleAwareUnitTest.java rename to javaxval/src/test/java/com/baeldung/javaxval/LocaleAwareUnitTest.java index 5623b50a72..ebf1ca3dc6 100644 --- a/javaxval/src/test/java/org/baeldung/javaxval/LocaleAwareUnitTest.java +++ b/javaxval/src/test/java/com/baeldung/javaxval/LocaleAwareUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval; +package com.baeldung.javaxval; import java.util.Locale; diff --git a/javaxval/src/test/java/com/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java b/javaxval/src/test/java/com/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java new file mode 100644 index 0000000000..3e60fa7acd --- /dev/null +++ b/javaxval/src/test/java/com/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java @@ -0,0 +1,124 @@ +package com.baeldung.javaxval.beanvalidation; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.junit.Before; +import org.junit.Test; + +public class ValidationIntegrationTest { + + private Validator validator; + + @Before + public void setup() { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + validator = factory.getValidator(); + } + + private User createUser() { + User user = new User(); + user.setName("John"); + user.setWorking(true); + user.setAge(18); + return user; + } + + @Test + public void ifNameIsNull_nameValidationFails() { + User user = new User(); + user.setWorking(true); + user.setAboutMe("Its all about me!!"); + user.setAge(50); + Set> violations = validator.validate(user); + assertEquals(violations.isEmpty(), false); + } + + @Test + public void ifSizeNotInRange_aboutMeValidationFails() { + User user = new User(); + user.setName("MyName"); + user.setAboutMe("Its all about me!!"); + user.setAge(50); + + Set> violations = validator.validate(user); + assertEquals(violations.isEmpty(), false); + } + + @Test + public void ifWorkingIsFalse_workingValidationFails() { + User user = new User(); + user.setName("MyName"); + user.setAboutMe("Its all about me!!"); + user.setAge(50); + + Set> violations = validator.validate(user); + assertEquals(violations.isEmpty(), false); + } + + @Test + public void ifAgeNotRange_ageValidationFails() { + User user = new User(); + user.setName("MyName"); + user.setAboutMe("Its all about me!!"); + user.setAge(8); + + Set> violations = validator.validate(user); + assertEquals(violations.isEmpty(), false); + } + + @Test + public void ifFnameNullAgeNotRangeAndWorkingIsFalse_validationFailsWithThreeErrors() { + User user = new User(); + user.setAboutMe("Its all about me!!"); + user.setAge(300); + + Set> violations = validator.validate(user); + assertEquals(violations.isEmpty(), false); + assertEquals(violations.size(), 3); + } + + @Test + public void givenInvalidEmail_thenValidationFails() { + User user = createUser(); + user.setEmail("john"); + + Set> violations = validator.validate(user); + assertEquals(1, violations.size()); + } + + @Test + public void givenBlankPreference_thenValidationFails() { + User user = createUser(); + user.setPreferences(Collections.singletonList(" ")); + + Set> violations = validator.validate(user); + assertEquals(1, violations.size()); + } + + @Test + public void givenEmptyOptional_thenValidationSucceeds() { + User user = createUser(); + + Set> violations = validator.validate(user); + assertEquals(0, violations.size()); + } + + @Test + public void givenPastDateOfBirth_thenValidationSuccess() { + User user = createUser(); + user.setDateOfBirth(LocalDate.of(1980, 5, 20)); + + Set> violations = validator.validate(user); + assertEquals(0, violations.size()); + + } +} diff --git a/javaxval/src/test/java/org/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java similarity index 96% rename from javaxval/src/test/java/org/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java rename to javaxval/src/test/java/com/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java index 6a53d67f30..2df0cf81af 100644 --- a/javaxval/src/test/java/org/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java +++ b/javaxval/src/test/java/com/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.bigdecimal; +package com.baeldung.javaxval.bigdecimal; import static org.assertj.core.api.Assertions.assertThat; @@ -9,7 +9,7 @@ import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; -import org.baeldung.javaxval.LocaleAwareUnitTest; +import com.baeldung.javaxval.LocaleAwareUnitTest; import org.junit.BeforeClass; import org.junit.Test; diff --git a/javaxval/src/test/java/com/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java b/javaxval/src/test/java/com/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java new file mode 100644 index 0000000000..d96b641442 --- /dev/null +++ b/javaxval/src/test/java/com/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java @@ -0,0 +1,90 @@ +package com.baeldung.javaxval.container.validation; + +import static org.junit.Assert.assertEquals; + +import java.util.Collections; +import java.util.OptionalInt; +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import com.baeldung.javaxval.container.validation.valueextractors.ProfileValueExtractor; +import org.junit.Before; +import org.junit.Test; + +public class ContainerValidationIntegrationTest { + private Validator validator; + + @Before + public void setup() { + ValidatorFactory factory = Validation.byDefaultProvider() + .configure() + .addValueExtractor(new ProfileValueExtractor()) + .buildValidatorFactory(); + validator = factory.getValidator(); + } + + @Test + public void whenEmptyAddress_thenValidationFails() { + Customer customer = new Customer(); + customer.setName("John"); + customer.setAddresses(Collections.singletonList(" ")); + Set> violations = validator.validate(customer); + assertEquals(1, violations.size()); + assertEquals("Address must not be blank", violations.iterator() + .next() + .getMessage()); + } + + @Test + public void whenInvalidEmail_thenValidationFails() { + CustomerMap map = new CustomerMap(); + map.setCustomers(Collections.singletonMap("john", new Customer())); + Set> violations = validator.validate(map); + assertEquals(1, violations.size()); + assertEquals("Must be a valid email", violations.iterator() + .next() + .getMessage()); + } + + @Test + public void whenAgeTooLow_thenValidationFails() { + Customer customer = new Customer(); + customer.setName("John"); + customer.setAge(15); + Set> violations = validator.validate(customer); + assertEquals(1, violations.size()); + } + + @Test + public void whenAgeNull_thenValidationSucceeds() { + Customer customer = new Customer(); + customer.setName("John"); + Set> violations = validator.validate(customer); + assertEquals(0, violations.size()); + } + + @Test + public void whenNumberOrdersValid_thenValidationSucceeds() { + Customer customer = new Customer(); + customer.setName("John"); + customer.setNumberOfOrders(OptionalInt.of(1)); + Set> violations = validator.validate(customer); + assertEquals(0, violations.size()); + } + + @Test + public void whenProfileCompanyNameBlank_thenValidationFails() { + Customer customer = new Customer(); + customer.setName("John"); + Profile profile = new Profile(); + profile.setCompanyName(" "); + customer.setProfile(profile); + Set> violations = validator.validate(customer); + assertEquals(1, violations.size()); + } + +} diff --git a/javaxval/src/test/java/org/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java similarity index 87% rename from javaxval/src/test/java/org/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java rename to javaxval/src/test/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java index 5aae504b23..08a51de81e 100644 --- a/javaxval/src/test/java/org/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java +++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.enums; +package com.baeldung.javaxval.enums; import static org.assertj.core.api.Assertions.assertThat; @@ -8,9 +8,9 @@ import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; -import org.baeldung.javaxval.enums.demo.Customer; -import org.baeldung.javaxval.enums.demo.CustomerType; -import org.baeldung.javaxval.enums.demo.CustomerUnitTest; +import com.baeldung.javaxval.enums.demo.CustomerUnitTest; +import com.baeldung.javaxval.enums.demo.Customer; +import com.baeldung.javaxval.enums.demo.CustomerType; import org.junit.BeforeClass; import org.junit.Test; diff --git a/javaxval/src/test/java/org/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java similarity index 86% rename from javaxval/src/test/java/org/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java rename to javaxval/src/test/java/com/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java index 48f7de2c34..03bb1f73ba 100644 --- a/javaxval/src/test/java/org/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java +++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java @@ -1,8 +1,8 @@ -package org.baeldung.javaxval.enums; +package com.baeldung.javaxval.enums; import static org.assertj.core.api.Assertions.assertThat; -import static org.baeldung.javaxval.enums.demo.CustomerType.DEFAULT; -import static org.baeldung.javaxval.enums.demo.CustomerType.OLD; +import static com.baeldung.javaxval.enums.demo.CustomerType.DEFAULT; +import static com.baeldung.javaxval.enums.demo.CustomerType.OLD; import java.util.Set; @@ -10,8 +10,8 @@ import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; -import org.baeldung.javaxval.enums.demo.Customer; -import org.baeldung.javaxval.enums.demo.CustomerUnitTest; +import com.baeldung.javaxval.enums.demo.CustomerUnitTest; +import com.baeldung.javaxval.enums.demo.Customer; import org.junit.BeforeClass; import org.junit.Test; diff --git a/javaxval/src/test/java/org/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java similarity index 89% rename from javaxval/src/test/java/org/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java rename to javaxval/src/test/java/com/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java index 0784b58b77..723ac3cc32 100644 --- a/javaxval/src/test/java/org/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java +++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.enums; +package com.baeldung.javaxval.enums; import static org.assertj.core.api.Assertions.assertThat; @@ -8,8 +8,8 @@ import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; -import org.baeldung.javaxval.enums.demo.Customer; -import org.baeldung.javaxval.enums.demo.CustomerUnitTest; +import com.baeldung.javaxval.enums.demo.CustomerUnitTest; +import com.baeldung.javaxval.enums.demo.Customer; import org.junit.BeforeClass; import org.junit.Test; @@ -47,6 +47,6 @@ public class ValueOfEnumValidatorUnitTest { assertThat(violations.size()).isEqualTo(1); assertThat(violations).anyMatch(CustomerUnitTest.havingPropertyPath("customerTypeString") - .and(CustomerUnitTest.havingMessage("must be any of enum class org.baeldung.javaxval.enums.demo.CustomerType"))); + .and(CustomerUnitTest.havingMessage("must be any of enum class com.baeldung.javaxval.enums.demo.CustomerType"))); } } \ No newline at end of file diff --git a/javaxval/src/test/java/org/baeldung/javaxval/enums/demo/CustomerUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/demo/CustomerUnitTest.java similarity index 92% rename from javaxval/src/test/java/org/baeldung/javaxval/enums/demo/CustomerUnitTest.java rename to javaxval/src/test/java/com/baeldung/javaxval/enums/demo/CustomerUnitTest.java index 6a064b640f..2c810bc2fe 100644 --- a/javaxval/src/test/java/org/baeldung/javaxval/enums/demo/CustomerUnitTest.java +++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/demo/CustomerUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.enums.demo; +package com.baeldung.javaxval.enums.demo; import static org.assertj.core.api.Assertions.assertThat; @@ -9,7 +9,7 @@ import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; -import org.baeldung.javaxval.LocaleAwareUnitTest; +import com.baeldung.javaxval.LocaleAwareUnitTest; import org.junit.BeforeClass; import org.junit.Test; @@ -50,7 +50,7 @@ public class CustomerUnitTest extends LocaleAwareUnitTest { Set> violations = validator.validate(customer); assertThat(violations.size()).isEqualTo(3); - assertThat(violations).anyMatch(havingPropertyPath("customerTypeString").and(havingMessage("must be any of enum class org.baeldung.javaxval.enums.demo.CustomerType"))); + assertThat(violations).anyMatch(havingPropertyPath("customerTypeString").and(havingMessage("must be any of enum class com.baeldung.javaxval.enums.demo.CustomerType"))); assertThat(violations).anyMatch(havingPropertyPath("customerTypeOfSubset").and(havingMessage("must be any of [NEW, OLD]"))); assertThat(violations).anyMatch(havingPropertyPath("customerTypeMatchesPattern").and(havingMessage("must match \"NEW|DEFAULT\""))); } diff --git a/javaxval/src/test/java/org/baeldung/javaxval/javabeanconstraints/test/UserNotBlankUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/test/UserNotBlankUnitTest.java similarity index 93% rename from javaxval/src/test/java/org/baeldung/javaxval/javabeanconstraints/test/UserNotBlankUnitTest.java rename to javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/test/UserNotBlankUnitTest.java index e3a51d4e27..5219004c6d 100644 --- a/javaxval/src/test/java/org/baeldung/javaxval/javabeanconstraints/test/UserNotBlankUnitTest.java +++ b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/test/UserNotBlankUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.javabeanconstraints.test; +package com.baeldung.javaxval.javabeanconstraints.test; import static org.assertj.core.api.Assertions.assertThat; @@ -8,7 +8,7 @@ import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; -import org.baeldung.javaxval.javabeanconstraints.entities.UserNotBlank; +import com.baeldung.javaxval.javabeanconstraints.entities.UserNotBlank; import org.junit.BeforeClass; import org.junit.Test; diff --git a/javaxval/src/test/java/org/baeldung/javaxval/javabeanconstraints/test/UserNotEmptyUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/test/UserNotEmptyUnitTest.java similarity index 92% rename from javaxval/src/test/java/org/baeldung/javaxval/javabeanconstraints/test/UserNotEmptyUnitTest.java rename to javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/test/UserNotEmptyUnitTest.java index 22fbab6997..7017848756 100644 --- a/javaxval/src/test/java/org/baeldung/javaxval/javabeanconstraints/test/UserNotEmptyUnitTest.java +++ b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/test/UserNotEmptyUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.javabeanconstraints.test; +package com.baeldung.javaxval.javabeanconstraints.test; import static org.assertj.core.api.Assertions.assertThat; @@ -8,7 +8,7 @@ import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; -import org.baeldung.javaxval.javabeanconstraints.entities.UserNotEmpty; +import com.baeldung.javaxval.javabeanconstraints.entities.UserNotEmpty; import org.junit.BeforeClass; import org.junit.Test; diff --git a/javaxval/src/test/java/org/baeldung/javaxval/javabeanconstraints/test/UserNotNullUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/test/UserNotNullUnitTest.java similarity index 92% rename from javaxval/src/test/java/org/baeldung/javaxval/javabeanconstraints/test/UserNotNullUnitTest.java rename to javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/test/UserNotNullUnitTest.java index a684668ae3..b0df88d72b 100644 --- a/javaxval/src/test/java/org/baeldung/javaxval/javabeanconstraints/test/UserNotNullUnitTest.java +++ b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/test/UserNotNullUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.javabeanconstraints.test; +package com.baeldung.javaxval.javabeanconstraints.test; import static org.assertj.core.api.Assertions.assertThat; @@ -8,7 +8,7 @@ import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; -import org.baeldung.javaxval.javabeanconstraints.entities.UserNotNull; +import com.baeldung.javaxval.javabeanconstraints.entities.UserNotNull; import org.junit.BeforeClass; import org.junit.Test; diff --git a/javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java b/javaxval/src/test/java/com/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java similarity index 97% rename from javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java rename to javaxval/src/test/java/com/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java index 6ecb916ab4..a60550aca5 100644 --- a/javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java +++ b/javaxval/src/test/java/com/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.messageinterpolator; +package com.baeldung.javaxval.messageinterpolator; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/javaxval/src/test/java/com/baeldung/javaxval/methodvalidation/ContainerValidationIntegrationTest.java b/javaxval/src/test/java/com/baeldung/javaxval/methodvalidation/ContainerValidationIntegrationTest.java new file mode 100644 index 0000000000..d9daf6c4ff --- /dev/null +++ b/javaxval/src/test/java/com/baeldung/javaxval/methodvalidation/ContainerValidationIntegrationTest.java @@ -0,0 +1,98 @@ +package com.baeldung.javaxval.methodvalidation; + +import java.time.LocalDate; +import java.util.List; + +import javax.validation.ConstraintViolationException; + +import com.baeldung.javaxval.methodvalidation.model.Customer; +import com.baeldung.javaxval.methodvalidation.model.Reservation; +import com.baeldung.javaxval.methodvalidation.model.ReservationManagement; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MethodValidationConfig.class }, loader = AnnotationConfigContextLoader.class) +public class ContainerValidationIntegrationTest { + + @Autowired + ReservationManagement reservationManagement; + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Test + public void whenValidationWithInvalidMethodParameters_thenConstraintViolationException() { + + exception.expect(ConstraintViolationException.class); + reservationManagement.createReservation(LocalDate.now(), 0, null); + } + + @Test + public void whenValidationWithValidMethodParameters_thenNoException() { + + reservationManagement.createReservation(LocalDate.now() + .plusDays(1), 1, new Customer("William", "Smith")); + } + + @Test + public void whenCrossParameterValidationWithInvalidParameters_thenConstraintViolationException() { + + exception.expect(ConstraintViolationException.class); + reservationManagement.createReservation(LocalDate.now(), LocalDate.now(), null); + } + + @Test + public void whenCrossParameterValidationWithValidParameters_thenNoException() { + + reservationManagement.createReservation(LocalDate.now() + .plusDays(1), + LocalDate.now() + .plusDays(2), + new Customer("William", "Smith")); + } + + @Test + public void whenValidationWithInvalidReturnValue_thenConstraintViolationException() { + + exception.expect(ConstraintViolationException.class); + List list = reservationManagement.getAllCustomers(); + } + + @Test + public void whenValidationWithInvalidCascadedValue_thenConstraintViolationException() { + + Customer customer = new Customer(); + customer.setFirstName("John"); + customer.setLastName("Doe"); + Reservation reservation = new Reservation(LocalDate.now() + .plusDays(1), + LocalDate.now() + .plusDays(2), + customer, 1); + + exception.expect(ConstraintViolationException.class); + reservationManagement.createReservation(reservation); + } + + @Test + public void whenValidationWithValidCascadedValue_thenCNoException() { + + Customer customer = new Customer(); + customer.setFirstName("William"); + customer.setLastName("Smith"); + Reservation reservation = new Reservation(LocalDate.now() + .plusDays(1), + LocalDate.now() + .plusDays(2), + customer, 1); + + reservationManagement.createReservation(reservation); + } +} diff --git a/javaxval/src/test/java/com/baeldung/javaxval/methodvalidation/ValidationIntegrationTest.java b/javaxval/src/test/java/com/baeldung/javaxval/methodvalidation/ValidationIntegrationTest.java new file mode 100644 index 0000000000..6f297a7c9c --- /dev/null +++ b/javaxval/src/test/java/com/baeldung/javaxval/methodvalidation/ValidationIntegrationTest.java @@ -0,0 +1,211 @@ +package com.baeldung.javaxval.methodvalidation; + +import static org.junit.Assert.assertEquals; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.time.LocalDate; +import java.util.Collections; +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.ValidatorFactory; +import javax.validation.executable.ExecutableValidator; + +import com.baeldung.javaxval.methodvalidation.model.Customer; +import com.baeldung.javaxval.methodvalidation.model.Reservation; +import com.baeldung.javaxval.methodvalidation.model.ReservationManagement; +import org.junit.Before; +import org.junit.Test; + +public class ValidationIntegrationTest { + + private ExecutableValidator executableValidator; + + @Before + public void getExecutableValidator() { + + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + this.executableValidator = factory.getValidator() + .forExecutables(); + } + + @Test + public void whenValidationWithInvalidMethodParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException { + + ReservationManagement object = new ReservationManagement(); + Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, int.class, Customer.class); + Object[] parameterValues = { LocalDate.now(), 0, null }; + Set> violations = executableValidator.validateParameters(object, method, parameterValues); + + assertEquals(3, violations.size()); + } + + @Test + public void whenValidationWithValidMethodParameters_thenZeroVoilations() throws NoSuchMethodException { + + ReservationManagement object = new ReservationManagement(); + Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, int.class, Customer.class); + Object[] parameterValues = { LocalDate.now() + .plusDays(1), 1, new Customer("John", "Doe") }; + Set> violations = executableValidator.validateParameters(object, method, parameterValues); + + assertEquals(0, violations.size()); + } + + @Test + public void whenCrossParameterValidationWithInvalidParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException { + + ReservationManagement object = new ReservationManagement(); + Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, LocalDate.class, Customer.class); + Object[] parameterValues = { LocalDate.now(), LocalDate.now(), new Customer("John", "Doe") }; + Set> violations = executableValidator.validateParameters(object, method, parameterValues); + + assertEquals(1, violations.size()); + } + + @Test + public void whenCrossParameterValidationWithValidParameters_thenZeroVoilations() throws NoSuchMethodException { + + ReservationManagement object = new ReservationManagement(); + Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, LocalDate.class, Customer.class); + Object[] parameterValues = { LocalDate.now() + .plusDays(1), + LocalDate.now() + .plusDays(2), + new Customer("John", "Doe") }; + Set> violations = executableValidator.validateParameters(object, method, parameterValues); + + assertEquals(0, violations.size()); + } + + @Test + public void whenValidationWithInvalidConstructorParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException { + + Constructor constructor = Customer.class.getConstructor(String.class, String.class); + Object[] parameterValues = { "John", "Doe" }; + Set> violations = executableValidator.validateConstructorParameters(constructor, parameterValues); + + assertEquals(2, violations.size()); + } + + @Test + public void whenValidationWithValidConstructorParameters_thenZeroVoilations() throws NoSuchMethodException { + + Constructor constructor = Customer.class.getConstructor(String.class, String.class); + Object[] parameterValues = { "William", "Smith" }; + Set> violations = executableValidator.validateConstructorParameters(constructor, parameterValues); + + assertEquals(0, violations.size()); + } + + @Test + public void whenCrossParameterValidationWithInvalidConstructorParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException { + + Constructor constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class); + Object[] parameterValues = { LocalDate.now(), LocalDate.now(), new Customer("William", "Smith"), 1 }; + Set> violations = executableValidator.validateConstructorParameters(constructor, parameterValues); + + assertEquals(1, violations.size()); + } + + @Test + public void whenCrossParameterValidationWithValidConstructorParameters_thenZeroVoilations() throws NoSuchMethodException { + + Constructor constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class); + Object[] parameterValues = { LocalDate.now() + .plusDays(1), + LocalDate.now() + .plusDays(2), + new Customer("William", "Smith"), 1 }; + Set> violations = executableValidator.validateConstructorParameters(constructor, parameterValues); + + assertEquals(0, violations.size()); + } + + @Test + public void whenValidationWithInvalidReturnValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException { + + ReservationManagement object = new ReservationManagement(); + Method method = ReservationManagement.class.getMethod("getAllCustomers"); + Object returnValue = Collections. emptyList(); + Set> violations = executableValidator.validateReturnValue(object, method, returnValue); + + assertEquals(1, violations.size()); + } + + @Test + public void whenValidationWithValidReturnValue_thenZeroVoilations() throws NoSuchMethodException { + + ReservationManagement object = new ReservationManagement(); + Method method = ReservationManagement.class.getMethod("getAllCustomers"); + Object returnValue = Collections.singletonList(new Customer("William", "Smith")); + Set> violations = executableValidator.validateReturnValue(object, method, returnValue); + + assertEquals(0, violations.size()); + } + + @Test + public void whenValidationWithInvalidConstructorReturnValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException { + + Constructor constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class); + Reservation createdObject = new Reservation(LocalDate.now(), LocalDate.now(), new Customer("William", "Smith"), 0); + Set> violations = executableValidator.validateConstructorReturnValue(constructor, createdObject); + + assertEquals(1, violations.size()); + } + + @Test + public void whenValidationWithValidConstructorReturnValue_thenZeroVoilations() throws NoSuchMethodException { + + Constructor constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class); + Reservation createdObject = new Reservation(LocalDate.now() + .plusDays(1), + LocalDate.now() + .plusDays(2), + new Customer("William", "Smith"), 1); + Set> violations = executableValidator.validateConstructorReturnValue(constructor, createdObject); + + assertEquals(0, violations.size()); + } + + @Test + public void whenValidationWithInvalidCascadedValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException { + + ReservationManagement object = new ReservationManagement(); + Method method = ReservationManagement.class.getMethod("createReservation", Reservation.class); + Customer customer = new Customer(); + customer.setFirstName("John"); + customer.setLastName("Doe"); + Reservation reservation = new Reservation(LocalDate.now() + .plusDays(1), + LocalDate.now() + .plusDays(2), + customer, 1); + Object[] parameterValues = { reservation }; + Set> violations = executableValidator.validateParameters(object, method, parameterValues); + + assertEquals(2, violations.size()); + } + + @Test + public void whenValidationWithValidCascadedValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException { + + ReservationManagement object = new ReservationManagement(); + Method method = ReservationManagement.class.getMethod("createReservation", Reservation.class); + Customer customer = new Customer(); + customer.setFirstName("William"); + customer.setLastName("Smith"); + Reservation reservation = new Reservation(LocalDate.now() + .plusDays(1), + LocalDate.now() + .plusDays(2), + customer, 1); + Object[] parameterValues = { reservation }; + Set> violations = executableValidator.validateParameters(object, method, parameterValues); + + assertEquals(0, violations.size()); + } + +} diff --git a/javaxval/src/test/java/org/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java similarity index 98% rename from javaxval/src/test/java/org/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java rename to javaxval/src/test/java/com/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java index df70ca0bce..6b7600d201 100644 --- a/javaxval/src/test/java/org/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java +++ b/javaxval/src/test/java/com/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.javaxval.validationgroup; +package com.baeldung.javaxval.validationgroup; import static org.assertj.core.api.Assertions.assertThat; @@ -8,7 +8,7 @@ import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; -import org.baeldung.javaxval.LocaleAwareUnitTest; +import com.baeldung.javaxval.LocaleAwareUnitTest; import org.junit.BeforeClass; import org.junit.Test; diff --git a/javaxval/src/test/java/org/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java b/javaxval/src/test/java/org/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java deleted file mode 100644 index 3d54955177..0000000000 --- a/javaxval/src/test/java/org/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.baeldung.javaxval.beanvalidation; - -import static org.junit.Assert.assertEquals; - -import java.time.LocalDate; -import java.util.Collections; -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; - -import org.junit.Before; -import org.junit.Test; - -public class ValidationIntegrationTest { - - private Validator validator; - - @Before - public void setup() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - validator = factory.getValidator(); - } - - private User createUser() { - User user = new User(); - user.setName("John"); - user.setWorking(true); - user.setAge(18); - return user; - } - - @Test - public void ifNameIsNull_nameValidationFails() { - User user = new User(); - user.setWorking(true); - user.setAboutMe("Its all about me!!"); - user.setAge(50); - Set> violations = validator.validate(user); - assertEquals(violations.isEmpty(), false); - } - - @Test - public void ifSizeNotInRange_aboutMeValidationFails() { - User user = new User(); - user.setName("MyName"); - user.setAboutMe("Its all about me!!"); - user.setAge(50); - - Set> violations = validator.validate(user); - assertEquals(violations.isEmpty(), false); - } - - @Test - public void ifWorkingIsFalse_workingValidationFails() { - User user = new User(); - user.setName("MyName"); - user.setAboutMe("Its all about me!!"); - user.setAge(50); - - Set> violations = validator.validate(user); - assertEquals(violations.isEmpty(), false); - } - - @Test - public void ifAgeNotRange_ageValidationFails() { - User user = new User(); - user.setName("MyName"); - user.setAboutMe("Its all about me!!"); - user.setAge(8); - - Set> violations = validator.validate(user); - assertEquals(violations.isEmpty(), false); - } - - @Test - public void ifFnameNullAgeNotRangeAndWorkingIsFalse_validationFailsWithThreeErrors() { - User user = new User(); - user.setAboutMe("Its all about me!!"); - user.setAge(300); - - Set> violations = validator.validate(user); - assertEquals(violations.isEmpty(), false); - assertEquals(violations.size(), 3); - } - - @Test - public void givenInvalidEmail_thenValidationFails() { - User user = createUser(); - user.setEmail("john"); - - Set> violations = validator.validate(user); - assertEquals(1, violations.size()); - } - - @Test - public void givenBlankPreference_thenValidationFails() { - User user = createUser(); - user.setPreferences(Collections.singletonList(" ")); - - Set> violations = validator.validate(user); - assertEquals(1, violations.size()); - } - - @Test - public void givenEmptyOptional_thenValidationSucceeds() { - User user = createUser(); - - Set> violations = validator.validate(user); - assertEquals(0, violations.size()); - } - - @Test - public void givenPastDateOfBirth_thenValidationSuccess() { - User user = createUser(); - user.setDateOfBirth(LocalDate.of(1980, 5, 20)); - - Set> violations = validator.validate(user); - assertEquals(0, violations.size()); - - } -} diff --git a/javaxval/src/test/java/org/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java b/javaxval/src/test/java/org/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java deleted file mode 100644 index 25c8111732..0000000000 --- a/javaxval/src/test/java/org/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.baeldung.javaxval.container.validation; - -import static org.junit.Assert.assertEquals; - -import java.util.Collections; -import java.util.OptionalInt; -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; - -import org.baeldung.javaxval.container.validation.valueextractors.ProfileValueExtractor; -import org.junit.Before; -import org.junit.Test; - -public class ContainerValidationIntegrationTest { - private Validator validator; - - @Before - public void setup() { - ValidatorFactory factory = Validation.byDefaultProvider() - .configure() - .addValueExtractor(new ProfileValueExtractor()) - .buildValidatorFactory(); - validator = factory.getValidator(); - } - - @Test - public void whenEmptyAddress_thenValidationFails() { - Customer customer = new Customer(); - customer.setName("John"); - customer.setAddresses(Collections.singletonList(" ")); - Set> violations = validator.validate(customer); - assertEquals(1, violations.size()); - assertEquals("Address must not be blank", violations.iterator() - .next() - .getMessage()); - } - - @Test - public void whenInvalidEmail_thenValidationFails() { - CustomerMap map = new CustomerMap(); - map.setCustomers(Collections.singletonMap("john", new Customer())); - Set> violations = validator.validate(map); - assertEquals(1, violations.size()); - assertEquals("Must be a valid email", violations.iterator() - .next() - .getMessage()); - } - - @Test - public void whenAgeTooLow_thenValidationFails() { - Customer customer = new Customer(); - customer.setName("John"); - customer.setAge(15); - Set> violations = validator.validate(customer); - assertEquals(1, violations.size()); - } - - @Test - public void whenAgeNull_thenValidationSucceeds() { - Customer customer = new Customer(); - customer.setName("John"); - Set> violations = validator.validate(customer); - assertEquals(0, violations.size()); - } - - @Test - public void whenNumberOrdersValid_thenValidationSucceeds() { - Customer customer = new Customer(); - customer.setName("John"); - customer.setNumberOfOrders(OptionalInt.of(1)); - Set> violations = validator.validate(customer); - assertEquals(0, violations.size()); - } - - @Test - public void whenProfileCompanyNameBlank_thenValidationFails() { - Customer customer = new Customer(); - customer.setName("John"); - Profile profile = new Profile(); - profile.setCompanyName(" "); - customer.setProfile(profile); - Set> violations = validator.validate(customer); - assertEquals(1, violations.size()); - } - -} diff --git a/javaxval/src/test/java/org/baeldung/javaxval/methodvalidation/ContainerValidationIntegrationTest.java b/javaxval/src/test/java/org/baeldung/javaxval/methodvalidation/ContainerValidationIntegrationTest.java deleted file mode 100644 index 8febdca0ee..0000000000 --- a/javaxval/src/test/java/org/baeldung/javaxval/methodvalidation/ContainerValidationIntegrationTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.baeldung.javaxval.methodvalidation; - -import java.time.LocalDate; -import java.util.List; - -import javax.validation.ConstraintViolationException; - -import org.baeldung.javaxval.methodvalidation.model.Customer; -import org.baeldung.javaxval.methodvalidation.model.Reservation; -import org.baeldung.javaxval.methodvalidation.model.ReservationManagement; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MethodValidationConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ContainerValidationIntegrationTest { - - @Autowired - ReservationManagement reservationManagement; - - @Rule - public final ExpectedException exception = ExpectedException.none(); - - @Test - public void whenValidationWithInvalidMethodParameters_thenConstraintViolationException() { - - exception.expect(ConstraintViolationException.class); - reservationManagement.createReservation(LocalDate.now(), 0, null); - } - - @Test - public void whenValidationWithValidMethodParameters_thenNoException() { - - reservationManagement.createReservation(LocalDate.now() - .plusDays(1), 1, new Customer("William", "Smith")); - } - - @Test - public void whenCrossParameterValidationWithInvalidParameters_thenConstraintViolationException() { - - exception.expect(ConstraintViolationException.class); - reservationManagement.createReservation(LocalDate.now(), LocalDate.now(), null); - } - - @Test - public void whenCrossParameterValidationWithValidParameters_thenNoException() { - - reservationManagement.createReservation(LocalDate.now() - .plusDays(1), - LocalDate.now() - .plusDays(2), - new Customer("William", "Smith")); - } - - @Test - public void whenValidationWithInvalidReturnValue_thenConstraintViolationException() { - - exception.expect(ConstraintViolationException.class); - List list = reservationManagement.getAllCustomers(); - } - - @Test - public void whenValidationWithInvalidCascadedValue_thenConstraintViolationException() { - - Customer customer = new Customer(); - customer.setFirstName("John"); - customer.setLastName("Doe"); - Reservation reservation = new Reservation(LocalDate.now() - .plusDays(1), - LocalDate.now() - .plusDays(2), - customer, 1); - - exception.expect(ConstraintViolationException.class); - reservationManagement.createReservation(reservation); - } - - @Test - public void whenValidationWithValidCascadedValue_thenCNoException() { - - Customer customer = new Customer(); - customer.setFirstName("William"); - customer.setLastName("Smith"); - Reservation reservation = new Reservation(LocalDate.now() - .plusDays(1), - LocalDate.now() - .plusDays(2), - customer, 1); - - reservationManagement.createReservation(reservation); - } -} diff --git a/javaxval/src/test/java/org/baeldung/javaxval/methodvalidation/ValidationIntegrationTest.java b/javaxval/src/test/java/org/baeldung/javaxval/methodvalidation/ValidationIntegrationTest.java deleted file mode 100644 index 9baeba7189..0000000000 --- a/javaxval/src/test/java/org/baeldung/javaxval/methodvalidation/ValidationIntegrationTest.java +++ /dev/null @@ -1,211 +0,0 @@ -package org.baeldung.javaxval.methodvalidation; - -import static org.junit.Assert.assertEquals; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.time.LocalDate; -import java.util.Collections; -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.ValidatorFactory; -import javax.validation.executable.ExecutableValidator; - -import org.baeldung.javaxval.methodvalidation.model.Customer; -import org.baeldung.javaxval.methodvalidation.model.Reservation; -import org.baeldung.javaxval.methodvalidation.model.ReservationManagement; -import org.junit.Before; -import org.junit.Test; - -public class ValidationIntegrationTest { - - private ExecutableValidator executableValidator; - - @Before - public void getExecutableValidator() { - - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - this.executableValidator = factory.getValidator() - .forExecutables(); - } - - @Test - public void whenValidationWithInvalidMethodParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException { - - ReservationManagement object = new ReservationManagement(); - Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, int.class, Customer.class); - Object[] parameterValues = { LocalDate.now(), 0, null }; - Set> violations = executableValidator.validateParameters(object, method, parameterValues); - - assertEquals(3, violations.size()); - } - - @Test - public void whenValidationWithValidMethodParameters_thenZeroVoilations() throws NoSuchMethodException { - - ReservationManagement object = new ReservationManagement(); - Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, int.class, Customer.class); - Object[] parameterValues = { LocalDate.now() - .plusDays(1), 1, new Customer("John", "Doe") }; - Set> violations = executableValidator.validateParameters(object, method, parameterValues); - - assertEquals(0, violations.size()); - } - - @Test - public void whenCrossParameterValidationWithInvalidParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException { - - ReservationManagement object = new ReservationManagement(); - Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, LocalDate.class, Customer.class); - Object[] parameterValues = { LocalDate.now(), LocalDate.now(), new Customer("John", "Doe") }; - Set> violations = executableValidator.validateParameters(object, method, parameterValues); - - assertEquals(1, violations.size()); - } - - @Test - public void whenCrossParameterValidationWithValidParameters_thenZeroVoilations() throws NoSuchMethodException { - - ReservationManagement object = new ReservationManagement(); - Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, LocalDate.class, Customer.class); - Object[] parameterValues = { LocalDate.now() - .plusDays(1), - LocalDate.now() - .plusDays(2), - new Customer("John", "Doe") }; - Set> violations = executableValidator.validateParameters(object, method, parameterValues); - - assertEquals(0, violations.size()); - } - - @Test - public void whenValidationWithInvalidConstructorParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException { - - Constructor constructor = Customer.class.getConstructor(String.class, String.class); - Object[] parameterValues = { "John", "Doe" }; - Set> violations = executableValidator.validateConstructorParameters(constructor, parameterValues); - - assertEquals(2, violations.size()); - } - - @Test - public void whenValidationWithValidConstructorParameters_thenZeroVoilations() throws NoSuchMethodException { - - Constructor constructor = Customer.class.getConstructor(String.class, String.class); - Object[] parameterValues = { "William", "Smith" }; - Set> violations = executableValidator.validateConstructorParameters(constructor, parameterValues); - - assertEquals(0, violations.size()); - } - - @Test - public void whenCrossParameterValidationWithInvalidConstructorParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException { - - Constructor constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class); - Object[] parameterValues = { LocalDate.now(), LocalDate.now(), new Customer("William", "Smith"), 1 }; - Set> violations = executableValidator.validateConstructorParameters(constructor, parameterValues); - - assertEquals(1, violations.size()); - } - - @Test - public void whenCrossParameterValidationWithValidConstructorParameters_thenZeroVoilations() throws NoSuchMethodException { - - Constructor constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class); - Object[] parameterValues = { LocalDate.now() - .plusDays(1), - LocalDate.now() - .plusDays(2), - new Customer("William", "Smith"), 1 }; - Set> violations = executableValidator.validateConstructorParameters(constructor, parameterValues); - - assertEquals(0, violations.size()); - } - - @Test - public void whenValidationWithInvalidReturnValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException { - - ReservationManagement object = new ReservationManagement(); - Method method = ReservationManagement.class.getMethod("getAllCustomers"); - Object returnValue = Collections. emptyList(); - Set> violations = executableValidator.validateReturnValue(object, method, returnValue); - - assertEquals(1, violations.size()); - } - - @Test - public void whenValidationWithValidReturnValue_thenZeroVoilations() throws NoSuchMethodException { - - ReservationManagement object = new ReservationManagement(); - Method method = ReservationManagement.class.getMethod("getAllCustomers"); - Object returnValue = Collections.singletonList(new Customer("William", "Smith")); - Set> violations = executableValidator.validateReturnValue(object, method, returnValue); - - assertEquals(0, violations.size()); - } - - @Test - public void whenValidationWithInvalidConstructorReturnValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException { - - Constructor constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class); - Reservation createdObject = new Reservation(LocalDate.now(), LocalDate.now(), new Customer("William", "Smith"), 0); - Set> violations = executableValidator.validateConstructorReturnValue(constructor, createdObject); - - assertEquals(1, violations.size()); - } - - @Test - public void whenValidationWithValidConstructorReturnValue_thenZeroVoilations() throws NoSuchMethodException { - - Constructor constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class); - Reservation createdObject = new Reservation(LocalDate.now() - .plusDays(1), - LocalDate.now() - .plusDays(2), - new Customer("William", "Smith"), 1); - Set> violations = executableValidator.validateConstructorReturnValue(constructor, createdObject); - - assertEquals(0, violations.size()); - } - - @Test - public void whenValidationWithInvalidCascadedValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException { - - ReservationManagement object = new ReservationManagement(); - Method method = ReservationManagement.class.getMethod("createReservation", Reservation.class); - Customer customer = new Customer(); - customer.setFirstName("John"); - customer.setLastName("Doe"); - Reservation reservation = new Reservation(LocalDate.now() - .plusDays(1), - LocalDate.now() - .plusDays(2), - customer, 1); - Object[] parameterValues = { reservation }; - Set> violations = executableValidator.validateParameters(object, method, parameterValues); - - assertEquals(2, violations.size()); - } - - @Test - public void whenValidationWithValidCascadedValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException { - - ReservationManagement object = new ReservationManagement(); - Method method = ReservationManagement.class.getMethod("createReservation", Reservation.class); - Customer customer = new Customer(); - customer.setFirstName("William"); - customer.setLastName("Smith"); - Reservation reservation = new Reservation(LocalDate.now() - .plusDays(1), - LocalDate.now() - .plusDays(2), - customer, 1); - Object[] parameterValues = { reservation }; - Set> violations = executableValidator.validateParameters(object, method, parameterValues); - - assertEquals(0, violations.size()); - } - -} diff --git a/jee-7-security/README.md b/jee-7-security/README.md index ced2beec46..0d95d81474 100644 --- a/jee-7-security/README.md +++ b/jee-7-security/README.md @@ -3,4 +3,4 @@ This module contains articles about security in JEE 7. ### Relevant Articles: -- [Securing Java EE with Spring Security](https://www.baeldung.com/java-ee-spring-security) +- [Securing Jakarta EE with Spring Security](https://www.baeldung.com/java-ee-spring-security) diff --git a/jee-7/README.md b/jee-7/README.md index 2c45fe2c67..adaee67d74 100644 --- a/jee-7/README.md +++ b/jee-7/README.md @@ -3,7 +3,7 @@ This module contains articles about JEE 7. ### Relevant Articles: -- [Scheduling in Java EE](https://www.baeldung.com/scheduling-in-java-enterprise-edition) +- [Scheduling in Jakarta EE](https://www.baeldung.com/scheduling-in-java-enterprise-edition) - [JSON Processing in Java EE 7](https://www.baeldung.com/jee7-json) - [Converters, Listeners and Validators in Java EE 7](https://www.baeldung.com/java-ee7-converter-listener-validator) - [Introduction to JAX-WS](https://www.baeldung.com/jax-ws) diff --git a/jee-7/pom.xml b/jee-7/pom.xml index 635d820c2b..9077aae1a6 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -118,7 +118,7 @@ javax.mvc javax.mvc-api - 20160715 + ${mvc.api.version} org.glassfish.ozark @@ -215,7 +215,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -242,6 +242,28 @@ + + + org.codehaus.mojo + jaxws-maven-plugin + 2.6 + + + wsimport-from-jdk + + wsimport + + + + + + http://localhost:8888/ws/country?wsdl + + true + com.baeldung.soap.ws.client.generated + src/main/java + + @@ -506,6 +528,8 @@ + 1.0.0 + 20160715 1.8 3.0.0 7.0 diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Country.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Country.java new file mode 100644 index 0000000000..6a810b9afa --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Country.java @@ -0,0 +1,129 @@ + +package com.baeldung.soap.ws.client.generated; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; + +/** + *

Java class for country complex type. + * + *

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

+ * <complexType name="country">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="capital" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *         <element name="currency" type="{http://server.ws.soap.baeldung.com/}currency" minOccurs="0"/>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *         <element name="population" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "country", propOrder = { "capital", "currency", "name", "population" }) +public class Country { + + protected String capital; + @XmlSchemaType(name = "string") + protected Currency currency; + protected String name; + protected int population; + + /** + * Gets the value of the capital property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCapital() { + return capital; + } + + /** + * Sets the value of the capital property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCapital(String value) { + this.capital = value; + } + + /** + * Gets the value of the currency property. + * + * @return + * possible object is + * {@link Currency } + * + */ + public Currency getCurrency() { + return currency; + } + + /** + * Sets the value of the currency property. + * + * @param value + * allowed object is + * {@link Currency } + * + */ + public void setCurrency(Currency value) { + this.currency = 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 population property. + * + */ + public int getPopulation() { + return population; + } + + /** + * Sets the value of the population property. + * + */ + public void setPopulation(int value) { + this.population = value; + } + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryService.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryService.java new file mode 100644 index 0000000000..bda4a305a5 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryService.java @@ -0,0 +1,34 @@ + +package com.baeldung.soap.ws.client.generated; + +import javax.jws.WebMethod; +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; +import javax.jws.soap.SOAPBinding; +import javax.xml.bind.annotation.XmlSeeAlso; +import javax.xml.ws.Action; + +/** + * This class was generated by the JAX-WS RI. + * JAX-WS RI 2.3.2 + * Generated source version: 2.2 + * + */ +@WebService(name = "CountryService", targetNamespace = "http://server.ws.soap.baeldung.com/") +@SOAPBinding(style = SOAPBinding.Style.RPC) +@XmlSeeAlso({ ObjectFactory.class }) +public interface CountryService { + + /** + * + * @param arg0 + * @return + * returns com.baeldung.soap.ws.client.generated.Country + */ + @WebMethod + @WebResult(partName = "return") + @Action(input = "http://server.ws.soap.baeldung.com/CountryService/findByNameRequest", output = "http://server.ws.soap.baeldung.com/CountryService/findByNameResponse") + public Country findByName(@WebParam(name = "arg0", partName = "arg0") String arg0); + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryServiceImplService.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryServiceImplService.java new file mode 100644 index 0000000000..a6983938f5 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryServiceImplService.java @@ -0,0 +1,91 @@ + +package com.baeldung.soap.ws.client.generated; + +import java.net.MalformedURLException; +import java.net.URL; +import javax.xml.namespace.QName; +import javax.xml.ws.Service; +import javax.xml.ws.WebEndpoint; +import javax.xml.ws.WebServiceClient; +import javax.xml.ws.WebServiceException; +import javax.xml.ws.WebServiceFeature; + +/** + * This class was generated by the JAX-WS RI. + * JAX-WS RI 2.2.9-b130926.1035 + * Generated source version: 2.2 + * + */ +@WebServiceClient(name = "CountryServiceImplService", targetNamespace = "http://server.ws.soap.baeldung.com/", wsdlLocation = "http://localhost:8888/ws/country?wsdl") +public class CountryServiceImplService extends Service { + + private final static URL COUNTRYSERVICEIMPLSERVICE_WSDL_LOCATION; + private final static WebServiceException COUNTRYSERVICEIMPLSERVICE_EXCEPTION; + private final static QName COUNTRYSERVICEIMPLSERVICE_QNAME = new QName("http://server.ws.soap.baeldung.com/", "CountryServiceImplService"); + + static { + URL url = null; + WebServiceException e = null; + try { + url = new URL("http://localhost:8888/ws/country?wsdl"); + } catch (MalformedURLException ex) { + e = new WebServiceException(ex); + } + COUNTRYSERVICEIMPLSERVICE_WSDL_LOCATION = url; + COUNTRYSERVICEIMPLSERVICE_EXCEPTION = e; + } + + public CountryServiceImplService() { + super(__getWsdlLocation(), COUNTRYSERVICEIMPLSERVICE_QNAME); + } + + public CountryServiceImplService(WebServiceFeature... features) { + super(__getWsdlLocation(), COUNTRYSERVICEIMPLSERVICE_QNAME, features); + } + + public CountryServiceImplService(URL wsdlLocation) { + super(wsdlLocation, COUNTRYSERVICEIMPLSERVICE_QNAME); + } + + public CountryServiceImplService(URL wsdlLocation, WebServiceFeature... features) { + super(wsdlLocation, COUNTRYSERVICEIMPLSERVICE_QNAME, features); + } + + public CountryServiceImplService(URL wsdlLocation, QName serviceName) { + super(wsdlLocation, serviceName); + } + + public CountryServiceImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { + super(wsdlLocation, serviceName, features); + } + + /** + * + * @return + * returns CountryService + */ + @WebEndpoint(name = "CountryServiceImplPort") + public CountryService getCountryServiceImplPort() { + return super.getPort(new QName("http://server.ws.soap.baeldung.com/", "CountryServiceImplPort"), CountryService.class); + } + + /** + * + * @param features + * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the features parameter will have their default values. + * @return + * returns CountryService + */ + @WebEndpoint(name = "CountryServiceImplPort") + public CountryService getCountryServiceImplPort(WebServiceFeature... features) { + return super.getPort(new QName("http://server.ws.soap.baeldung.com/", "CountryServiceImplPort"), CountryService.class, features); + } + + private static URL __getWsdlLocation() { + if (COUNTRYSERVICEIMPLSERVICE_EXCEPTION != null) { + throw COUNTRYSERVICEIMPLSERVICE_EXCEPTION; + } + return COUNTRYSERVICEIMPLSERVICE_WSDL_LOCATION; + } + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Currency.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Currency.java new file mode 100644 index 0000000000..8b9355edc5 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Currency.java @@ -0,0 +1,37 @@ + +package com.baeldung.soap.ws.client.generated; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + +/** + *

Java class for currency. + * + *

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

+ *

+ * <simpleType name="currency">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="EUR"/>
+ *     <enumeration value="INR"/>
+ *     <enumeration value="USD"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "currency") +@XmlEnum +public enum Currency { + + EUR, INR, USD; + + public String value() { + return name(); + } + + public static Currency fromValue(String v) { + return valueOf(v); + } + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/ObjectFactory.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/ObjectFactory.java new file mode 100644 index 0000000000..241debe758 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/ObjectFactory.java @@ -0,0 +1,38 @@ + +package com.baeldung.soap.ws.client.generated; + +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.soap.ws.client.generated 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.soap.ws.client.generated + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link Country } + * + */ + public Country createCountry() { + return new Country(); + } + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/package-info.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/package-info.java new file mode 100644 index 0000000000..6df70b70f1 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/package-info.java @@ -0,0 +1,2 @@ +@javax.xml.bind.annotation.XmlSchema(namespace = "http://server.ws.soap.baeldung.com/", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package com.baeldung.soap.ws.client.generated; diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/Country.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/Country.java new file mode 100644 index 0000000000..62ea4a22ed --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/Country.java @@ -0,0 +1,41 @@ +package com.baeldung.soap.ws.server; + +public class Country { + protected String name; + protected int population; + protected String capital; + protected Currency currency; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getPopulation() { + return population; + } + + public void setPopulation(int population) { + this.population = population; + } + + public String getCapital() { + return capital; + } + + public void setCapital(String capital) { + this.capital = capital; + } + + public Currency getCurrency() { + return currency; + } + + public void setCurrency(Currency currency) { + this.currency = currency; + } + +} \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryRepository.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryRepository.java new file mode 100644 index 0000000000..558f7c1293 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryRepository.java @@ -0,0 +1,43 @@ +package com.baeldung.soap.ws.server; + +import java.util.HashMap; +import java.util.Map; + +public class CountryRepository { + + private static final Map countries = new HashMap<>(); + + { + initData(); + } + + private final static void initData() { + Country usa = new Country(); + usa.setName("USA"); + usa.setCapital("Washington D.C."); + usa.setCurrency(Currency.USD); + usa.setPopulation(323947000); + + countries.put(usa.getName(), usa); + + Country india = new Country(); + india.setName("India"); + india.setCapital("New Delhi"); + india.setCurrency(Currency.INR); + india.setPopulation(1295210000); + + countries.put(india.getName(), india); + + Country france = new Country(); + france.setName("France"); + france.setCapital("Paris"); + france.setCurrency(Currency.EUR); + france.setPopulation(66710000); + + countries.put(france.getName(), france); + } + + public Country findCountry(String name) { + return countries.get(name); + } +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryService.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryService.java new file mode 100644 index 0000000000..e3f68a4e59 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryService.java @@ -0,0 +1,15 @@ +package com.baeldung.soap.ws.server; + +import javax.jws.WebMethod; +import javax.jws.WebService; +import javax.jws.soap.SOAPBinding; +import javax.jws.soap.SOAPBinding.Style; + +@WebService +@SOAPBinding(style=Style.RPC) +public interface CountryService { + + @WebMethod + Country findByName(String name); + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServiceImpl.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServiceImpl.java new file mode 100644 index 0000000000..a8c6250354 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServiceImpl.java @@ -0,0 +1,15 @@ +package com.baeldung.soap.ws.server; + +import javax.jws.WebService; + +@WebService(endpointInterface = "com.baeldung.soap.ws.server.CountryService") +public class CountryServiceImpl implements CountryService { + + private CountryRepository countryRepository = new CountryRepository(); + + @Override + public Country findByName(String name) { + return countryRepository.findCountry(name); + } + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServicePublisher.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServicePublisher.java new file mode 100644 index 0000000000..e7c1c480f4 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServicePublisher.java @@ -0,0 +1,19 @@ +package com.baeldung.soap.ws.server; + +import javax.xml.ws.Endpoint; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class CountryServicePublisher { + + private static final Logger logger = LoggerFactory.getLogger(CountryServicePublisher.class); + + public static void main(String[] args) { + Endpoint endpoint = Endpoint.create(new CountryServiceImpl()); + endpoint.publish("http://localhost:8888/ws/country"); + + logger.info("Country web service ready to consume requests!"); + } +} \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/Currency.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/Currency.java new file mode 100644 index 0000000000..d1b25a26c6 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/Currency.java @@ -0,0 +1,15 @@ +package com.baeldung.soap.ws.server; + +public enum Currency { + + EUR, INR, USD; + + public String value() { + return name(); + } + + public static Currency fromValue(String v) { + return valueOf(v); + } + +} diff --git a/jee-7/src/main/resources/country.xsd b/jee-7/src/main/resources/country.xsd new file mode 100644 index 0000000000..c94b6047f9 --- /dev/null +++ b/jee-7/src/main/resources/country.xsd @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java index dfea878a75..c607efeb24 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java @@ -1,15 +1,14 @@ package com.baeldung.batch.understanding; -import static org.junit.jupiter.api.Assertions.*; -import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Properties; + import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; -import javax.batch.runtime.Metric; import javax.batch.runtime.StepExecution; -import com.baeldung.batch.understanding.BatchTestHelper; import org.junit.jupiter.api.Test; diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java index 7c5e8d0b78..4b27e5f5ec 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java @@ -1,6 +1,8 @@ package com.baeldung.batch.understanding; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java index ade492b1b9..788b75eb3e 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java @@ -1,11 +1,14 @@ package com.baeldung.batch.understanding; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Properties; + import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; + import org.junit.jupiter.api.Test; class SimpleBatchLetUnitTest { diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java index 57c794ba00..9010c365a2 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.batch.understanding; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Map; diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java index ded31b6345..bc410aec8d 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java @@ -1,17 +1,14 @@ package com.baeldung.batch.understanding; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.*; import java.util.List; -import java.util.Map; import java.util.Properties; + import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; -import javax.batch.runtime.Metric.MetricType; import javax.batch.runtime.StepExecution; import org.junit.jupiter.api.Test; diff --git a/jee-7/src/test/java/com/baeldung/soap/ws/client/CountryClientLiveTest.java b/jee-7/src/test/java/com/baeldung/soap/ws/client/CountryClientLiveTest.java new file mode 100644 index 0000000000..ae423f9bdd --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/soap/ws/client/CountryClientLiveTest.java @@ -0,0 +1,39 @@ +package com.baeldung.soap.ws.client; + +import static org.junit.Assert.assertEquals; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.soap.ws.client.generated.CountryService; +import com.baeldung.soap.ws.client.generated.CountryServiceImplService; +import com.baeldung.soap.ws.client.generated.Currency; + +//Ensure that com.baeldung.soap.ws.server.CountryServicePublisher is running before executing this test +public class CountryClientLiveTest { + + private static CountryService countryService; + + @BeforeClass + public static void setup() { + CountryServiceImplService service = new CountryServiceImplService(); + countryService = service.getCountryServiceImplPort(); + } + + @Test + public void givenCountryService_whenCountryIndia_thenCapitalIsNewDelhi() { + assertEquals("New Delhi", countryService.findByName("India").getCapital()); + } + + @Test + public void givenCountryService_whenCountryFrance_thenPopulationCorrect() { + assertEquals(66710000, countryService.findByName("France").getPopulation()); + } + + @Test + public void givenCountryService_whenCountryUSA_thenCurrencyUSD() { + assertEquals(Currency.USD, countryService.findByName("USA").getCurrency()); + } + + +} diff --git a/jee-7/src/test/resources/jberet.properties b/jee-7/src/test/resources/jberet.properties new file mode 100644 index 0000000000..e8b9907de5 --- /dev/null +++ b/jee-7/src/test/resources/jberet.properties @@ -0,0 +1 @@ +db-url=jdbc:h2:mem:jberet-repo;DB_CLOSE_DELAY=-1 \ No newline at end of file diff --git a/jee-kotlin/README.md b/jee-kotlin/README.md index aa3aa58b4e..e8975a7f62 100644 --- a/jee-kotlin/README.md +++ b/jee-kotlin/README.md @@ -3,4 +3,4 @@ This module contains articles about Java EE with Kotlin. ### Relevant Articles: -- [Java EE Application with Kotlin](https://www.baeldung.com/java-ee-kotlin-app) +- [Jakarta EE Application with Kotlin](https://www.baeldung.com/java-ee-kotlin-app) diff --git a/jee-kotlin/pom.xml b/jee-kotlin/pom.xml index 80c5ea4e22..9191885bd4 100644 --- a/jee-kotlin/pom.xml +++ b/jee-kotlin/pom.xml @@ -253,7 +253,7 @@ org.wildfly.arquillian wildfly-arquillian-container-remote - 2.2.0.Final + ${wildfly.arquillian.version} test @@ -261,6 +261,7 @@ + 2.2.0.Final UTF-8 false 8.0 diff --git a/jgit/pom.xml b/jgit/pom.xml index eef3c9b8e8..d960843868 100644 --- a/jgit/pom.xml +++ b/jgit/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - JGit + jgit 1.0-SNAPSHOT - JGit + jgit jar http://maven.apache.org diff --git a/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java deleted file mode 100644 index ad34890996..0000000000 --- a/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.jgit; - -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.ObjectReader; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevWalk; -import org.junit.Test; -import java.io.IOException; -import static org.junit.Assert.assertNotNull; - -/** - * Tests which show issues with JGit that we reported upstream. - */ -public class JGitBugIntegrationTest { - @Test - public void testRevWalkDisposeClosesReader() throws IOException { - try (Repository repo = Helper.openJGitRepository()) { - try (ObjectReader reader = repo.newObjectReader()) { - try (RevWalk walk = new RevWalk(reader)) { - walk.dispose(); - - Ref head = repo.exactRef("refs/heads/master"); - System.out.println("Found head: " + head); - - ObjectLoader loader = reader.open(head.getObjectId()); - assertNotNull(loader); - } - } - } - } -} diff --git a/jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java b/jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java new file mode 100644 index 0000000000..bcfe615bc7 --- /dev/null +++ b/jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java @@ -0,0 +1,41 @@ +package com.baeldung.jgit; + +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.lib.ObjectLoader; +import org.eclipse.jgit.lib.ObjectReader; +import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevWalk; +import org.junit.Test; +import java.io.IOException; +import static org.junit.Assert.assertNotNull; + +public class JGitBugManualTest { + + /** + * This test case expects one git repository to be present in local file system. + * Currently this test uses the Baeldung repository i.e. the current checkout repository. + * It finds the repository by tracking back and scan file system to find .git folder in + * the file system. + * + * Before running the test case ensure that the .git folder is present. + * + * @throws IOException + */ + @Test + public void testRevWalkDisposeClosesReader() throws IOException { + try (Repository repo = Helper.openJGitRepository()) { + try (ObjectReader reader = repo.newObjectReader()) { + try (RevWalk walk = new RevWalk(reader)) { + walk.dispose(); + + Ref head = repo.exactRef("refs/heads/master"); + System.out.println("Found head: " + head); + + ObjectLoader loader = reader.open(head.getObjectId()); + assertNotNull(loader); + } + } + } + } +} diff --git a/jhipster-5/bookstore-monolith/.gitignore b/jhipster-5/bookstore-monolith/.gitignore index f1f6845d33..b3f7df5404 100644 --- a/jhipster-5/bookstore-monolith/.gitignore +++ b/jhipster-5/bookstore-monolith/.gitignore @@ -14,6 +14,7 @@ node_modules/ npm-debug.log.* /.awcache/* /.cache-loader/* +package-lock.json ###################### # SASS diff --git a/jhipster-5/bookstore-monolith/package-lock.json b/jhipster-5/bookstore-monolith/package-lock.json deleted file mode 100644 index 6e2a8dc526..0000000000 --- a/jhipster-5/bookstore-monolith/package-lock.json +++ /dev/null @@ -1,18244 +0,0 @@ -{ - "name": "bookstore", - "version": "0.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "@angular-devkit/architect": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/@angular-devkit/architect/-/architect-0.13.1.tgz", - "integrity": "sha512-QDmIbqde75ZZSEFbw6Q6kQWq4cY6C7D67yujXw6XTyubDNAs1tyXJyxTIB8vjSlEKwRizTTDd/B0ZXVcke3Mvw==", - "dev": true, - "requires": { - "@angular-devkit/core": "7.3.1", - "rxjs": "6.3.3" - }, - "dependencies": { - "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", - "dev": true, - "requires": { - "tslib": "^1.9.0" - } - } - } - }, - "@angular-devkit/core": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-7.3.1.tgz", - "integrity": "sha512-56XDWWfIzOAkEk69lBLgmCYybPUA4yjunhmMlCk7vVdb7gbQUyzNjFD04Uj0GjlejatAQ5F76tRwygD9C+3RXQ==", - "dev": true, - "requires": { - "ajv": "6.7.0", - "chokidar": "2.0.4", - "fast-json-stable-stringify": "2.0.0", - "rxjs": "6.3.3", - "source-map": "0.7.3" - }, - "dependencies": { - "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", - "dev": true, - "requires": { - "tslib": "^1.9.0" - } - } - } - }, - "@angular-devkit/schematics": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-7.3.1.tgz", - "integrity": "sha512-cd7usiasfSgw75INz72/VssrLr9tiVRYfo1TEdvr9ww0GuQbuQpB33xbV8W135eAV8+wzQ3Ce8ohaDHibvj6Yg==", - "dev": true, - "requires": { - "@angular-devkit/core": "7.3.1", - "rxjs": "6.3.3" - }, - "dependencies": { - "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", - "dev": true, - "requires": { - "tslib": "^1.9.0" - } - } - } - }, - "@angular/cli": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/@angular/cli/-/cli-7.3.1.tgz", - "integrity": "sha512-8EvXYRhTqTaTk5PKv7VZxIWJiyG51R9RC9gtpRFx4bbnurqBHdEUxGMmaRsGT8QDbfvVsWnuakE0eeW1CrfZAQ==", - "dev": true, - "requires": { - "@angular-devkit/architect": "0.13.1", - "@angular-devkit/core": "7.3.1", - "@angular-devkit/schematics": "7.3.1", - "@schematics/angular": "7.3.1", - "@schematics/update": "0.13.1", - "@yarnpkg/lockfile": "1.1.0", - "ini": "1.3.5", - "inquirer": "6.2.1", - "npm-package-arg": "6.1.0", - "opn": "5.4.0", - "pacote": "9.4.0", - "semver": "5.6.0", - "symbol-observable": "1.2.0" - }, - "dependencies": { - "ansi-escapes": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", - "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==", - "dev": true - }, - "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "chardet": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", - "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", - "dev": true - }, - "external-editor": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.0.3.tgz", - "integrity": "sha512-bn71H9+qWoOQKyZDo25mOMVpSmXROAsTJVVVYzrrtol3d4y+AsKjf4Iwl2Q+IuT0kFSQ1qo166UuIwqYq7mGnA==", - "dev": true, - "requires": { - "chardet": "^0.7.0", - "iconv-lite": "^0.4.24", - "tmp": "^0.0.33" - } - }, - "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", - "dev": true, - "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", - "cli-cursor": "^2.1.0", - "cli-width": "^2.0.0", - "external-editor": "^3.0.0", - "figures": "^2.0.0", - "lodash": "^4.17.10", - "mute-stream": "0.0.7", - "run-async": "^2.2.0", - "rxjs": "^6.1.0", - "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", - "through": "^2.3.6" - } - }, - "opn": { - "version": "5.4.0", - "resolved": "https://registry.npmjs.org/opn/-/opn-5.4.0.tgz", - "integrity": "sha512-YF9MNdVy/0qvJvDtunAOzFw9iasOQHpVthTCvGzxt61Il64AYSGdK+rYwld7NAfk9qJ7dt+hymBNSc9LNYS+Sw==", - "dev": true, - "requires": { - "is-wsl": "^1.1.0" - } - }, - "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "dev": true, - "requires": { - "ansi-regex": "^4.1.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "@angular/common": { - "version": "7.2.4", - "resolved": "https://registry.npmjs.org/@angular/common/-/common-7.2.4.tgz", - "integrity": "sha512-3/i8RtnLTx/90gJHk5maE8zwsSiHgHvLItaa0qVfNlWiU0eCId/PL6TgDkut5vN9SQYL0oxhxFaVd35HmwsmuQ==", - "requires": { - "tslib": "^1.9.0" - } - }, - "@angular/compiler": { - "version": "7.2.4", - "resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-7.2.4.tgz", - "integrity": "sha512-+zyMzPCL45ePEV9nrnYJvhAVgp2Y19bDaq0f0YdZAqAjgDqHzXGGR6wX8GueyJWmUYWx5vwK6Apla4HwDrYA1w==", - "requires": { - "tslib": "^1.9.0" - } - }, - "@angular/compiler-cli": { - "version": "7.2.4", - "resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-7.2.4.tgz", - "integrity": "sha512-UhLosSeuwFIfaGqGcYOh9WSOuzEpeuhIRAOt81MeqOQEqkoreUjfxrQq8XWNkdqsPZHtiptF5ZwXlMBxlj9jJg==", - "dev": true, - "requires": { - "canonical-path": "1.0.0", - "chokidar": "^1.4.2", - "convert-source-map": "^1.5.1", - "dependency-graph": "^0.7.2", - "magic-string": "^0.25.0", - "minimist": "^1.2.0", - "reflect-metadata": "^0.1.2", - "shelljs": "^0.8.1", - "source-map": "^0.6.1", - "tslib": "^1.9.0", - "yargs": "9.0.1" - }, - "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" - } - }, - "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 - } - } - }, - "@angular/core": { - "version": "7.2.4", - "resolved": "https://registry.npmjs.org/@angular/core/-/core-7.2.4.tgz", - "integrity": "sha512-kfAxhIxl89PmB7y81FR/RAv0yWRFcEYxEnTwV+o8jKGfemAXtQ0g/Vh+lJR0SD/TBgFilMxotN1mhwH4A8GShw==", - "requires": { - "tslib": "^1.9.0" - } - }, - "@angular/forms": { - "version": "7.2.4", - "resolved": "https://registry.npmjs.org/@angular/forms/-/forms-7.2.4.tgz", - "integrity": "sha512-DAtOrdlTRsgvmZrsvczCAkY8dhTwZb5DXBmPuSXh0UR9lvEiCgNHGbwEiIiIkAHpw1wSeXZrq0qyy/oJRvf18g==", - "requires": { - "tslib": "^1.9.0" - } - }, - "@angular/platform-browser": { - "version": "7.2.4", - "resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-7.2.4.tgz", - "integrity": "sha512-Klt8aKR5SP9bqfMfpSY5vQOY7AQEs8JGuZOk5Bfc2dUtYT2IEIvK2IqO8v2rcFRVO13HOPUxl328efyHqLgI7g==", - "requires": { - "tslib": "^1.9.0" - } - }, - "@angular/platform-browser-dynamic": { - "version": "7.2.4", - "resolved": "https://registry.npmjs.org/@angular/platform-browser-dynamic/-/platform-browser-dynamic-7.2.4.tgz", - "integrity": "sha512-J/xWlmaYOPUoCHZ5TiIRiyYa4uRMtCz3aGdBfY8k/NWtNo8SCYaS3aut7Sk4RS5rK8aAVi+aYFlY5YOrlW+Hbg==", - "requires": { - "tslib": "^1.9.0" - } - }, - "@angular/router": { - "version": "7.2.4", - "resolved": "https://registry.npmjs.org/@angular/router/-/router-7.2.4.tgz", - "integrity": "sha512-T8Uqf2H1SV1MQI38WwYJ4aa+4NNnvlp2Tp/rkfg6tKcp/cLkKqE6OOfiy9lmW+i/624v8tMgYoBMOUNBjAG23g==", - "requires": { - "tslib": "^1.9.0" - } - }, - "@babel/code-frame": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz", - "integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==", - "dev": true, - "requires": { - "@babel/highlight": "^7.0.0" - } - }, - "@babel/core": { - "version": "7.3.4", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.3.4.tgz", - "integrity": "sha512-jRsuseXBo9pN197KnDwhhaaBzyZr2oIcLHHTt2oDdQrej5Qp57dCCJafWx5ivU8/alEYDpssYqv1MUqcxwQlrA==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/generator": "^7.3.4", - "@babel/helpers": "^7.2.0", - "@babel/parser": "^7.3.4", - "@babel/template": "^7.2.2", - "@babel/traverse": "^7.3.4", - "@babel/types": "^7.3.4", - "convert-source-map": "^1.1.0", - "debug": "^4.1.0", - "json5": "^2.1.0", - "lodash": "^4.17.11", - "resolve": "^1.3.2", - "semver": "^5.4.1", - "source-map": "^0.5.0" - }, - "dependencies": { - "debug": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", - "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "json5": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.0.tgz", - "integrity": "sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==", - "dev": true, - "requires": { - "minimist": "^1.2.0" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "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 - } - } - }, - "@babel/generator": { - "version": "7.3.4", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.3.4.tgz", - "integrity": "sha512-8EXhHRFqlVVWXPezBW5keTiQi/rJMQTg/Y9uVCEZ0CAF3PKtCCaVRnp64Ii1ujhkoDhhF1fVsImoN4yJ2uz4Wg==", - "dev": true, - "requires": { - "@babel/types": "^7.3.4", - "jsesc": "^2.5.1", - "lodash": "^4.17.11", - "source-map": "^0.5.0", - "trim-right": "^1.0.1" - }, - "dependencies": { - "jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", - "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 - } - } - }, - "@babel/helper-function-name": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz", - "integrity": "sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==", - "dev": true, - "requires": { - "@babel/helper-get-function-arity": "^7.0.0", - "@babel/template": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "@babel/helper-get-function-arity": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz", - "integrity": "sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==", - "dev": true, - "requires": { - "@babel/types": "^7.0.0" - } - }, - "@babel/helper-plugin-utils": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz", - "integrity": "sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==", - "dev": true - }, - "@babel/helper-split-export-declaration": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.0.0.tgz", - "integrity": "sha512-MXkOJqva62dfC0w85mEf/LucPPS/1+04nmmRMPEBUB++hiiThQ2zPtX/mEWQ3mtzCEjIJvPY8nuwxXtQeQwUag==", - "dev": true, - "requires": { - "@babel/types": "^7.0.0" - } - }, - "@babel/helpers": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.3.1.tgz", - "integrity": "sha512-Q82R3jKsVpUV99mgX50gOPCWwco9Ec5Iln/8Vyu4osNIOQgSrd9RFrQeUvmvddFNoLwMyOUWU+5ckioEKpDoGA==", - "dev": true, - "requires": { - "@babel/template": "^7.1.2", - "@babel/traverse": "^7.1.5", - "@babel/types": "^7.3.0" - } - }, - "@babel/highlight": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz", - "integrity": "sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==", - "dev": true, - "requires": { - "chalk": "^2.0.0", - "esutils": "^2.0.2", - "js-tokens": "^4.0.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "@babel/parser": { - "version": "7.3.4", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.3.4.tgz", - "integrity": "sha512-tXZCqWtlOOP4wgCp6RjRvLmfuhnqTLy9VHwRochJBCP2nDm27JnnuFEnXFASVyQNHk36jD1tAammsCEEqgscIQ==", - "dev": true - }, - "@babel/plugin-syntax-object-rest-spread": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.2.0.tgz", - "integrity": "sha512-t0JKGgqk2We+9may3t0xDdmneaXmyxq0xieYcKHxIsrJO64n1OiMWNUtc5gQK1PA0NpdCRrtZp4z+IUaKugrSA==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.0.0" - } - }, - "@babel/runtime": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.0.0.tgz", - "integrity": "sha512-7hGhzlcmg01CvH1EHdSPVXYX1aJ8KCEyz6I9xYIi/asDtzBPMyMhVibhM/K6g/5qnKBwjZtp10bNZIEFTRW1MA==", - "dev": true, - "requires": { - "regenerator-runtime": "^0.12.0" - }, - "dependencies": { - "regenerator-runtime": { - "version": "0.12.1", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.12.1.tgz", - "integrity": "sha512-odxIc1/vDlo4iZcfXqRYFj0vpXFNoGdKMAUieAlFYO6m/nl5e9KR/beGf41z4a1FI+aQgtjhuaSlDxQ0hmkrHg==", - "dev": true - } - } - }, - "@babel/template": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.2.2.tgz", - "integrity": "sha512-zRL0IMM02AUDwghf5LMSSDEz7sBCO2YnNmpg3uWTZj/v1rcG2BmQUvaGU8GhU8BvfMh1k2KIAYZ7Ji9KXPUg7g==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/parser": "^7.2.2", - "@babel/types": "^7.2.2" - } - }, - "@babel/traverse": { - "version": "7.3.4", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.3.4.tgz", - "integrity": "sha512-TvTHKp6471OYEcE/91uWmhR6PrrYywQntCHSaZ8CM8Vmp+pjAusal4nGB2WCCQd0rvI7nOMKn9GnbcvTUz3/ZQ==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/generator": "^7.3.4", - "@babel/helper-function-name": "^7.1.0", - "@babel/helper-split-export-declaration": "^7.0.0", - "@babel/parser": "^7.3.4", - "@babel/types": "^7.3.4", - "debug": "^4.1.0", - "globals": "^11.1.0", - "lodash": "^4.17.11" - }, - "dependencies": { - "debug": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", - "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - } - } - }, - "@babel/types": { - "version": "7.3.4", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.3.4.tgz", - "integrity": "sha512-WEkp8MsLftM7O/ty580wAmZzN1nDmCACc5+jFzUt+GUFNNIi3LdRlueYz0YIlmJhlZx1QYDMZL5vdWCL0fNjFQ==", - "dev": true, - "requires": { - "esutils": "^2.0.2", - "lodash": "^4.17.11", - "to-fast-properties": "^2.0.0" - } - }, - "@cnakazawa/watch": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@cnakazawa/watch/-/watch-1.0.3.tgz", - "integrity": "sha512-r5160ogAvGyHsal38Kux7YYtodEKOj89RGb28ht1jh3SJb08VwRwAKKJL0bGb04Zd/3r9FL3BFIc3bBidYffCA==", - "dev": true, - "requires": { - "exec-sh": "^0.3.2", - "minimist": "^1.2.0" - } - }, - "@fortawesome/angular-fontawesome": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@fortawesome/angular-fontawesome/-/angular-fontawesome-0.3.0.tgz", - "integrity": "sha512-wXvyPI7GidoNiqeMz2re9iemUMFH4zBmuv94CfXlaanQ8+kMP/fYs/k69PLVN1KsebQY4kRA9GHmc1U1ndBkJg==", - "requires": { - "tslib": "^1.9.0" - } - }, - "@fortawesome/fontawesome-common-types": { - "version": "0.2.15", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-0.2.15.tgz", - "integrity": "sha512-ATBRyKJw1d2ko+0DWN9+BXau0EK3I/Q6pPzPv3LhJD7r052YFAkAdfb1Bd7ZqhBsJrdse/S7jKxWUOZ61qBD4g==" - }, - "@fortawesome/fontawesome-svg-core": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-1.2.14.tgz", - "integrity": "sha512-T1qCqkwm9PuvK53J64D1ovfrOTa1kG+SrHNj5cFst/rrskhCnbxpRdbqFIdc/thmXC0ebBX8nOUyja2/mrxe4g==", - "requires": { - "@fortawesome/fontawesome-common-types": "^0.2.14" - } - }, - "@fortawesome/free-solid-svg-icons": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-5.7.1.tgz", - "integrity": "sha512-5V/Q+JoPzuiIHW2JwmZGvE9bHguvNJKa7611DPo51uIvYv9LweX/SnDF+HC23X2W5T3myHhnGi+EZJTmidAmyg==", - "requires": { - "@fortawesome/fontawesome-common-types": "^0.2.14" - } - }, - "@iamstarkov/listr-update-renderer": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@iamstarkov/listr-update-renderer/-/listr-update-renderer-0.4.1.tgz", - "integrity": "sha512-IJyxQWsYDEkf8C8QthBn5N8tIUR9V9je6j3sMIpAkonaadjbvxmRC6RAhpa3RKxndhNnU2M6iNbtJwd7usQYIA==", - "dev": true, - "requires": { - "chalk": "^1.1.3", - "cli-truncate": "^0.2.1", - "elegant-spinner": "^1.0.1", - "figures": "^1.7.0", - "indent-string": "^3.0.0", - "log-symbols": "^1.0.2", - "log-update": "^2.3.0", - "strip-ansi": "^3.0.1" - }, - "dependencies": { - "figures": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-1.7.0.tgz", - "integrity": "sha1-y+Hjr/zxzUS4DK3+0o3Hk6lwHS4=", - "dev": true, - "requires": { - "escape-string-regexp": "^1.0.5", - "object-assign": "^4.1.0" - } - }, - "log-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-1.0.2.tgz", - "integrity": "sha1-N2/3tY6jCGoPCfrMdGF+ylAeGhg=", - "dev": true, - "requires": { - "chalk": "^1.0.0" - } - } - } - }, - "@jest/console": { - "version": "24.3.0", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-24.3.0.tgz", - "integrity": "sha512-NaCty/OOei6rSDcbPdMiCbYCI0KGFGPgGO6B09lwWt5QTxnkuhKYET9El5u5z1GAcSxkQmSMtM63e24YabCWqA==", - "dev": true, - "requires": { - "@jest/source-map": "^24.3.0", - "@types/node": "*", - "chalk": "^2.0.1", - "slash": "^2.0.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "slash": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", - "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "@jest/core": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-24.5.0.tgz", - "integrity": "sha512-RDZArRzAs51YS7dXG1pbXbWGxK53rvUu8mCDYsgqqqQ6uSOaTjcVyBl2Jce0exT2rSLk38ca7az7t2f3b0/oYQ==", - "dev": true, - "requires": { - "@jest/console": "^24.3.0", - "@jest/reporters": "^24.5.0", - "@jest/test-result": "^24.5.0", - "@jest/transform": "^24.5.0", - "@jest/types": "^24.5.0", - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.1", - "exit": "^0.1.2", - "graceful-fs": "^4.1.15", - "jest-changed-files": "^24.5.0", - "jest-config": "^24.5.0", - "jest-haste-map": "^24.5.0", - "jest-message-util": "^24.5.0", - "jest-regex-util": "^24.3.0", - "jest-resolve-dependencies": "^24.5.0", - "jest-runner": "^24.5.0", - "jest-runtime": "^24.5.0", - "jest-snapshot": "^24.5.0", - "jest-util": "^24.5.0", - "jest-validate": "^24.5.0", - "jest-watcher": "^24.5.0", - "micromatch": "^3.1.10", - "p-each-series": "^1.0.0", - "pirates": "^4.0.1", - "realpath-native": "^1.1.0", - "rimraf": "^2.5.4", - "strip-ansi": "^5.0.0" - }, - "dependencies": { - "ansi-escapes": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", - "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==", - "dev": true - }, - "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "dev": true, - "requires": { - "ansi-regex": "^4.1.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "@jest/environment": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-24.5.0.tgz", - "integrity": "sha512-tzUHR9SHjMXwM8QmfHb/EJNbF0fjbH4ieefJBvtwO8YErLTrecc1ROj0uo2VnIT6SlpEGZnvdCK6VgKYBo8LsA==", - "dev": true, - "requires": { - "@jest/fake-timers": "^24.5.0", - "@jest/transform": "^24.5.0", - "@jest/types": "^24.5.0", - "@types/node": "*", - "jest-mock": "^24.5.0" - } - }, - "@jest/fake-timers": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-24.5.0.tgz", - "integrity": "sha512-i59KVt3QBz9d+4Qr4QxsKgsIg+NjfuCjSOWj3RQhjF5JNy+eVJDhANQ4WzulzNCHd72srMAykwtRn5NYDGVraw==", - "dev": true, - "requires": { - "@jest/types": "^24.5.0", - "@types/node": "*", - "jest-message-util": "^24.5.0", - "jest-mock": "^24.5.0" - } - }, - "@jest/reporters": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-24.5.0.tgz", - "integrity": "sha512-vfpceiaKtGgnuC3ss5czWOihKOUSyjJA4M4udm6nH8xgqsuQYcyDCi4nMMcBKsHXWgz9/V5G7iisnZGfOh1w6Q==", - "dev": true, - "requires": { - "@jest/environment": "^24.5.0", - "@jest/test-result": "^24.5.0", - "@jest/transform": "^24.5.0", - "@jest/types": "^24.5.0", - "chalk": "^2.0.1", - "exit": "^0.1.2", - "glob": "^7.1.2", - "istanbul-api": "^2.1.1", - "istanbul-lib-coverage": "^2.0.2", - "istanbul-lib-instrument": "^3.0.1", - "istanbul-lib-source-maps": "^3.0.1", - "jest-haste-map": "^24.5.0", - "jest-resolve": "^24.5.0", - "jest-runtime": "^24.5.0", - "jest-util": "^24.5.0", - "jest-worker": "^24.4.0", - "node-notifier": "^5.2.1", - "slash": "^2.0.0", - "source-map": "^0.6.0", - "string-length": "^2.0.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "slash": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", - "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", - "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 - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "@jest/source-map": { - "version": "24.3.0", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-24.3.0.tgz", - "integrity": "sha512-zALZt1t2ou8le/crCeeiRYzvdnTzaIlpOWaet45lNSqNJUnXbppUUFR4ZUAlzgDmKee4Q5P/tKXypI1RiHwgag==", - "dev": true, - "requires": { - "callsites": "^3.0.0", - "graceful-fs": "^4.1.15", - "source-map": "^0.6.0" - }, - "dependencies": { - "callsites": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.0.0.tgz", - "integrity": "sha512-tWnkwu9YEq2uzlBDI4RcLn8jrFvF9AOi8PxDNU3hZZjJcjkcRAq3vCI+vZcg1SuxISDYe86k9VZFwAxDiJGoAw==", - "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 - } - } - }, - "@jest/test-result": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-24.5.0.tgz", - "integrity": "sha512-u66j2vBfa8Bli1+o3rCaVnVYa9O8CAFZeqiqLVhnarXtreSXG33YQ6vNYBogT7+nYiFNOohTU21BKiHlgmxD5A==", - "dev": true, - "requires": { - "@jest/console": "^24.3.0", - "@jest/types": "^24.5.0", - "@types/istanbul-lib-coverage": "^1.1.0" - } - }, - "@jest/transform": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-24.5.0.tgz", - "integrity": "sha512-XSsDz1gdR/QMmB8UCKlweAReQsZrD/DK7FuDlNo/pE8EcKMrfi2kqLRk8h8Gy/PDzgqJj64jNEzOce9pR8oj1w==", - "dev": true, - "requires": { - "@babel/core": "^7.1.0", - "@jest/types": "^24.5.0", - "babel-plugin-istanbul": "^5.1.0", - "chalk": "^2.0.1", - "convert-source-map": "^1.4.0", - "fast-json-stable-stringify": "^2.0.0", - "graceful-fs": "^4.1.15", - "jest-haste-map": "^24.5.0", - "jest-regex-util": "^24.3.0", - "jest-util": "^24.5.0", - "micromatch": "^3.1.10", - "realpath-native": "^1.1.0", - "slash": "^2.0.0", - "source-map": "^0.6.1", - "write-file-atomic": "2.4.1" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "slash": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", - "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", - "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 - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "write-file-atomic": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.1.tgz", - "integrity": "sha512-TGHFeZEZMnv+gBFRfjAcxL5bPHrsGKtnb4qsFAws7/vlh+QfwAaySIw4AXP9ZskTTh5GWu3FLuJhsWVdiJPGvg==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.11", - "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.2" - } - } - } - }, - "@jest/types": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-24.5.0.tgz", - "integrity": "sha512-kN7RFzNMf2R8UDadPOl6ReyI+MT8xfqRuAnuVL+i4gwjv/zubdDK+EDeLHYwq1j0CSSR2W/MmgaRlMZJzXdmVA==", - "dev": true, - "requires": { - "@types/istanbul-lib-coverage": "^1.1.0", - "@types/yargs": "^12.0.9" - } - }, - "@mrmlnc/readdir-enhanced": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@mrmlnc/readdir-enhanced/-/readdir-enhanced-2.2.1.tgz", - "integrity": "sha512-bPHp6Ji8b41szTOcaP63VlnbbO5Ny6dwAATtY6JTjh5N2OLrb5Qk/Th5cRkRQhkWCt+EJsYrNB0MiL+Gpn6e3g==", - "dev": true, - "requires": { - "call-me-maybe": "^1.0.1", - "glob-to-regexp": "^0.3.0" - } - }, - "@ng-bootstrap/ng-bootstrap": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@ng-bootstrap/ng-bootstrap/-/ng-bootstrap-4.0.2.tgz", - "integrity": "sha512-SBsN8ORvj/WXpZGSyR2+CRkg6GCtax5+fsLKt9ImHKUVWwePVqRxiGlnxXqwNPHQ46vOdd7nDN9cwE7dfbGaAQ==", - "requires": { - "tslib": "^1.9.0" - } - }, - "@ngtools/webpack": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/@ngtools/webpack/-/webpack-7.3.1.tgz", - "integrity": "sha512-EGQRjgDf5XP+Fm1MdZNRFiPd9e1vhl11BhjkwqkAsewic4eoz6fqXfj/Osz1hQy8xU+2dPPf/byQ/+nY3E02Zg==", - "dev": true, - "requires": { - "@angular-devkit/core": "7.3.1", - "enhanced-resolve": "4.1.0", - "rxjs": "6.3.3", - "tree-kill": "1.2.1", - "webpack-sources": "1.3.0" - }, - "dependencies": { - "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", - "dev": true, - "requires": { - "tslib": "^1.9.0" - } - } - } - }, - "@ngx-translate/core": { - "version": "11.0.1", - "resolved": "https://registry.npmjs.org/@ngx-translate/core/-/core-11.0.1.tgz", - "integrity": "sha512-nBCa1ZD9fAUY/3eskP3Lql2fNg8OMrYIej1/5GRsfcutx9tG/5fZLCv9m6UCw1aS+u4uK/vXjv1ctG/FdMvaWg==", - "requires": { - "tslib": "^1.9.0" - } - }, - "@ngx-translate/http-loader": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@ngx-translate/http-loader/-/http-loader-4.0.0.tgz", - "integrity": "sha512-x8LumqydWD7eX9yQTAVeoCM9gFUIGVTUjZqbxdAUavAA3qVnk9wCQux7iHLPXpydl8vyQmLoPQR+fFU+DUDOMA==", - "requires": { - "tslib": "^1.9.0" - } - }, - "@nodelib/fs.stat": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-1.1.3.tgz", - "integrity": "sha512-shAmDyaQC4H92APFoIaVDHCx5bStIocgvbwQyxPRrbUY20V1EYTbSDchWbuwlMG3V17cprZhA6+78JfB+3DTPw==", - "dev": true - }, - "@samverschueren/stream-to-observable": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@samverschueren/stream-to-observable/-/stream-to-observable-0.3.0.tgz", - "integrity": "sha512-MI4Xx6LHs4Webyvi6EbspgyAb4D2Q2VtnCQ1blOJcoLS6mVa8lNN2rkIy1CVxfTUpoyIbCTkXES1rLXztFD1lg==", - "dev": true, - "requires": { - "any-observable": "^0.3.0" - } - }, - "@schematics/angular": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/@schematics/angular/-/angular-7.3.1.tgz", - "integrity": "sha512-0Ne8APPlTAjKg5CSZqluwCuW/5yPjr3ALCWzqwPxN0suE745usThtasBmqrjw0RMIt8nRqRgtg54Z7lCPO9ZFg==", - "dev": true, - "requires": { - "@angular-devkit/core": "7.3.1", - "@angular-devkit/schematics": "7.3.1", - "typescript": "3.2.4" - } - }, - "@schematics/update": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/@schematics/update/-/update-0.13.1.tgz", - "integrity": "sha512-EHOqolT/d/jRGuVTCUESLpk8JNpuaPlsVHfeK7Kdp/t0wSEnmtOelZX4+leS25lGXDaDUF3138ntjrZR4n6bGw==", - "dev": true, - "requires": { - "@angular-devkit/core": "7.3.1", - "@angular-devkit/schematics": "7.3.1", - "@yarnpkg/lockfile": "1.1.0", - "ini": "1.3.5", - "pacote": "9.4.0", - "rxjs": "6.3.3", - "semver": "5.6.0", - "semver-intersect": "1.4.0" - }, - "dependencies": { - "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", - "dev": true, - "requires": { - "tslib": "^1.9.0" - } - } - } - }, - "@types/babel__core": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.1.0.tgz", - "integrity": "sha512-wJTeJRt7BToFx3USrCDs2BhEi4ijBInTQjOIukj6a/5tEkwpFMVZ+1ppgmE+Q/FQyc5P/VWUbx7I9NELrKruHA==", - "dev": true, - "requires": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" - } - }, - "@types/babel__generator": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.0.2.tgz", - "integrity": "sha512-NHcOfab3Zw4q5sEE2COkpfXjoE7o+PmqD9DQW4koUT3roNxwziUdXGnRndMat/LJNUtePwn1TlP4do3uoe3KZQ==", - "dev": true, - "requires": { - "@babel/types": "^7.0.0" - } - }, - "@types/babel__template": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.0.2.tgz", - "integrity": "sha512-/K6zCpeW7Imzgab2bLkLEbz0+1JlFSrUMdw7KoIIu+IUdu51GWaBZpd3y1VXGVXzynvGa4DaIaxNZHiON3GXUg==", - "dev": true, - "requires": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "@types/babel__traverse": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.0.6.tgz", - "integrity": "sha512-XYVgHF2sQ0YblLRMLNPB3CkFMewzFmlDsH/TneZFHUXDlABQgh88uOxuez7ZcXxayLFrqLwtDH1t+FmlFwNZxw==", - "dev": true, - "requires": { - "@babel/types": "^7.3.0" - } - }, - "@types/istanbul-lib-coverage": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-1.1.0.tgz", - "integrity": "sha512-ohkhb9LehJy+PA40rDtGAji61NCgdtKLAlFoYp4cnuuQEswwdK3vz9SOIkkyc3wrk8dzjphQApNs56yyXLStaQ==", - "dev": true - }, - "@types/jest": { - "version": "24.0.0", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-24.0.0.tgz", - "integrity": "sha512-kOafJnUTnMd7/OfEO/x3I47EHswNjn+dbz9qk3mtonr1RvKT+1FGVxnxAx08I9K8Tl7j9hpoJRE7OCf+t10fng==", - "dev": true - }, - "@types/node": { - "version": "10.12.24", - "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.24.tgz", - "integrity": "sha512-GWWbvt+z9G5otRBW8rssOFgRY87J9N/qbhqfjMZ+gUuL6zoL+Hm6gP/8qQBG4jjimqdaNLCehcVapZ/Fs2WjCQ==", - "dev": true - }, - "@types/q": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/@types/q/-/q-1.5.2.tgz", - "integrity": "sha512-ce5d3q03Ex0sy4R14722Rmt6MT07Ua+k4FwDfdcToYJcMKNtRVQvJ6JCAPdAmAnbRb6CsX6aYb9m96NGod9uTw==", - "dev": true - }, - "@types/stack-utils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-1.0.1.tgz", - "integrity": "sha512-l42BggppR6zLmpfU6fq9HEa2oGPEI8yrSPL3GITjfRInppYFahObbIQOQK3UGxEnyQpltZLaPe75046NOZQikw==", - "dev": true - }, - "@types/yargs": { - "version": "12.0.10", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-12.0.10.tgz", - "integrity": "sha512-WsVzTPshvCSbHThUduGGxbmnwcpkgSctHGHTqzWyFg4lYAuV5qXlyFPOsP3OWqCINfmg/8VXP+zJaa4OxEsBQQ==", - "dev": true - }, - "@webassemblyjs/ast": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.7.11.tgz", - "integrity": "sha512-ZEzy4vjvTzScC+SH8RBssQUawpaInUdMTYwYYLh54/s8TuT0gBLuyUnppKsVyZEi876VmmStKsUs28UxPgdvrA==", - "dev": true, - "requires": { - "@webassemblyjs/helper-module-context": "1.7.11", - "@webassemblyjs/helper-wasm-bytecode": "1.7.11", - "@webassemblyjs/wast-parser": "1.7.11" - } - }, - "@webassemblyjs/floating-point-hex-parser": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.7.11.tgz", - "integrity": "sha512-zY8dSNyYcgzNRNT666/zOoAyImshm3ycKdoLsyDw/Bwo6+/uktb7p4xyApuef1dwEBo/U/SYQzbGBvV+nru2Xg==", - "dev": true - }, - "@webassemblyjs/helper-api-error": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.7.11.tgz", - "integrity": "sha512-7r1qXLmiglC+wPNkGuXCvkmalyEstKVwcueZRP2GNC2PAvxbLYwLLPr14rcdJaE4UtHxQKfFkuDFuv91ipqvXg==", - "dev": true - }, - "@webassemblyjs/helper-buffer": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.7.11.tgz", - "integrity": "sha512-MynuervdylPPh3ix+mKZloTcL06P8tenNH3sx6s0qE8SLR6DdwnfgA7Hc9NSYeob2jrW5Vql6GVlsQzKQCa13w==", - "dev": true - }, - "@webassemblyjs/helper-code-frame": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-code-frame/-/helper-code-frame-1.7.11.tgz", - "integrity": "sha512-T8ESC9KMXFTXA5urJcyor5cn6qWeZ4/zLPyWeEXZ03hj/x9weSokGNkVCdnhSabKGYWxElSdgJ+sFa9G/RdHNw==", - "dev": true, - "requires": { - "@webassemblyjs/wast-printer": "1.7.11" - } - }, - "@webassemblyjs/helper-fsm": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-fsm/-/helper-fsm-1.7.11.tgz", - "integrity": "sha512-nsAQWNP1+8Z6tkzdYlXT0kxfa2Z1tRTARd8wYnc/e3Zv3VydVVnaeePgqUzFrpkGUyhUUxOl5ML7f1NuT+gC0A==", - "dev": true - }, - "@webassemblyjs/helper-module-context": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-module-context/-/helper-module-context-1.7.11.tgz", - "integrity": "sha512-JxfD5DX8Ygq4PvXDucq0M+sbUFA7BJAv/GGl9ITovqE+idGX+J3QSzJYz+LwQmL7fC3Rs+utvWoJxDb6pmC0qg==", - "dev": true - }, - "@webassemblyjs/helper-wasm-bytecode": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.7.11.tgz", - "integrity": "sha512-cMXeVS9rhoXsI9LLL4tJxBgVD/KMOKXuFqYb5oCJ/opScWpkCMEz9EJtkonaNcnLv2R3K5jIeS4TRj/drde1JQ==", - "dev": true - }, - "@webassemblyjs/helper-wasm-section": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.7.11.tgz", - "integrity": "sha512-8ZRY5iZbZdtNFE5UFunB8mmBEAbSI3guwbrsCl4fWdfRiAcvqQpeqd5KHhSWLL5wuxo53zcaGZDBU64qgn4I4Q==", - "dev": true, - "requires": { - "@webassemblyjs/ast": "1.7.11", - "@webassemblyjs/helper-buffer": "1.7.11", - "@webassemblyjs/helper-wasm-bytecode": "1.7.11", - "@webassemblyjs/wasm-gen": "1.7.11" - } - }, - "@webassemblyjs/ieee754": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.7.11.tgz", - "integrity": "sha512-Mmqx/cS68K1tSrvRLtaV/Lp3NZWzXtOHUW2IvDvl2sihAwJh4ACE0eL6A8FvMyDG9abes3saB6dMimLOs+HMoQ==", - "dev": true, - "requires": { - "@xtuc/ieee754": "^1.2.0" - } - }, - "@webassemblyjs/leb128": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.7.11.tgz", - "integrity": "sha512-vuGmgZjjp3zjcerQg+JA+tGOncOnJLWVkt8Aze5eWQLwTQGNgVLcyOTqgSCxWTR4J42ijHbBxnuRaL1Rv7XMdw==", - "dev": true, - "requires": { - "@xtuc/long": "4.2.1" - } - }, - "@webassemblyjs/utf8": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.7.11.tgz", - "integrity": "sha512-C6GFkc7aErQIAH+BMrIdVSmW+6HSe20wg57HEC1uqJP8E/xpMjXqQUxkQw07MhNDSDcGpxI9G5JSNOQCqJk4sA==", - "dev": true - }, - "@webassemblyjs/wasm-edit": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.7.11.tgz", - "integrity": "sha512-FUd97guNGsCZQgeTPKdgxJhBXkUbMTY6hFPf2Y4OedXd48H97J+sOY2Ltaq6WGVpIH8o/TGOVNiVz/SbpEMJGg==", - "dev": true, - "requires": { - "@webassemblyjs/ast": "1.7.11", - "@webassemblyjs/helper-buffer": "1.7.11", - "@webassemblyjs/helper-wasm-bytecode": "1.7.11", - "@webassemblyjs/helper-wasm-section": "1.7.11", - "@webassemblyjs/wasm-gen": "1.7.11", - "@webassemblyjs/wasm-opt": "1.7.11", - "@webassemblyjs/wasm-parser": "1.7.11", - "@webassemblyjs/wast-printer": "1.7.11" - } - }, - "@webassemblyjs/wasm-gen": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.7.11.tgz", - "integrity": "sha512-U/KDYp7fgAZX5KPfq4NOupK/BmhDc5Kjy2GIqstMhvvdJRcER/kUsMThpWeRP8BMn4LXaKhSTggIJPOeYHwISA==", - "dev": true, - "requires": { - "@webassemblyjs/ast": "1.7.11", - "@webassemblyjs/helper-wasm-bytecode": "1.7.11", - "@webassemblyjs/ieee754": "1.7.11", - "@webassemblyjs/leb128": "1.7.11", - "@webassemblyjs/utf8": "1.7.11" - } - }, - "@webassemblyjs/wasm-opt": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.7.11.tgz", - "integrity": "sha512-XynkOwQyiRidh0GLua7SkeHvAPXQV/RxsUeERILmAInZegApOUAIJfRuPYe2F7RcjOC9tW3Cb9juPvAC/sCqvg==", - "dev": true, - "requires": { - "@webassemblyjs/ast": "1.7.11", - "@webassemblyjs/helper-buffer": "1.7.11", - "@webassemblyjs/wasm-gen": "1.7.11", - "@webassemblyjs/wasm-parser": "1.7.11" - } - }, - "@webassemblyjs/wasm-parser": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.7.11.tgz", - "integrity": "sha512-6lmXRTrrZjYD8Ng8xRyvyXQJYUQKYSXhJqXOBLw24rdiXsHAOlvw5PhesjdcaMadU/pyPQOJ5dHreMjBxwnQKg==", - "dev": true, - "requires": { - "@webassemblyjs/ast": "1.7.11", - "@webassemblyjs/helper-api-error": "1.7.11", - "@webassemblyjs/helper-wasm-bytecode": "1.7.11", - "@webassemblyjs/ieee754": "1.7.11", - "@webassemblyjs/leb128": "1.7.11", - "@webassemblyjs/utf8": "1.7.11" - } - }, - "@webassemblyjs/wast-parser": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-parser/-/wast-parser-1.7.11.tgz", - "integrity": "sha512-lEyVCg2np15tS+dm7+JJTNhNWq9yTZvi3qEhAIIOaofcYlUp0UR5/tVqOwa/gXYr3gjwSZqw+/lS9dscyLelbQ==", - "dev": true, - "requires": { - "@webassemblyjs/ast": "1.7.11", - "@webassemblyjs/floating-point-hex-parser": "1.7.11", - "@webassemblyjs/helper-api-error": "1.7.11", - "@webassemblyjs/helper-code-frame": "1.7.11", - "@webassemblyjs/helper-fsm": "1.7.11", - "@xtuc/long": "4.2.1" - } - }, - "@webassemblyjs/wast-printer": { - "version": "1.7.11", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.7.11.tgz", - "integrity": "sha512-m5vkAsuJ32QpkdkDOUPGSltrg8Cuk3KBx4YrmAGQwCZPRdUHXxG4phIOuuycLemHFr74sWL9Wthqss4fzdzSwg==", - "dev": true, - "requires": { - "@webassemblyjs/ast": "1.7.11", - "@webassemblyjs/wast-parser": "1.7.11", - "@xtuc/long": "4.2.1" - } - }, - "@xtuc/ieee754": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", - "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", - "dev": true - }, - "@xtuc/long": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.1.tgz", - "integrity": "sha512-FZdkNBDqBRHKQ2MEbSC17xnPFOhZxeJ2YGSfr2BKf3sujG49Qe3bB+rGCwQfIaA7WHnGeGkSijX4FuBCdrzW/g==", - "dev": true - }, - "@yarnpkg/lockfile": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz", - "integrity": "sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ==", - "dev": true - }, - "JSONStream": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.3.5.tgz", - "integrity": "sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==", - "dev": true, - "requires": { - "jsonparse": "^1.2.0", - "through": ">=2.2.7 <3" - } - }, - "abab": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.0.tgz", - "integrity": "sha512-sY5AXXVZv4Y1VACTtR11UJCPHHudgY5i26Qj5TypE6DKlIApbwb5uqhXcJ5UUGbvZNRh7EeIoW+LrJumBsKp7w==", - "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.3", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.3.tgz", - "integrity": "sha512-T/zvzYRfbVojPWahDsE5evJdHb3oJoQfFbsrKM7w5Zcs++Tr257tia3BmMP8XYVjp1S9RZXQMh7gao96BlqZOw==", - "dev": true - }, - "acorn-dynamic-import": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-4.0.0.tgz", - "integrity": "sha512-d3OEjQV4ROpoflsnUA8HozoIR504TFxNivYEUi6uwz0IYhBkTDXGuWlNdMtybRt3nqVx/L6XqMt0FxkXuWKZhw==", - "dev": true - }, - "acorn-globals": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-4.3.0.tgz", - "integrity": "sha512-hMtHj3s5RnuhvHPowpBYvJVj3rAar82JiDQHvGs1zO0l10ocX/xEdBShNHTJaboucJUsScghp74pH3s7EnHHQw==", - "dev": true, - "requires": { - "acorn": "^6.0.1", - "acorn-walk": "^6.0.1" - }, - "dependencies": { - "acorn": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz", - "integrity": "sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==", - "dev": true - } - } - }, - "acorn-walk": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-6.1.1.tgz", - "integrity": "sha512-OtUw6JUTgxA2QoqqmrmQ7F2NYqiBPi/L2jqHyFtllhOUvXYQXf0Z1CYUinIfyT4bTCGmrA7gX9FvHA81uzCoVw==", - "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" - } - }, - "agentkeepalive": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-3.5.2.tgz", - "integrity": "sha512-e0L/HNe6qkQ7H19kTlRRqUibEAwDK5AFk6y3PtMsuut2VAH6+Q4xZml1tNDJD7kSAyqmbG/K08K5WEJYtUrSlQ==", - "dev": true, - "requires": { - "humanize-ms": "^1.2.1" - } - }, - "ajv": { - "version": "6.7.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.7.0.tgz", - "integrity": "sha512-RZXPviBTtfmtka9n9sy1N5M5b82CbxWIR6HIis4s3WQTXDJamc/0gpCWNGz6EWdWp4DOfjzJfhz/AS9zVPjjWg==", - "dev": true, - "requires": { - "fast-deep-equal": "^2.0.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - } - }, - "ajv-errors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/ajv-errors/-/ajv-errors-1.0.1.tgz", - "integrity": "sha512-DCRfO/4nQ+89p/RK43i8Ezd41EqdGIU4ld7nGF8OQ14oc/we5rEntLCUa7+jrn3nn83BosfwZA0wb4pon2o8iQ==", - "dev": true - }, - "ajv-keywords": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.4.0.tgz", - "integrity": "sha512-aUjdRFISbuFOl0EIZc+9e4FfZp0bDZgAdOOf30bJmw8VM9v84SHyVyxDfbWxpGYbdZD/9XoKxfHVNmxPkhwyGw==", - "dev": true - }, - "alphanum-sort": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/alphanum-sort/-/alphanum-sort-1.0.2.tgz", - "integrity": "sha1-l6ERlkmyEa0zaR2fn0hqjsn74KM=", - "dev": true - }, - "amdefine": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz", - "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=", - "dev": true - }, - "angular-router-loader": { - "version": "0.8.5", - "resolved": "https://registry.npmjs.org/angular-router-loader/-/angular-router-loader-0.8.5.tgz", - "integrity": "sha512-8wggCTKGgzB1o8co3Wvj+p9pKN7T7q3C477lEz3NLjvPVzUti8rv9i45Di+4aO/k+HvzGh3s8QdNlXU2Bl4avQ==", - "dev": true, - "requires": { - "loader-utils": "^1.0.2" - } - }, - "angular2-template-loader": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/angular2-template-loader/-/angular2-template-loader-0.6.2.tgz", - "integrity": "sha1-wNROkP/w+sleiyPwQ6zaf9HFHXw=", - "dev": true, - "requires": { - "loader-utils": "^0.2.15" - }, - "dependencies": { - "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 - }, - "json5": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", - "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=", - "dev": true - }, - "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" - } - } - } - }, - "ansi": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/ansi/-/ansi-0.3.1.tgz", - "integrity": "sha1-DELU+xcWDVqa8eSEus4cZpIsGyE=", - "dev": true - }, - "ansi-colors": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-3.2.4.tgz", - "integrity": "sha512-hHUXGagefjN2iRrID63xckIvotOXOojhQKWIPUZ4mNUZ9nLZW+7FMNoE1lOkEhNWYsx/7ysGIuJYCiMAA9FnrA==", - "dev": true - }, - "ansi-cyan": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/ansi-cyan/-/ansi-cyan-0.1.1.tgz", - "integrity": "sha1-U4rlKK+JgvKK4w2G8vF0VtJgmHM=", - "dev": true, - "requires": { - "ansi-wrap": "0.1.0" - } - }, - "ansi-escapes": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-1.4.0.tgz", - "integrity": "sha1-06ioOzGapneTZisT52HHkRQiMG4=" - }, - "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-red": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/ansi-red/-/ansi-red-0.1.1.tgz", - "integrity": "sha1-jGOPnRCAgAo1PJwoyKgcpHBdlGw=", - "dev": true, - "requires": { - "ansi-wrap": "0.1.0" - } - }, - "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": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "ansi-wrap": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/ansi-wrap/-/ansi-wrap-0.1.0.tgz", - "integrity": "sha1-qCJQ3bABXponyoLoLqYDu/pF768=", - "dev": true - }, - "any-observable": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/any-observable/-/any-observable-0.3.0.tgz", - "integrity": "sha512-/FQM1EDkTsf63Ub2C6O7GuYFDsSXUwsaZDurV0np41ocwq0jthUAYCmhBX9f+KwlaCgIuWyr/4WlUQUBfKfZog==", - "dev": true - }, - "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" - }, - "dependencies": { - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", - "dev": true - } - } - }, - "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-differ": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz", - "integrity": "sha1-7/UuN1gknTO+QCuLuOVkuytdQDE=", - "dev": true - }, - "array-equal": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/array-equal/-/array-equal-1.0.0.tgz", - "integrity": "sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM=", - "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.2", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-2.1.2.tgz", - "integrity": "sha512-hNfzcOV8W4NdualtqBFPyVO+54DSJuZGY9qT4pRroB6S9e3iiido2ISIC5h9R2sPJ8H3FHCIiEnsv1lPXO3KtQ==", - "dev": true - }, - "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.7", - "resolved": "https://registry.npmjs.org/arraybuffer.slice/-/arraybuffer.slice-0.0.7.tgz", - "integrity": "sha512-wGUIVQXuehL5TCqQun8OW81jGzAWycqzFF8lFp+GOM5BXLYj3bKNsYC4daB7n6XjCqxQA/qgTJ+8ANR3acjrog==", - "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 - }, - "asn1": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", - "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", - "dev": true, - "requires": { - "safer-buffer": "~2.1.0" - } - }, - "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 - }, - "ast-types": { - "version": "0.9.6", - "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.9.6.tgz", - "integrity": "sha1-ECyenpAF0+fjgpvwxPok7oYu6bk=", - "dev": true - }, - "astral-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", - "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", - "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.2", - "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.2.tgz", - "integrity": "sha512-6xrbvN0MOBKSJDdonmSSz2OwFSgxRaVtBDes26mj9KIGtDo+g9xosFRSC+i1gQh2oAN/tQ62AI/pGZGQjVOiRg==", - "dev": true - }, - "async-each-series": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/async-each-series/-/async-each-series-0.1.1.tgz", - "integrity": "sha1-dhfBkXQB/Yykooqtzj266Yr+tDI=", - "dev": true - }, - "async-limiter": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", - "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==", - "dev": 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.2", - "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", - "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", - "dev": true - }, - "autoprefixer": { - "version": "9.4.7", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-9.4.7.tgz", - "integrity": "sha512-qS5wW6aXHkm53Y4z73tFGsUhmZu4aMPV9iHXYlF0c/wxjknXNHuj/1cIQb+6YH692DbJGGWcckAXX+VxKvahMA==", - "dev": true, - "requires": { - "browserslist": "^4.4.1", - "caniuse-lite": "^1.0.30000932", - "normalize-range": "^0.1.2", - "num2fraction": "^1.2.2", - "postcss": "^7.0.14", - "postcss-value-parser": "^3.3.1" - } - }, - "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.8.0", - "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz", - "integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ==", - "dev": true - }, - "axios": { - "version": "0.17.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.17.1.tgz", - "integrity": "sha1-LY4+XQvb1zJ/kbyBT1xXZg+Bgk0=", - "dev": true, - "requires": { - "follow-redirects": "^1.2.5", - "is-buffer": "^1.1.5" - } - }, - "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" - } - }, - "babel-extract-comments": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/babel-extract-comments/-/babel-extract-comments-1.0.0.tgz", - "integrity": "sha512-qWWzi4TlddohA91bFwgt6zO/J0X+io7Qp184Fw0m2JYRSTZnJbFR8+07KmzudHCZgOiKRCrjhylwv9Xd8gfhVQ==", - "dev": true, - "requires": { - "babylon": "^6.18.0" - } - }, - "babel-jest": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-24.5.0.tgz", - "integrity": "sha512-0fKCXyRwxFTJL0UXDJiT2xYxO9Lu2vBd9n+cC+eDjESzcVG3s2DRGAxbzJX21fceB1WYoBjAh8pQ83dKcl003g==", - "dev": true, - "requires": { - "@jest/transform": "^24.5.0", - "@jest/types": "^24.5.0", - "@types/babel__core": "^7.1.0", - "babel-plugin-istanbul": "^5.1.0", - "babel-preset-jest": "^24.3.0", - "chalk": "^2.4.2", - "slash": "^2.0.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "slash": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", - "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "babel-plugin-istanbul": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-5.1.1.tgz", - "integrity": "sha512-RNNVv2lsHAXJQsEJ5jonQwrJVWK8AcZpG1oxhnjCUaAjL7xahYLANhPUZbzEQHjKy1NMYUwn+0NPKQc8iSY4xQ==", - "dev": true, - "requires": { - "find-up": "^3.0.0", - "istanbul-lib-instrument": "^3.0.0", - "test-exclude": "^5.0.0" - }, - "dependencies": { - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "p-limit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", - "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.1.0.tgz", - "integrity": "sha512-H2RyIJ7+A3rjkwKC2l5GGtU4H1vkxKCAGsWasNVd0Set+6i4znxbWy6/j16YDPJDWxhsgZiKAstMEP8wCdSpjA==", - "dev": true - } - } - }, - "babel-plugin-jest-hoist": { - "version": "24.3.0", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-24.3.0.tgz", - "integrity": "sha512-nWh4N1mVH55Tzhx2isvUN5ebM5CDUvIpXPZYMRazQughie/EqGnbR+czzoQlhUmJG9pPJmYDRhvocotb2THl1w==", - "dev": true, - "requires": { - "@types/babel__traverse": "^7.0.6" - } - }, - "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=", - "dev": true - }, - "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=", - "dev": true, - "requires": { - "babel-plugin-syntax-object-rest-spread": "^6.8.0", - "babel-runtime": "^6.26.0" - } - }, - "babel-polyfill": { - "version": "6.23.0", - "resolved": "https://registry.npmjs.org/babel-polyfill/-/babel-polyfill-6.23.0.tgz", - "integrity": "sha1-g2TKYt+Or7gwSZ9pkXdGbDsDSZ0=", - "requires": { - "babel-runtime": "^6.22.0", - "core-js": "^2.4.0", - "regenerator-runtime": "^0.10.0" - } - }, - "babel-preset-jest": { - "version": "24.3.0", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-24.3.0.tgz", - "integrity": "sha512-VGTV2QYBa/Kn3WCOKdfS31j9qomaXSgJqi65B6o05/1GsJyj9LVhSljM9ro4S+IBGj/ENhNBuH9bpqzztKAQSw==", - "dev": true, - "requires": { - "@babel/plugin-syntax-object-rest-spread": "^7.0.0", - "babel-plugin-jest-hoist": "^24.3.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=", - "requires": { - "core-js": "^2.4.0", - "regenerator-runtime": "^0.11.0" - }, - "dependencies": { - "regenerator-runtime": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", - "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==" - } - } - }, - "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" - } - } - } - }, - "base62": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/base62/-/base62-1.2.8.tgz", - "integrity": "sha512-V6YHUbjLxN1ymqNLb1DPHoU1CpfdL7d2YTIp5W3U4hhoG4hhxNmsFDs66M9EXxBiSEke5Bt5dwdfMwwZF70iLA==", - "dev": true - }, - "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, - "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": "5.2.2", - "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", - "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==", - "dev": true - }, - "binary-extensions": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.13.0.tgz", - "integrity": "sha512-EgmjVLMn22z7eGGv3kcnHwSnJXmFHjISTY9E/S5lIcTD3Oxw05QTcBLNkJFzcb3cNueUdF/IN4U+d78V0zO8Hw==", - "dev": true - }, - "binaryextensions": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/binaryextensions/-/binaryextensions-2.1.2.tgz", - "integrity": "sha512-xVNN69YGDghOqCCtA6FI7avYrr02mTJjOgB0/f1VPD3pJC8QEvjTKWc4epDx8AqxxA75NI0QpVM2gPJXUbE4Tg==", - "dev": true - }, - "blob": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/blob/-/blob-0.0.5.tgz", - "integrity": "sha512-gaqbzQPqOoamawKg0LGVd7SzLgXS+JH61oWprSLH+P+abTczqJbhTR8CmJ2u9/bUYNmHTGJx/UEmn6doAvvuig==", - "dev": true - }, - "bluebird": { - "version": "3.5.3", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.3.tgz", - "integrity": "sha512-/qKPUQlaW1OyR51WeCPBvRnAlnZFUJkCSG5HzGnuIqhgyJtF+T94lFnn33eiazjRm2LAHVy2guNnaq48X9SJuw==", - "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.3", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.3.tgz", - "integrity": "sha1-WykhmP/dVTs6DyDe0FkrlWlVyLQ=", - "dev": true, - "requires": { - "bytes": "3.0.0", - "content-type": "~1.0.4", - "debug": "2.6.9", - "depd": "~1.1.2", - "http-errors": "~1.6.3", - "iconv-lite": "0.4.23", - "on-finished": "~2.3.0", - "qs": "6.5.2", - "raw-body": "2.3.3", - "type-is": "~1.6.16" - }, - "dependencies": { - "iconv-lite": { - "version": "0.4.23", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.23.tgz", - "integrity": "sha512-neyTUVFtahjf0mB3dZT77u+8O0QB89jFdnBkd5P1JgYPbPaia3gXXOVL2fq8VyU2gMMD7SaN7QukTB/pmXYvDA==", - "dev": true, - "requires": { - "safer-buffer": ">= 2.1.2 < 3" - } - }, - "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 - } - } - }, - "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 - }, - "bootstrap": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-4.2.1.tgz", - "integrity": "sha512-tt/7vIv3Gm2mnd/WeDx36nfGGHleil0Wg8IeB7eMrVkY0fZ5iTaBisSh8oNANc2IBsCc6vCgCNTIM/IEN0+50Q==" - }, - "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 - }, - "browser-process-hrtime": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/browser-process-hrtime/-/browser-process-hrtime-0.1.3.tgz", - "integrity": "sha512-bRFnI4NnjO6cnyLmOV/7PVoDEMJChlcfN0z4s1YMBY989/SvlfMI1lgCnkFUs53e9gQF+w7qu7XdllSTiSl8Aw==", - "dev": true - }, - "browser-resolve": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/browser-resolve/-/browser-resolve-1.11.3.tgz", - "integrity": "sha512-exDi1BYWB/6raKHmDTCicQfTkqwN5fioMFV4j8BsfMU4R2DK/QfZfK7kOVkmWCNANf0snkBzqGqAJBao9gZMdQ==", - "dev": true, - "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=", - "dev": true - } - } - }, - "browser-sync": { - "version": "2.26.3", - "resolved": "https://registry.npmjs.org/browser-sync/-/browser-sync-2.26.3.tgz", - "integrity": "sha512-VLzpjCA4uXqfzkwqWtMM6hvPm2PNHp2RcmzBXcbi6C9WpkUhhFb8SVAr4CFrCsFxDg+oY6HalOjn8F+egyvhag==", - "dev": true, - "requires": { - "browser-sync-client": "^2.26.2", - "browser-sync-ui": "^2.26.2", - "bs-recipes": "1.3.4", - "bs-snippet-injector": "^2.0.1", - "chokidar": "^2.0.4", - "connect": "3.6.6", - "connect-history-api-fallback": "^1", - "dev-ip": "^1.0.1", - "easy-extender": "^2.3.4", - "eazy-logger": "^3", - "etag": "^1.8.1", - "fresh": "^0.5.2", - "fs-extra": "3.0.1", - "http-proxy": "1.15.2", - "immutable": "^3", - "localtunnel": "1.9.1", - "micromatch": "2.3.11", - "opn": "5.3.0", - "portscanner": "2.1.1", - "qs": "6.2.3", - "raw-body": "^2.3.2", - "resp-modifier": "6.0.2", - "rx": "4.1.0", - "send": "0.16.2", - "serve-index": "1.9.1", - "serve-static": "1.13.2", - "server-destroy": "1.0.1", - "socket.io": "2.1.1", - "ua-parser-js": "0.7.17", - "yargs": "6.4.0" - }, - "dependencies": { - "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" - } - }, - "camelcase": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", - "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=", - "dev": true - }, - "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" - } - }, - "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" - } - }, - "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-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": "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" - } - }, - "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" - } - }, - "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" - } - }, - "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" - } - }, - "os-locale": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz", - "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", - "dev": true, - "requires": { - "lcid": "^1.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" - } - }, - "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" - } - }, - "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" - } - }, - "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" - } - }, - "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" - } - }, - "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" - } - }, - "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 - }, - "y18n": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz", - "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=", - "dev": true - }, - "yargs": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-6.4.0.tgz", - "integrity": "sha1-gW4ahm1VmMzzTlWW3c4i2S2kkNQ=", - "dev": 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", - "window-size": "^0.2.0", - "y18n": "^3.2.1", - "yargs-parser": "^4.1.0" - } - }, - "yargs-parser": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-4.2.1.tgz", - "integrity": "sha1-KczqwNxPA8bIe0qfIX3RjJ90hxw=", - "dev": true, - "requires": { - "camelcase": "^3.0.0" - } - } - } - }, - "browser-sync-client": { - "version": "2.26.2", - "resolved": "https://registry.npmjs.org/browser-sync-client/-/browser-sync-client-2.26.2.tgz", - "integrity": "sha512-FEuVJD41fI24HJ30XOT2RyF5WcnEtdJhhTqeyDlnMk/8Ox9MZw109rvk9pdfRWye4soZLe+xcAo9tHSMxvgAdw==", - "dev": true, - "requires": { - "etag": "1.8.1", - "fresh": "0.5.2", - "mitt": "^1.1.3", - "rxjs": "^5.5.6" - }, - "dependencies": { - "rxjs": { - "version": "5.5.12", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-5.5.12.tgz", - "integrity": "sha512-xx2itnL5sBbqeeiVgNPVuQQ1nC8Jp2WfNJhXWHmElW9YmrpS9UVnNzhP3EH3HFqexO5Tlp8GhYY+WEcqcVMvGw==", - "dev": true, - "requires": { - "symbol-observable": "1.0.1" - } - }, - "symbol-observable": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.0.1.tgz", - "integrity": "sha1-g0D8RwLDEi310iKI+IKD9RPT/dQ=", - "dev": true - } - } - }, - "browser-sync-ui": { - "version": "2.26.2", - "resolved": "https://registry.npmjs.org/browser-sync-ui/-/browser-sync-ui-2.26.2.tgz", - "integrity": "sha512-LF7GMWo8ELOE0eAlxuRCfnGQT1ZxKP9flCfGgZdXFc6BwmoqaJHlYe7MmVvykKkXjolRXTz8ztXAKGVqNwJ3EQ==", - "dev": true, - "requires": { - "async-each-series": "0.1.1", - "connect-history-api-fallback": "^1", - "immutable": "^3", - "server-destroy": "1.0.1", - "socket.io-client": "^2.0.4", - "stream-throttle": "^0.1.3" - } - }, - "browser-sync-webpack-plugin": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/browser-sync-webpack-plugin/-/browser-sync-webpack-plugin-2.2.2.tgz", - "integrity": "sha512-x92kl8LdBi4dp6YVXYqrSoDkOCOLCeBOrYSY0h9Sk1VcCDSoZC1Vc62eae6TfC2ljN4/L+aYlkzE46kirHzbgA==", - "dev": true, - "requires": { - "lodash": "^4" - } - }, - "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": "4.5.1", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.5.1.tgz", - "integrity": "sha512-/pPw5IAUyqaQXGuD5vS8tcbudyPZ241jk1W5pQBsGDfcjNQt7p8qxZhgMNuygDShte1PibLFexecWUPgmVLfrg==", - "dev": true, - "requires": { - "caniuse-lite": "^1.0.30000949", - "electron-to-chromium": "^1.3.116", - "node-releases": "^1.1.11" - } - }, - "bs-recipes": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/bs-recipes/-/bs-recipes-1.3.4.tgz", - "integrity": "sha1-DS1NSKcYyMBEdp/cT4lZLci2lYU=", - "dev": true - }, - "bs-snippet-injector": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/bs-snippet-injector/-/bs-snippet-injector-2.0.1.tgz", - "integrity": "sha1-YbU5PxH1JVntEgaTEANDtu2wTdU=", - "dev": true - }, - "bser": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/bser/-/bser-2.0.0.tgz", - "integrity": "sha1-mseNPtXZFYBP2HrLFYvHlxR6Fxk=", - "dev": true, - "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=", - "dev": true, - "requires": { - "base64-js": "^1.0.2", - "ieee754": "^1.1.4", - "isarray": "^1.0.0" - } - }, - "buffer-alloc": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/buffer-alloc/-/buffer-alloc-1.2.0.tgz", - "integrity": "sha512-CFsHQgjtW1UChdXgbyJGtnm+O/uLQeZdtbDo8mfUgYXCHSM1wgrVxXm6bSyrUuErEb+4sYVGCzASBRot7zyrow==", - "dev": true, - "requires": { - "buffer-alloc-unsafe": "^1.1.0", - "buffer-fill": "^1.0.0" - } - }, - "buffer-alloc-unsafe": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/buffer-alloc-unsafe/-/buffer-alloc-unsafe-1.1.0.tgz", - "integrity": "sha512-TEM2iMIEQdJ2yjPJoSIsldnleVaAk1oW3DBVUykyOLsEsFmEc9kn+SFFPz+gl54KQNxlDnAwCXosOS9Okx2xAg==", - "dev": true - }, - "buffer-fill": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/buffer-fill/-/buffer-fill-1.0.0.tgz", - "integrity": "sha1-+PeLdniYiO858gXNY39o5wISKyw=", - "dev": true - }, - "buffer-from": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", - "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", - "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": "11.3.2", - "resolved": "https://registry.npmjs.org/cacache/-/cacache-11.3.2.tgz", - "integrity": "sha512-E0zP4EPGDOaT2chM08Als91eYnf8Z+eH1awwwVsngUmgppfM5jjJ8l3z5vO5p5w/I3LsiXawb1sW0VY65pQABg==", - "dev": true, - "requires": { - "bluebird": "^3.5.3", - "chownr": "^1.1.1", - "figgy-pudding": "^3.5.1", - "glob": "^7.1.3", - "graceful-fs": "^4.1.15", - "lru-cache": "^5.1.1", - "mississippi": "^3.0.0", - "mkdirp": "^0.5.1", - "move-concurrently": "^1.0.1", - "promise-inflight": "^1.0.1", - "rimraf": "^2.6.2", - "ssri": "^6.0.1", - "unique-filename": "^1.1.1", - "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": "2.0.1", - "resolved": "https://registry.npmjs.org/cache-loader/-/cache-loader-2.0.1.tgz", - "integrity": "sha512-V99T3FOynmGx26Zom+JrVBytLBsmUCzVG2/4NnUKgvXN4bEV42R1ERl1IyiH/cvFIDA1Ytq2lPZ9tXDSahcQpQ==", - "dev": true, - "requires": { - "loader-utils": "^1.1.0", - "mkdirp": "^0.5.1", - "neo-async": "^2.6.0", - "normalize-path": "^3.0.0", - "schema-utils": "^1.0.0" - }, - "dependencies": { - "normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true - } - } - }, - "call-me-maybe": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.1.tgz", - "integrity": "sha1-JtII6onje1y95gJQoV8DHBak1ms=", - "dev": true - }, - "caller-callsite": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/caller-callsite/-/caller-callsite-2.0.0.tgz", - "integrity": "sha1-hH4PzgoiN1CpoCfFSzNzGtMVQTQ=", - "dev": true, - "requires": { - "callsites": "^2.0.0" - } - }, - "caller-path": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-2.0.0.tgz", - "integrity": "sha1-Ro+DBE42mrIBD6xfBs7uFbsssfQ=", - "dev": true, - "requires": { - "caller-callsite": "^2.0.0" - } - }, - "callsite": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/callsite/-/callsite-1.0.0.tgz", - "integrity": "sha1-KAOY5dZkvXQDi28JBRU+borxvCA=", - "dev": true - }, - "callsites": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-2.0.0.tgz", - "integrity": "sha1-BuuE8A7qQT2oav/vrL/7Ngk7PFA=", - "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": "4.1.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", - "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=", - "dev": true - }, - "camelcase-keys": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-4.2.0.tgz", - "integrity": "sha1-oqpfsa9oh1glnDLBQUJteJI7m3c=", - "dev": true, - "requires": { - "camelcase": "^4.1.0", - "map-obj": "^2.0.0", - "quick-lru": "^1.0.0" - } - }, - "caniuse-api": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/caniuse-api/-/caniuse-api-3.0.0.tgz", - "integrity": "sha512-bsTwuIg/BZZK/vreVTYYbSWoe2F+71P7K5QGEX+pT250DZbfU1MQ5prOKpPR+LL6uWKK3KMwMCAS74QB3Um1uw==", - "dev": true, - "requires": { - "browserslist": "^4.0.0", - "caniuse-lite": "^1.0.0", - "lodash.memoize": "^4.1.2", - "lodash.uniq": "^4.5.0" - } - }, - "caniuse-lite": { - "version": "1.0.30000950", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30000950.tgz", - "integrity": "sha512-Cs+4U9T0okW2ftBsCIHuEYXXkki7mjXmjCh4c6PzYShk04qDEr76/iC7KwhLoWoY65wcra1XOsRD+S7BptEb5A==", - "dev": true - }, - "canonical-path": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/canonical-path/-/canonical-path-1.0.0.tgz", - "integrity": "sha512-feylzsbDxi1gPZ1IjystzIQZagYYLvfKrSuygUCgf7z6x790VEzze5QEkdSV1U58RA7Hi0+v6fv4K54atOzATg==", - "dev": true - }, - "capture-exit": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/capture-exit/-/capture-exit-2.0.0.tgz", - "integrity": "sha512-PiT/hQmTonHhl/HFGN+Lx3JJUznrVYJ3+AQsnthneZbvW7x+f08Tk7yLJTLEOUvBTbduLeeBkxEaYXUOUrRq6g==", - "dev": true, - "requires": { - "rsvp": "^4.8.4" - } - }, - "caseless": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", - "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", - "dev": true - }, - "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" - } - }, - "chardet": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.4.2.tgz", - "integrity": "sha1-tUc7M9yXxCTl2Y3IfVXU2KKci/I=" - }, - "chevrotain": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-4.2.0.tgz", - "integrity": "sha512-uiwhNpkudwrk3rHxKKfrvsWNe4SBDjnswbF2FDqDfrqsfYr4gY0Yl1k2m9yPKR0fqfbiIP67EbgOv4e+JP+GGg==", - "dev": true, - "requires": { - "regexp-to-ast": "0.3.5" - } - }, - "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.1.1", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.1.tgz", - "integrity": "sha512-j38EvO5+LHX84jlo6h4UzmOwi0UgW61WRyPtJz4qaadK5eY3BTS5TY/S1Stc3Uk2lIM6TPevAlULiEJwie860g==", - "dev": true - }, - "chrome-trace-event": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.0.tgz", - "integrity": "sha512-xDbVgyfDTT2piup/h8dK/y4QZfJRSa73bw1WZ8b4XM1o7fsFubUVGYcE+1ANtOzJJELGpYoG2961z0Z6OAld9A==", - "dev": true, - "requires": { - "tslib": "^1.9.0" - } - }, - "ci-info": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", - "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", - "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" - } - }, - "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.2.1", - "resolved": "https://registry.npmjs.org/clean-css/-/clean-css-4.2.1.tgz", - "integrity": "sha512-4ZxI6dy4lrY6FHzfiy1aEOXgu4LIsW2MhwG0VBKdcoGoH/XLFgaHSdLTGr4O8Be6A8r3MOphEiI8Gc1n0ecf3g==", - "dev": true, - "requires": { - "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 - } - } - }, - "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-table": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/cli-table/-/cli-table-0.3.1.tgz", - "integrity": "sha1-9TsFJmqLGguTSz0IIebi3FkUriM=", - "dev": true, - "requires": { - "colors": "1.0.3" - }, - "dependencies": { - "colors": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", - "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", - "dev": true - } - } - }, - "cli-truncate": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-0.2.1.tgz", - "integrity": "sha1-nxXPuwcFAFNpIWxiasfQWrkN1XQ=", - "dev": true, - "requires": { - "slice-ansi": "0.0.4", - "string-width": "^1.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=", - "dev": true, - "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=", - "dev": true, - "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "strip-ansi": "^3.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": "3.2.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", - "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=", - "dev": true, - "requires": { - "string-width": "^1.0.1", - "strip-ansi": "^3.0.1", - "wrap-ansi": "^2.0.0" - }, - "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=", - "dev": true, - "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=", - "dev": true, - "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "strip-ansi": "^3.0.0" - } - } - } - }, - "clone": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", - "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", - "dev": true - }, - "clone-buffer": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/clone-buffer/-/clone-buffer-1.0.0.tgz", - "integrity": "sha1-4+JbIHrE5wGvch4staFnksrD3Fg=", - "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" - }, - "dependencies": { - "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" - } - } - } - }, - "clone-stats": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-0.0.1.tgz", - "integrity": "sha1-uI+UqCzzi4eR1YBG6kAprYjKmdE=", - "dev": true - }, - "cloneable-readable": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/cloneable-readable/-/cloneable-readable-1.1.2.tgz", - "integrity": "sha512-Bq6+4t+lbM8vhTs/Bef5c5AdEMtapp/iFb6+s4/Hh9MVTt8OLKH7ZOOZSCT+Ys7hsHvqv0GuMPJ1lnQJVHvxpg==", - "dev": true, - "requires": { - "inherits": "^2.0.1", - "process-nextick-args": "^2.0.0", - "readable-stream": "^2.3.5" - } - }, - "closest-file-data": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/closest-file-data/-/closest-file-data-0.1.4.tgz", - "integrity": "sha1-l1+HwTLymdJKA3W59jyj+4j3Kzo=", - "dev": true - }, - "co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", - "dev": true - }, - "coa": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/coa/-/coa-2.0.2.tgz", - "integrity": "sha512-q5/jG+YQnSy4nRTV4F7lPepBJZ8qBNJJDBuJdoejDyLXgmL7IEo+Le2JDZudFTFt7mrCqIRaSjws4ygRCTCAXA==", - "dev": true, - "requires": { - "@types/q": "^1.5.1", - "chalk": "^2.4.1", - "q": "^1.1.2" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "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.5.0", - "resolved": "https://registry.npmjs.org/codelyzer/-/codelyzer-4.5.0.tgz", - "integrity": "sha512-oO6vCkjqsVrEsmh58oNlnJkRXuA30hF8cdNAQV9DytEalDwyOFRvHMnlKFzmOStNerOmPGZU9GAHnBo4tGvtiQ==", - "dev": true, - "requires": { - "app-root-path": "^2.1.0", - "css-selector-tokenizer": "^0.7.0", - "cssauron": "^1.4.0", - "semver-dsl": "^1.0.1", - "source-map": "^0.5.7", - "sprintf-js": "^1.1.1" - }, - "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 - } - } - }, - "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": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/color/-/color-3.0.0.tgz", - "integrity": "sha512-jCpd5+s0s0t7p3pHQKpnJ0TpQKKdleP71LWcA0aqiljpiuAkOSUFN/dyH8ZwF0hRmFlrIuRhufds1QyEP9EB+w==", - "dev": true, - "requires": { - "color-convert": "^1.9.1", - "color-string": "^1.5.2" - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true - }, - "color-string": { - "version": "1.5.3", - "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.5.3.tgz", - "integrity": "sha512-dC2C5qeWoYkxki5UAXapdjqO672AM4vZuPGRQfO8b5HKuKGBbKWpITyDYN7TOFKvRW7kOgAn3746clDBMDJyQw==", - "dev": true, - "requires": { - "color-name": "^1.0.0", - "simple-swizzle": "^0.2.2" - } - }, - "colornames": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/colornames/-/colornames-1.1.1.tgz", - "integrity": "sha1-+IiQMGhcfE/54qVZ9Qd+t2qBb5Y=", - "dev": true - }, - "colors": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/colors/-/colors-1.3.3.tgz", - "integrity": "sha512-mmGt/1pZqYRjMxB1axhTo16/snVZ5krrKkcmMeVKxzECMMXoCgnvTPp10QgHfcbQZw8Dq2jMNG6je4JlWU0gWg==", - "dev": true - }, - "colorspace": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.1.tgz", - "integrity": "sha512-pI3btWyiuz7Ken0BWh9Elzsmv2bM9AhA7psXib4anUXy/orfZ/E0MbQwhSOG/9L8hLlalqrU0UhOuqxW1YjmVw==", - "dev": true, - "requires": { - "color": "3.0.x", - "text-hex": "1.0.x" - } - }, - "combined-stream": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.7.tgz", - "integrity": "sha512-brWl9y6vOB1xYPZcpZde3N9zDByXTosAeMDo4p1wzo6UMOX4vumB+TP1RZ76sfE6Md68Q0NJSrE/gbezd4Ul+w==", - "dev": true, - "requires": { - "delayed-stream": "~1.0.0" - } - }, - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==", - "dev": true - }, - "common-tags": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/common-tags/-/common-tags-1.8.0.tgz", - "integrity": "sha512-6P6g0uetGpW/sdyUy/iQQCbFF0kWVMSIVSyYz7Zgjcgh8mgw8PQzDNZeyZ5DQ2gM7LBoZPHmnjz8rUthkBG5tw==", - "dev": true - }, - "commondir": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", - "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", - "dev": true - }, - "commoner": { - "version": "0.10.8", - "resolved": "https://registry.npmjs.org/commoner/-/commoner-0.10.8.tgz", - "integrity": "sha1-NPw2cs0kOT6LtH5wyqApOBH08sU=", - "dev": true, - "requires": { - "commander": "^2.5.0", - "detective": "^4.3.1", - "glob": "^5.0.15", - "graceful-fs": "^4.1.2", - "iconv-lite": "^0.4.5", - "mkdirp": "^0.5.0", - "private": "^0.1.6", - "q": "^1.1.2", - "recast": "^0.11.17" - }, - "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" - } - } - } - }, - "compare-versions": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-3.4.0.tgz", - "integrity": "sha512-tK69D7oNXXqUW3ZNo/z7NXTEz22TCF0pTE+YF9cxvaAM9XnkLo1fV621xCLrRR6aevJlKxExkss0vWqUCUpqdg==", - "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.16", - "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.16.tgz", - "integrity": "sha512-JQfEOdnI7dASwCuSPWIeVYwc/zMsu/+tRhoUvEfXz2gxOA2DNjmG5vhtFdBlhWPPGo+RdT9S3tgc/uH5qgDiiA==", - "dev": true, - "requires": { - "mime-db": ">= 1.38.0 < 2" - } - }, - "compression": { - "version": "1.7.4", - "resolved": "https://registry.npmjs.org/compression/-/compression-1.7.4.tgz", - "integrity": "sha512-jaSIDzP9pZVS4ZfQ+TzvtiWhdpFhE2RDHz8QJkpX9SIpLq88VueF5jJw6t+6CUQcAoA6t+x89MLrWAqpfDE8iQ==", - "dev": true, - "requires": { - "accepts": "~1.3.5", - "bytes": "3.0.0", - "compressible": "~2.0.16", - "debug": "2.6.9", - "on-headers": "~1.0.2", - "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" - } - }, - "conf": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/conf/-/conf-2.0.0.tgz", - "integrity": "sha512-iCLzBsGFi8S73EANsEJZz0JnJ/e5VZef/kSaxydYZLAvw0rFNAUx5R7K5leC/CXXR2mZfXWhUvcZOO/dM2D5xg==", - "dev": true, - "requires": { - "dot-prop": "^4.1.0", - "env-paths": "^1.0.0", - "make-dir": "^1.0.0", - "pkg-up": "^2.0.0", - "write-file-atomic": "^2.3.0" - } - }, - "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" - } - }, - "connect-history-api-fallback": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/connect-history-api-fallback/-/connect-history-api-fallback-1.6.0.tgz", - "integrity": "sha512-e54B99q/OUoH64zYYRf3HBP5z24G38h5D3qXu23JGRoigpX5Ss4r9ZnDk3g0Z8uQC2x2lPaJ+UlWBc1ZWBWdLg==", - "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" - } - }, - "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.6.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz", - "integrity": "sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==", - "dev": true, - "requires": { - "safe-buffer": "~5.1.1" - } - }, - "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.6.0", - "resolved": "https://registry.npmjs.org/copy-webpack-plugin/-/copy-webpack-plugin-4.6.0.tgz", - "integrity": "sha512-Y+SQCF+0NoWQryez2zXn5J5knmr9z/9qSQt7fbL78u83rxmigOy8X5+BFn8CFSuX+nKT8gpYwJX68ekqtQt6ZA==", - "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" - }, - "dependencies": { - "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" - } - }, - "lru-cache": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", - "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", - "dev": true, - "requires": { - "pseudomap": "^1.0.2", - "yallist": "^2.1.2" - } - }, - "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" - } - }, - "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" - } - }, - "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" - } - }, - "yallist": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", - "dev": true - } - } - }, - "core-js": { - "version": "2.6.4", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.4.tgz", - "integrity": "sha512-05qQ5hXShcqGkPZpXEFLIpxayZscVD2kuMBZewxiIPPEagukO4mqgPA9CWhUvFBJfy3ODdK2p9xyHh7FTU9/7A==" - }, - "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": "5.1.0", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-5.1.0.tgz", - "integrity": "sha512-kCNPvthka8gvLtzAxQXvWo4FxqRB+ftRZyPZNuab5ngvM9Y7yw7hbEysglptLgpkGX9nAOKTBVkHUAe8xtYR6Q==", - "dev": true, - "requires": { - "import-fresh": "^2.0.0", - "is-directory": "^0.3.1", - "js-yaml": "^3.9.0", - "lodash.get": "^4.4.2", - "parse-json": "^4.0.0" - }, - "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": "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" - }, - "dependencies": { - "lru-cache": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", - "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", - "dev": true, - "requires": { - "pseudomap": "^1.0.2", - "yallist": "^2.1.2" - } - }, - "yallist": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", - "dev": true - } - } - }, - "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-color-names": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/css-color-names/-/css-color-names-0.0.4.tgz", - "integrity": "sha1-gIrcLnnPhHOAabZGyyDsJ762KeA=", - "dev": true - }, - "css-declaration-sorter": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/css-declaration-sorter/-/css-declaration-sorter-4.0.1.tgz", - "integrity": "sha512-BcxQSKTSEEQUftYpBVnsH4SF05NTuBokb19/sBt6asXGKZ/6VP7PLG1CBCkFDYOnhXhPh0jMhO6xZ71oYHXHBA==", - "dev": true, - "requires": { - "postcss": "^7.0.1", - "timsort": "^0.3.0" - } - }, - "css-loader": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-2.1.0.tgz", - "integrity": "sha512-MoOu+CStsGrSt5K2OeZ89q3Snf+IkxRfAIt9aAKg4piioTrhtP1iEFPu+OVn3Ohz24FO6L+rw9UJxBILiSBw5Q==", - "dev": true, - "requires": { - "icss-utils": "^4.0.0", - "loader-utils": "^1.2.1", - "lodash": "^4.17.11", - "postcss": "^7.0.6", - "postcss-modules-extract-imports": "^2.0.0", - "postcss-modules-local-by-default": "^2.0.3", - "postcss-modules-scope": "^2.0.0", - "postcss-modules-values": "^2.0.0", - "postcss-value-parser": "^3.3.0", - "schema-utils": "^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=", - "dev": true, - "requires": { - "boolbase": "~1.0.0", - "css-what": "2.1", - "domutils": "1.5.1", - "nth-check": "~1.0.1" - } - }, - "css-select-base-adapter": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/css-select-base-adapter/-/css-select-base-adapter-0.1.1.tgz", - "integrity": "sha512-jQVeeRG70QI08vSTwf1jHxp74JoZsr2XSgETae8/xC8ovSnL2WF87GTLO86Sbwdt2lK4Umg4HnnwMO4YF3Ce7w==", - "dev": true - }, - "css-selector-tokenizer": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/css-selector-tokenizer/-/css-selector-tokenizer-0.7.1.tgz", - "integrity": "sha512-xYL0AMZJ4gFzJQsHUKa5jiWWi2vH77WVNg7JYRyewwj6oPh4yb/y6Y9ZCw9dsj/9UauMhtuxR+ogQd//EdEVNA==", - "dev": true, - "requires": { - "cssesc": "^0.1.0", - "fastparse": "^1.1.1", - "regexpu-core": "^1.0.0" - } - }, - "css-tree": { - "version": "1.0.0-alpha.28", - "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-1.0.0-alpha.28.tgz", - "integrity": "sha512-joNNW1gCp3qFFzj4St6zk+Wh/NBv0vM5YbEreZk0SD4S23S+1xBKb6cLDg2uj4P4k/GUMlIm6cKIDqIG+vdt0w==", - "dev": true, - "requires": { - "mdn-data": "~1.1.0", - "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=", - "dev": true - } - } - }, - "css-unit-converter": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/css-unit-converter/-/css-unit-converter-1.1.1.tgz", - "integrity": "sha1-2bkoGtz9jO2TW9urqDeGiX9k6ZY=", - "dev": true - }, - "css-url-regex": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/css-url-regex/-/css-url-regex-1.1.0.tgz", - "integrity": "sha1-g4NCMMyfdMRX3lnuvRVD/uuDt+w=", - "dev": true - }, - "css-what": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/css-what/-/css-what-2.1.3.tgz", - "integrity": "sha512-a+EPoD+uZiNfh+5fxw2nO9QwFa6nJe2Or35fGY6Ipw1R3R4AGz1d1TEZrCegvw2YTmZ0jXirGYlzxxpYSHwpEg==", - "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 - }, - "cssnano": { - "version": "4.1.10", - "resolved": "https://registry.npmjs.org/cssnano/-/cssnano-4.1.10.tgz", - "integrity": "sha512-5wny+F6H4/8RgNlaqab4ktc3e0/blKutmq8yNlBFXA//nSFFAqAngjNVRzUvCgYROULmZZUoosL/KSoZo5aUaQ==", - "dev": true, - "requires": { - "cosmiconfig": "^5.0.0", - "cssnano-preset-default": "^4.0.7", - "is-resolvable": "^1.0.0", - "postcss": "^7.0.0" - } - }, - "cssnano-preset-default": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/cssnano-preset-default/-/cssnano-preset-default-4.0.7.tgz", - "integrity": "sha512-x0YHHx2h6p0fCl1zY9L9roD7rnlltugGu7zXSKQx6k2rYw0Hi3IqxcoAGF7u9Q5w1nt7vK0ulxV8Lo+EvllGsA==", - "dev": true, - "requires": { - "css-declaration-sorter": "^4.0.1", - "cssnano-util-raw-cache": "^4.0.1", - "postcss": "^7.0.0", - "postcss-calc": "^7.0.1", - "postcss-colormin": "^4.0.3", - "postcss-convert-values": "^4.0.1", - "postcss-discard-comments": "^4.0.2", - "postcss-discard-duplicates": "^4.0.2", - "postcss-discard-empty": "^4.0.1", - "postcss-discard-overridden": "^4.0.1", - "postcss-merge-longhand": "^4.0.11", - "postcss-merge-rules": "^4.0.3", - "postcss-minify-font-values": "^4.0.2", - "postcss-minify-gradients": "^4.0.2", - "postcss-minify-params": "^4.0.2", - "postcss-minify-selectors": "^4.0.2", - "postcss-normalize-charset": "^4.0.1", - "postcss-normalize-display-values": "^4.0.2", - "postcss-normalize-positions": "^4.0.2", - "postcss-normalize-repeat-style": "^4.0.2", - "postcss-normalize-string": "^4.0.2", - "postcss-normalize-timing-functions": "^4.0.2", - "postcss-normalize-unicode": "^4.0.1", - "postcss-normalize-url": "^4.0.1", - "postcss-normalize-whitespace": "^4.0.2", - "postcss-ordered-values": "^4.1.2", - "postcss-reduce-initial": "^4.0.3", - "postcss-reduce-transforms": "^4.0.2", - "postcss-svgo": "^4.0.2", - "postcss-unique-selectors": "^4.0.1" - } - }, - "cssnano-util-get-arguments": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/cssnano-util-get-arguments/-/cssnano-util-get-arguments-4.0.0.tgz", - "integrity": "sha1-7ToIKZ8h11dBsg87gfGU7UnMFQ8=", - "dev": true - }, - "cssnano-util-get-match": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/cssnano-util-get-match/-/cssnano-util-get-match-4.0.0.tgz", - "integrity": "sha1-wOTKB/U4a7F+xeUiULT1lhNlFW0=", - "dev": true - }, - "cssnano-util-raw-cache": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/cssnano-util-raw-cache/-/cssnano-util-raw-cache-4.0.1.tgz", - "integrity": "sha512-qLuYtWK2b2Dy55I8ZX3ky1Z16WYsx544Q0UWViebptpwn/xDBmog2TLg4f+DBMg1rJ6JDWtn96WHbOKDWt1WQA==", - "dev": true, - "requires": { - "postcss": "^7.0.0" - } - }, - "cssnano-util-same-parent": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/cssnano-util-same-parent/-/cssnano-util-same-parent-4.0.1.tgz", - "integrity": "sha512-WcKx5OY+KoSIAxBW6UBBRay1U6vkYheCdjyVNDm85zt5K9mHoGOfsOsqIszfAqrQQFIIKgjh2+FDgIj/zsl21Q==", - "dev": true - }, - "csso": { - "version": "3.5.1", - "resolved": "https://registry.npmjs.org/csso/-/csso-3.5.1.tgz", - "integrity": "sha512-vrqULLffYU1Q2tLdJvaCYbONStnfkfimRxXNaGjxMldI0C7JPBC4rB1RyjhfdZ4m1frm8pM9uRPKH3d2knZ8gg==", - "dev": true, - "requires": { - "css-tree": "1.0.0-alpha.29" - }, - "dependencies": { - "css-tree": { - "version": "1.0.0-alpha.29", - "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-1.0.0-alpha.29.tgz", - "integrity": "sha512-sRNb1XydwkW9IOci6iB2xmy8IGCj6r/fr+JWitvJ2JxQRPzN3T4AGGVWCMlVmVwM1gtgALJRmGIlWv5ppnGGkg==", - "dev": true, - "requires": { - "mdn-data": "~1.1.0", - "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=", - "dev": true - } - } - }, - "cssom": { - "version": "0.3.6", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.6.tgz", - "integrity": "sha512-DtUeseGk9/GBW0hl0vVPpU22iHL6YB5BUX7ml1hB+GMpo0NX5G4voX3kdWiMSEguFtcW3Vh3djqNF4aIe6ne0A==", - "dev": true - }, - "cssstyle": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-1.2.1.tgz", - "integrity": "sha512-7DYm8qe+gPx/h77QlCyFmX80+fGaE/6A/Ekl0zaszYOubvySO2saYFdQ78P29D0UsULxFKCetDGNaNRUdSF+2A==", - "dev": true, - "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=", - "dev": true, - "requires": { - "array-find-index": "^1.0.1" - } - }, - "cyclist": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-0.2.2.tgz", - "integrity": "sha1-GzN5LhHpFKL9bW7WRHRkRE5fpkA=", - "dev": true - }, - "d3": { - "version": "3.5.17", - "resolved": "https://registry.npmjs.org/d3/-/d3-3.5.17.tgz", - "integrity": "sha1-vEZ0gAQ3iyGjYMn8fPUjF5B2L7g=", - "dev": true - }, - "dargs": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/dargs/-/dargs-6.0.0.tgz", - "integrity": "sha512-6lJauzNaI7MiM8EHQWmGj+s3rP5/i1nYs8GAvKrLAx/9dpc9xS/4seFb1ioR39A+kcfu4v3jnEa/EE5qWYnitQ==", - "dev": true - }, - "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" - } - }, - "data-urls": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-1.1.0.tgz", - "integrity": "sha512-YTWYI9se1P55u58gL5GkQHW4P6VJBJ5iBT+B5a7i2Tjadhv52paJG0qHX4A0OR6/t52odI64KP2YvFpkDOi3eQ==", - "dev": true, - "requires": { - "abab": "^2.0.0", - "whatwg-mimetype": "^2.2.0", - "whatwg-url": "^7.0.0" - }, - "dependencies": { - "whatwg-url": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-7.0.0.tgz", - "integrity": "sha512-37GeVSIJ3kn1JgKyjiYNmSLP1yzbpb29jdmwBSgkD9h40/hyrR/OifpVUndji3tmwGgD8qpw7iQu3RSbCrBpsQ==", - "dev": true, - "requires": { - "lodash.sortby": "^4.7.0", - "tr46": "^1.0.1", - "webidl-conversions": "^4.0.2" - } - } - } - }, - "date-fns": { - "version": "1.30.1", - "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-1.30.1.tgz", - "integrity": "sha512-hBSVCvSmWC+QypYObzwGOd9wqdDpOt+0wl0KbU+R+uuZBS1jN8VsD1ss3irQDknRj5NvxiTF6oj/nDRnN/UQNw==", - "dev": true - }, - "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 - }, - "dateformat": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-3.0.3.tgz", - "integrity": "sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q==", - "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 - }, - "decamelize-keys": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/decamelize-keys/-/decamelize-keys-1.1.0.tgz", - "integrity": "sha1-0XGoeTMlKAfrPLYdwcFEXQeN8tk=", - "dev": true, - "requires": { - "decamelize": "^1.1.0", - "map-obj": "^1.0.0" - }, - "dependencies": { - "map-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", - "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", - "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 - }, - "decompress-response": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", - "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", - "dev": true, - "requires": { - "mimic-response": "^1.0.0" - } - }, - "dedent": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", - "integrity": "sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw=", - "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-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "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-gateway": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/default-gateway/-/default-gateway-2.7.2.tgz", - "integrity": "sha512-lAc4i9QJR0YHSDFdzeBQKfZ1SRDG3hsJNEkrpcZa8QhBfidLAilT60BDEIVUUGqosFp425KOgB3uYqcnQrWafQ==", - "dev": true, - "requires": { - "execa": "^0.10.0", - "ip-regex": "^2.1.0" - }, - "dependencies": { - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "execa": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-0.10.0.tgz", - "integrity": "sha512-7XOMnz8Ynx1gGo/3hyV9loYNPWM94jG3+3T3Y8tsfSstFmETmENCMU/A/zj8Lyaj1lkgEepKepvd6240tBRvlw==", - "dev": true, - "requires": { - "cross-spawn": "^6.0.0", - "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" - } - }, - "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 - } - } - }, - "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" - } - }, - "define-properties": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", - "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", - "dev": true, - "requires": { - "object-keys": "^1.0.12" - } - }, - "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" - } - } - } - }, - "defined": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/defined/-/defined-1.0.0.tgz", - "integrity": "sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM=", - "dev": true - }, - "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 - } - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "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 - }, - "dependency-graph": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/dependency-graph/-/dependency-graph-0.7.2.tgz", - "integrity": "sha512-KqtH4/EZdtdfWX0p6MGP9jljvxSY6msy/pRUD4jgNwVpv3v1QmNLlsB3LDSSUg79BRVSn7jI1QPRtArGABovAQ==", - "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-conflict": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/detect-conflict/-/detect-conflict-1.0.1.tgz", - "integrity": "sha1-CIZXpmqWHAUBnbfEIwiDsca0F24=", - "dev": true - }, - "detect-file": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", - "integrity": "sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc=", - "dev": true - }, - "detect-newline": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-2.1.0.tgz", - "integrity": "sha1-9B8cEL5LAOh7XxPaaAdZ8sW/0+I=", - "dev": true - }, - "detect-node": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.0.4.tgz", - "integrity": "sha512-ZIzRpLJrOj7jjP2miAtgqIfmzbxa4ZOr5jJc601zklsfEx9oTzmmj2nVpIPRpNlRTIh8lc1kyViIY7BWSGNmKw==", - "dev": true - }, - "detective": { - "version": "4.7.1", - "resolved": "https://registry.npmjs.org/detective/-/detective-4.7.1.tgz", - "integrity": "sha512-H6PmeeUcZloWtdt4DAkFyzFL94arpHr3NOwwmVILFiy+9Qd4JTxxXrzfyGk/lmct2qVGBwTSwSXagqu2BxmWig==", - "dev": true, - "requires": { - "acorn": "^5.2.1", - "defined": "^1.0.0" - } - }, - "dev-ip": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dev-ip/-/dev-ip-1.0.1.tgz", - "integrity": "sha1-p2o+0YVb56ASu4rBbLgPPADcKPA=", - "dev": true - }, - "diagnostics": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/diagnostics/-/diagnostics-1.1.1.tgz", - "integrity": "sha512-8wn1PmdunLJ9Tqbx+Fx/ZEuHfJf4NKSN2ZBj7SJC/OWRWha843+WsTjqMe1B5E3p28jqBlp+mJ2fPVxPyNgYKQ==", - "dev": true, - "requires": { - "colorspace": "1.1.x", - "enabled": "1.0.x", - "kuler": "1.0.x" - } - }, - "didyoumean": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.1.tgz", - "integrity": "sha1-6S7f2tplN9SE1zwBcv0eugxJdv8=", - "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 - }, - "diff-sequences": { - "version": "24.3.0", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-24.3.0.tgz", - "integrity": "sha512-xLqpez+Zj9GKSnPWS0WZw1igGocZ+uua8+y+5dDNTT934N3QuY1sp2LkHzwiaYQGz60hMq0pjAshdeXm5VUOEw==", - "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.2.2", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-2.2.2.tgz", - "integrity": "sha512-f9LBi5QWzIW3I6e//uxZoLBlUt9kcp66qo0sSCxL6YZKc75R1c4MFCoe/LaZiBGmgujvQdxc5Bn3QhfyvK5Hsw==", - "dev": true, - "requires": { - "path-type": "^3.0.0" - }, - "dependencies": { - "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" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - } - } - }, - "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.2.0", - "resolved": "https://registry.npmjs.org/dom-converter/-/dom-converter-0.2.0.tgz", - "integrity": "sha512-gd3ypIPfOMr9h5jIKq8E3sHOTCjeirnl0WK5ZdS1AW0Odt0b1PaWaHdJ4Qk4klv+YB9aJBS7mESXjFoDQPu6DA==", - "dev": true, - "requires": { - "utila": "~0.4" - } - }, - "dom-serializer": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.1.tgz", - "integrity": "sha512-l0IU0pPzLWSHBcieZbpOKgkIn3ts3vAh7ZuFyXNwJxJXk/c4Gwj9xaTJwIDVQCXawWD0qb3IzMGH5rglQaO0XA==", - "dev": true, - "requires": { - "domelementtype": "^1.3.0", - "entities": "^1.1.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==", - "dev": true - }, - "domelementtype": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz", - "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==", - "dev": true - }, - "domexception": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/domexception/-/domexception-1.0.1.tgz", - "integrity": "sha512-raigMkn7CJNNo6Ihro1fzG7wr3fHuYVytzquZKX5n0yizGsTcYgzdIUwj1X9pK0VvjeihV+XiclP+DjwbsSKug==", - "dev": true, - "requires": { - "webidl-conversions": "^4.0.2" - } - }, - "domhandler": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.4.2.tgz", - "integrity": "sha512-JiK04h0Ht5u/80fdLMCEmV4zkNh2BcoMFBmZ/91WtYZ8qVXSKjiw7fXMgFPnHcSZgOo3XdinHvmnDUeMf5R4wA==", - "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" - } - }, - "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==", - "dev": true, - "requires": { - "is-obj": "^1.0.0" - } - }, - "drange": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/drange/-/drange-1.1.1.tgz", - "integrity": "sha512-pYxfDYpued//QpnLIm4Avk7rsNtAtQkUES2cwAYSvD/wd2pKD71gN2Ebj3e7klzXwjocvE8c5vx/1fxwpqmSxA==", - "dev": true - }, - "duplexer3": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz", - "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=", - "dev": true - }, - "duplexify": { - "version": "3.7.1", - "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.7.1.tgz", - "integrity": "sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g==", - "dev": true, - "requires": { - "end-of-stream": "^1.0.0", - "inherits": "^2.0.1", - "readable-stream": "^2.0.0", - "stream-shift": "^1.0.0" - } - }, - "easy-extender": { - "version": "2.3.4", - "resolved": "https://registry.npmjs.org/easy-extender/-/easy-extender-2.3.4.tgz", - "integrity": "sha512-8cAwm6md1YTiPpOvDULYJL4ZS6WfM5/cTeVVh4JsvyYZAoqlRVUpHL9Gr5Fy7HA6xcSZicUia3DeAgO3Us8E+Q==", - "dev": true, - "requires": { - "lodash": "^4.17.10" - } - }, - "eazy-logger": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/eazy-logger/-/eazy-logger-3.0.2.tgz", - "integrity": "sha1-oyWqXlPROiIliJsqxBE7K5Y29Pw=", - "dev": true, - "requires": { - "tfunk": "^3.0.1" - } - }, - "ecc-jsbn": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", - "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", - "dev": true, - "requires": { - "jsbn": "~0.1.0", - "safer-buffer": "^2.1.0" - } - }, - "editions": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/editions/-/editions-2.1.3.tgz", - "integrity": "sha512-xDZyVm0A4nLgMNWVVLJvcwMjI80ShiH/27RyLiCnW1L273TcJIA25C4pwJ33AWV01OX6UriP35Xu+lH4S7HWQw==", - "dev": true, - "requires": { - "errlop": "^1.1.1", - "semver": "^5.6.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.116", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.116.tgz", - "integrity": "sha512-NKwKAXzur5vFCZYBHpdWjTMO8QptNLNP80nItkSIgUOapPAo9Uia+RvkCaZJtO7fhQaVElSvBPWEc2ku6cKsPA==", - "dev": true - }, - "elegant-spinner": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/elegant-spinner/-/elegant-spinner-1.0.1.tgz", - "integrity": "sha1-2wQ1IcldfjA/2PNFvtwzSc+wcp4=", - "dev": true - }, - "elliptic": { - "version": "6.4.1", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.1.tgz", - "integrity": "sha512-BsXLz5sqX8OHcsh7CqBMztyXARmGQ3LWPtGjJi6DiJHq5C/qvi9P3OqgswKSDftbu8+IoI/QDTAm2fFnQ9SZSQ==", - "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 - }, - "enabled": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/enabled/-/enabled-1.0.2.tgz", - "integrity": "sha1-ll9lE9LC0cX0ZStkouM5ZGf8L5M=", - "dev": true, - "requires": { - "env-variable": "0.0.x" - } - }, - "encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", - "dev": true - }, - "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" - } - }, - "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": "3.2.1", - "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-3.2.1.tgz", - "integrity": "sha512-+VlKzHzMhaU+GsCIg4AoXF1UdDFjHHwMmMKqMJNDNLlUlejz58FCy4LBqB2YVJskHGYl06BatYWKP2TVdVXE5w==", - "dev": true, - "requires": { - "accepts": "~1.3.4", - "base64id": "1.0.0", - "cookie": "0.3.1", - "debug": "~3.1.0", - "engine.io-parser": "~2.1.0", - "ws": "~3.3.1" - }, - "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" - } - }, - "ws": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-3.3.3.tgz", - "integrity": "sha512-nnWLa/NwZSt4KQJu51MYlCcSQ5g7INpOrOMt4XV8j4dqTXdmlUmSHQ8/oLC069ckre0fRsgfvsKwbTdtKLCDkA==", - "dev": true, - "requires": { - "async-limiter": "~1.0.0", - "safe-buffer": "~5.1.0", - "ultron": "~1.1.0" - } - } - } - }, - "engine.io-client": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-3.3.2.tgz", - "integrity": "sha512-y0CPINnhMvPuwtqXfsGuWE8BB66+B6wTtCofQDRecMQPYX3MYUZXFNKDhdrSe3EVjgOu4V3rxdeqN/Tr91IgbQ==", - "dev": true, - "requires": { - "component-emitter": "1.2.1", - "component-inherit": "0.0.3", - "debug": "~3.1.0", - "engine.io-parser": "~2.1.1", - "has-cors": "1.1.0", - "indexof": "0.0.1", - "parseqs": "0.0.5", - "parseuri": "0.0.5", - "ws": "~6.1.0", - "xmlhttprequest-ssl": "~1.5.4", - "yeast": "0.1.2" - }, - "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" - } - } - } - }, - "engine.io-parser": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-2.1.3.tgz", - "integrity": "sha512-6HXPre2O4Houl7c4g7Ic/XzPnHBvaEmN90vtRO9uLmwtRqQmTOw0QMevL1TOfL2Cpu1VzsaTmMotQgMdkzGkVA==", - "dev": true, - "requires": { - "after": "0.8.2", - "arraybuffer.slice": "~0.0.7", - "base64-arraybuffer": "0.1.5", - "blob": "0.0.5", - "has-binary2": "~1.0.2" - } - }, - "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" - } - }, - "entities": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.2.tgz", - "integrity": "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w==", - "dev": true - }, - "env-paths": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-1.0.0.tgz", - "integrity": "sha1-QWgTO0K7BcOKNbGuQ5fIKYqzaeA=", - "dev": true - }, - "env-variable": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/env-variable/-/env-variable-0.0.5.tgz", - "integrity": "sha512-zoB603vQReOFvTg5xMl9I1P2PnHsHQQKTEowsKKD7nseUfJq6UWzK+4YtlWUO1nhiQUxe6XMkk+JleSZD1NZFA==", - "dev": true - }, - "envify": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/envify/-/envify-3.4.1.tgz", - "integrity": "sha1-1xIjKejfFoi6dxsSUBkXyc5cvOg=", - "dev": true, - "requires": { - "jstransform": "^11.0.3", - "through": "~2.3.4" - } - }, - "err-code": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/err-code/-/err-code-1.1.2.tgz", - "integrity": "sha1-BuARbTAo9q70gGhJ6w6mp0iuaWA=", - "dev": true - }, - "errlop": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/errlop/-/errlop-1.1.1.tgz", - "integrity": "sha512-WX7QjiPHhsny7/PQvrhS5VMizXXKoKCS3udaBp8gjlARdbn+XmK300eKBAAN0hGyRaTCtRpOaxK+xFVPUJ3zkw==", - "dev": true, - "requires": { - "editions": "^2.1.2" - } - }, - "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": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/error/-/error-7.0.2.tgz", - "integrity": "sha1-pfdf/02ZJhJt2sDqXcOOaJFTywI=", - "dev": true, - "requires": { - "string-template": "~0.2.1", - "xtend": "~4.0.0" - } - }, - "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" - } - }, - "error-stack-parser": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/error-stack-parser/-/error-stack-parser-2.0.2.tgz", - "integrity": "sha512-E1fPutRDdIj/hohG0UpT5mayXNCxXP9d+snxFsPU9X0XgccOumKraa3juDMwTUyi7+Bu5+mCGagjg4IYeNbOdw==", - "dev": true, - "requires": { - "stackframe": "^1.0.4" - } - }, - "es-abstract": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.13.0.tgz", - "integrity": "sha512-vDZfg/ykNxQVwup/8E1BZhVzFfBxs9NqMzGcvIJrqg5k2/5Za2bWo40dK2J1pgLngZ7c+Shh8lwYtLGyrwPutg==", - "dev": true, - "requires": { - "es-to-primitive": "^1.2.0", - "function-bind": "^1.1.1", - "has": "^1.0.3", - "is-callable": "^1.1.4", - "is-regex": "^1.0.4", - "object-keys": "^1.0.12" - } - }, - "es-to-primitive": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.0.tgz", - "integrity": "sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg==", - "dev": true, - "requires": { - "is-callable": "^1.1.4", - "is-date-object": "^1.0.1", - "is-symbol": "^1.0.2" - } - }, - "es6-promise": { - "version": "4.2.6", - "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.6.tgz", - "integrity": "sha512-aRVgGdnmW2OiySVPUC9e6m+plolMAJKjZnQlCwNSuK5yQ0JN61DZSO1X1Ufd1foqWRAlig0rhduTCHe7sVtK5Q==", - "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-templates": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/es6-templates/-/es6-templates-0.2.3.tgz", - "integrity": "sha1-XLmsn7He1usSOTQrgdeSu7QHjuQ=", - "dev": true, - "requires": { - "recast": "~0.11.12", - "through": "~2.3.6" - } - }, - "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=" - }, - "escodegen": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.11.1.tgz", - "integrity": "sha512-JwiqFD9KdGVVpeuRa68yU3zZnBEOcPs0nKW7wZzXky8Z7tffdYUHbe11bPCV5jYlK6DVdKLWLm0f5I/QlL0Kmw==", - "dev": true, - "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=", - "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, - "optional": true - } - } - }, - "eslint-scope": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.3.tgz", - "integrity": "sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg==", - "dev": true, - "requires": { - "esrecurse": "^4.1.0", - "estraverse": "^4.1.1" - } - }, - "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 - }, - "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" - } - }, - "estraverse": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", - "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", - "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": "1.2.0", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-1.2.0.tgz", - "integrity": "sha1-HIaZHYFq0eUEdQ5zh0Ik7PO+xQg=", - "dev": true - }, - "events": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/events/-/events-3.0.0.tgz", - "integrity": "sha512-Dc381HFWJzEOhQ+d8pkNon++bk9h6cdAoAj4iE6Q4y6xgTzySWXlKn05/TVNpjnfRqi/X0EpJEJohPjNI3zpVA==", - "dev": true - }, - "eventsource": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-1.0.7.tgz", - "integrity": "sha512-4Ln17+vVT0k8aWq+t/bF5arcS3EpT9gYtW66EPacdj/mAFevznsnyoHLPy2BA8gbIQeIHoPsvwmfBftfcG//BQ==", - "dev": true, - "requires": { - "original": "^1.0.0" - } - }, - "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" - } - }, - "exec-sh": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/exec-sh/-/exec-sh-0.3.2.tgz", - "integrity": "sha512-9sLAvzhI5nc8TpuQUh4ahMdCrWT00wPWz7j47/emR5+2qEfoZP5zzUXvx+vdx+H6ohhnsYC31iX04QLYJK8zTg==", - "dev": true - }, - "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": { - "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 - } - } - }, - "exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", - "dev": true - }, - "exit-hook": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-1.1.1.tgz", - "integrity": "sha1-8FyiM7SMBdVP/wd2XfhQfpXAL/g=", - "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" - } - } - } - }, - "expand-tilde": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", - "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", - "dev": true, - "requires": { - "homedir-polyfill": "^1.0.1" - } - }, - "expect": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/expect/-/expect-24.5.0.tgz", - "integrity": "sha512-p2Gmc0CLxOgkyA93ySWmHFYHUPFIHG6XZ06l7WArWAsrqYVaVEkOU5NtT5i68KUyGKbkQgDCkiT65bWmdoL6Bw==", - "dev": true, - "requires": { - "@jest/types": "^24.5.0", - "ansi-styles": "^3.2.0", - "jest-get-type": "^24.3.0", - "jest-matcher-utils": "^24.5.0", - "jest-message-util": "^24.5.0", - "jest-regex-util": "^24.3.0" - }, - "dependencies": { - "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" - } - } - } - }, - "express": { - "version": "4.16.4", - "resolved": "https://registry.npmjs.org/express/-/express-4.16.4.tgz", - "integrity": "sha512-j12Uuyb4FMrd/qQAm6uCHAkPtO8FDTRJZBDd5D2KOL2eLaz1yUNdUB/NOIyq0iU4q4cFarsUCrnFDPBcnksuOg==", - "dev": true, - "requires": { - "accepts": "~1.3.5", - "array-flatten": "1.1.1", - "body-parser": "1.18.3", - "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.4", - "qs": "6.5.2", - "range-parser": "~1.2.0", - "safe-buffer": "5.1.2", - "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 - }, - "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" - } - }, - "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 - }, - "statuses": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz", - "integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==", - "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" - } - } - } - }, - "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==", - "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": "2.0.1", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", - "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", - "dev": true - }, - "fast-glob": { - "version": "2.2.6", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-2.2.6.tgz", - "integrity": "sha512-0BvMaZc1k9F+MeWWMe8pL6YltFzZYcJsYU7D4JyDA6PAczaXvxqQQ/z+mDF7/4Mw01DeUc+i3CTKajnkANkV4w==", - "dev": true, - "requires": { - "@mrmlnc/readdir-enhanced": "^2.2.1", - "@nodelib/fs.stat": "^1.1.2", - "glob-parent": "^3.1.0", - "is-glob": "^4.0.0", - "merge2": "^1.2.3", - "micromatch": "^3.1.10" - } - }, - "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 - }, - "fast-safe-stringify": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.0.6.tgz", - "integrity": "sha512-q8BZ89jjc+mz08rSxROs8VsrBBcn1SIw1kq9NjolL509tkABRk9io01RAjSaEv1Xb2uFLt8VtRiZbGp5H8iDtg==", - "dev": true - }, - "fastparse": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/fastparse/-/fastparse-1.1.2.tgz", - "integrity": "sha512-483XLLxTVIwWK3QTrMGRqUfUpoOs/0hbQrl2oz4J0pAcm3A3bu84wxTFqGqkJzewCLdME38xJLJAxBABfQT8sQ==", - "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" - } - }, - "fb-watchman": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.0.tgz", - "integrity": "sha1-VOmr99+i8mzZsWNsWIwa/AXeXVg=", - "dev": true, - "requires": { - "bser": "^2.0.0" - } - }, - "fbjs": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/fbjs/-/fbjs-0.6.1.tgz", - "integrity": "sha1-lja3cF9bqWhNRLcveDISVK/IYPc=", - "dev": true, - "requires": { - "core-js": "^1.0.0", - "loose-envify": "^1.0.0", - "promise": "^7.0.3", - "ua-parser-js": "^0.7.9", - "whatwg-fetch": "^0.9.0" - }, - "dependencies": { - "core-js": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-1.2.7.tgz", - "integrity": "sha1-ZSKUwUZR2yj6k70tX/KYOk8IxjY=", - "dev": true - } - } - }, - "fecha": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fecha/-/fecha-2.3.3.tgz", - "integrity": "sha512-lUGBnIamTAwk4znq5BcqsDaxSmZ9nDVJaij6NvRt/Tg4R69gERA+otPKbS86ROw9nxVMw2/mp1fnaiWqbs6Sdg==", - "dev": true - }, - "figgy-pudding": { - "version": "3.5.1", - "resolved": "https://registry.npmjs.org/figgy-pudding/-/figgy-pudding-3.5.1.tgz", - "integrity": "sha512-vNKxJHTEKNThjfrdJwHc7brvM6eVevuO5nTj6ez8ZQ1qbXTvGthucRF7S4vf2cr71QVnT70V34v0S1DyQsti0w==", - "dev": true - }, - "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-loader": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/file-loader/-/file-loader-3.0.1.tgz", - "integrity": "sha512-4sNIOXgtH/9WZq4NvlfU3Opn5ynUsqBwSLyM+I7UOwdGigTBYfVVQEwe/msZNX/j4pCJTIM14Fsw66Svo1oVrw==", - "dev": true, - "requires": { - "loader-utils": "^1.0.2", - "schema-utils": "^1.0.0" - } - }, - "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" - } - }, - "filesize": { - "version": "3.6.1", - "resolved": "https://registry.npmjs.org/filesize/-/filesize-3.6.1.tgz", - "integrity": "sha512-7KjR1vv6qnicaPMi1iiTcI85CyYwRO/PSFCu6SvqL8jN2Wjt/NIYQTFtFs7fSDCYOstUkEWIQGFUg5YZQfjlcg==", - "dev": true - }, - "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.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" - } - }, - "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-parent-dir": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/find-parent-dir/-/find-parent-dir-0.3.0.tgz", - "integrity": "sha1-M8RLQpqysvBkYpnF+fcY83b/jVQ=", - "dev": true - }, - "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" - } - }, - "findup-sync": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-2.0.0.tgz", - "integrity": "sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw=", - "dev": true, - "requires": { - "detect-file": "^1.0.0", - "is-glob": "^3.1.0", - "micromatch": "^3.0.4", - "resolve-dir": "^1.0.1" - }, - "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" - } - } - } - }, - "first-chunk-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/first-chunk-stream/-/first-chunk-stream-2.0.0.tgz", - "integrity": "sha1-G97NuOCDwGZLkZRVgVd6Q6nzHXA=", - "dev": true, - "requires": { - "readable-stream": "^2.0.2" - } - }, - "flush-write-stream": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/flush-write-stream/-/flush-write-stream-1.1.1.tgz", - "integrity": "sha512-3Z4XhFZ3992uIq0XOqb9AreonueSYphE6oYbpt5+3u06JWklbsPkNv3ZKkP9Bz/r+1MWCaMoSQ28P85+1Yc77w==", - "dev": true, - "requires": { - "inherits": "^2.0.3", - "readable-stream": "^2.3.6" - } - }, - "fn-name": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/fn-name/-/fn-name-2.0.1.tgz", - "integrity": "sha1-UhTXU3pNBqSjAcDMJi/rhBiAAuc=", - "dev": true - }, - "follow-redirects": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.7.0.tgz", - "integrity": "sha512-m/pZQy4Gj287eNy94nivy5wchN3Kp+Q5WgUPNy5lJSZ3sgkVKSYV/ZChMAQVIgx1SqfZ2zBZtPA2YlXIWxxJOQ==", - "dev": true, - "requires": { - "debug": "^3.2.6" - }, - "dependencies": { - "debug": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - } - } - }, - "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": "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" - } - }, - "forever-agent": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", - "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", - "dev": true - }, - "fork-ts-checker-webpack-plugin": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fork-ts-checker-webpack-plugin/-/fork-ts-checker-webpack-plugin-0.5.2.tgz", - "integrity": "sha512-a5IG+xXyKnpruI0CP/anyRLAoxWtp3lzdG6flxicANnoSzz64b12dJ7ASAVRrI2OaWwZR2JyBaMHFQqInhWhIw==", - "dev": true, - "requires": { - "babel-code-frame": "^6.22.0", - "chalk": "^2.4.1", - "chokidar": "^2.0.4", - "micromatch": "^3.1.10", - "minimatch": "^3.0.4", - "tapable": "^1.0.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "form-data": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", - "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", - "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 - }, - "friendly-errors-webpack-plugin": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/friendly-errors-webpack-plugin/-/friendly-errors-webpack-plugin-1.7.0.tgz", - "integrity": "sha512-K27M3VK30wVoOarP651zDmb93R9zF28usW4ocaK3mfQeIEI5BPht/EzZs5E8QLLwbLRJQMwscAjDxYPb1FuNiw==", - "dev": true, - "requires": { - "chalk": "^1.1.3", - "error-stack-parser": "^2.0.0", - "string-width": "^2.0.0" - } - }, - "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-extra": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-3.0.1.tgz", - "integrity": "sha1-N5TzeMWLNC6n27sjCVEJxLO2IpE=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "jsonfile": "^3.0.0", - "universalify": "^0.1.0" - } - }, - "fs-minipass": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-1.2.5.tgz", - "integrity": "sha512-JhBl0skXjUPCFH7x6x61gQxrKyXsxB5gcgePLZCwfyCGGsTISMoIeObbrvVeP6Xmyaudw4TT43qV2Gz+iyd2oQ==", - "dev": true, - "requires": { - "minipass": "^2.2.1" - } - }, - "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.7", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.7.tgz", - "integrity": "sha512-Pxm6sI2MeBD7RdD12RYsqaP0nMiwx8eZBXCa6z2L+mRHm2DYrOYwihmhjpkdjUHwQhslWQjRpEgNq4XvBmaAuw==", - "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, - "optional": true - }, - "aproba": { - "version": "1.2.0", - "bundled": true, - "dev": true, - "optional": true - }, - "are-we-there-yet": { - "version": "1.1.5", - "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, - "optional": true - }, - "brace-expansion": { - "version": "1.1.11", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "chownr": { - "version": "1.1.1", - "bundled": true, - "dev": true, - "optional": true - }, - "code-point-at": { - "version": "1.1.0", - "bundled": true, - "dev": true, - "optional": true - }, - "concat-map": { - "version": "0.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "console-control-strings": { - "version": "1.1.0", - "bundled": true, - "dev": true, - "optional": 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.6.0", - "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.3", - "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.24", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "safer-buffer": ">= 2.1.2 < 3" - } - }, - "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, - "optional": true - }, - "ini": { - "version": "1.3.5", - "bundled": true, - "dev": true, - "optional": true - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": 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, - "optional": true, - "requires": { - "brace-expansion": "^1.1.7" - } - }, - "minimist": { - "version": "0.0.8", - "bundled": true, - "dev": true, - "optional": true - }, - "minipass": { - "version": "2.3.5", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "safe-buffer": "^5.1.2", - "yallist": "^3.0.0" - } - }, - "minizlib": { - "version": "1.2.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "minipass": "^2.2.1" - } - }, - "mkdirp": { - "version": "0.5.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "minimist": "0.0.8" - } - }, - "ms": { - "version": "2.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "needle": { - "version": "2.2.4", - "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.3", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "detect-libc": "^1.0.2", - "mkdirp": "^0.5.1", - "needle": "^2.2.1", - "nopt": "^4.0.1", - "npm-packlist": "^1.1.6", - "npmlog": "^4.0.2", - "rc": "^1.2.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.5", - "bundled": true, - "dev": true, - "optional": true - }, - "npm-packlist": { - "version": "1.2.0", - "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, - "optional": true - }, - "object-assign": { - "version": "4.1.1", - "bundled": true, - "dev": true, - "optional": true - }, - "once": { - "version": "1.4.0", - "bundled": true, - "dev": true, - "optional": 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.8", - "bundled": true, - "dev": true, - "optional": true, - "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", - "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.3", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "glob": "^7.1.3" - } - }, - "safe-buffer": { - "version": "5.1.2", - "bundled": true, - "dev": true, - "optional": 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.6.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, - "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, - "dev": true, - "optional": true, - "requires": { - "safe-buffer": "~5.1.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "strip-json-comments": { - "version": "2.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "tar": { - "version": "4.4.8", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "chownr": "^1.1.1", - "fs-minipass": "^1.2.5", - "minipass": "^2.3.4", - "minizlib": "^1.1.1", - "mkdirp": "^0.5.0", - "safe-buffer": "^5.1.2", - "yallist": "^3.0.2" - } - }, - "util-deprecate": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "wide-align": { - "version": "1.1.3", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "string-width": "^1.0.2 || 2" - } - }, - "wrappy": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "yallist": { - "version": "3.0.3", - "bundled": true, - "dev": 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==", - "dev": true - }, - "g-status": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/g-status/-/g-status-2.0.2.tgz", - "integrity": "sha512-kQoE9qH+T1AHKgSSD0Hkv98bobE90ILQcXAF4wvGgsr7uFqNvwmh8j+Lq3l0RVt3E3HjSbv2B9biEGcEtpHLCA==", - "dev": true, - "requires": { - "arrify": "^1.0.1", - "matcher": "^1.0.0", - "simple-git": "^1.85.0" - } - }, - "gauge": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/gauge/-/gauge-1.2.7.tgz", - "integrity": "sha1-6c7FSD09TuDvRLYKfZnkk14TbZM=", - "dev": true, - "requires": { - "ansi": "^0.3.0", - "has-unicode": "^2.0.0", - "lodash.pad": "^4.1.0", - "lodash.padend": "^4.1.0", - "lodash.padstart": "^4.1.0" - } - }, - "generator-jhipster": { - "version": "5.8.2", - "resolved": "https://registry.npmjs.org/generator-jhipster/-/generator-jhipster-5.8.2.tgz", - "integrity": "sha512-GW33cKnIf0wWuK411U9GDiNKwKVLbL4BpAqyR4b9JD6ClhwHsQg3HRlItN8pV0iTHJtyFnSfcV/9nJIHFWwvKA==", - "dev": true, - "requires": { - "axios": "0.18.0", - "chalk": "2.4.1", - "commander": "2.16.0", - "conf": "2.0.0", - "didyoumean": "1.2.1", - "ejs": "2.6.1", - "glob": "7.1.2", - "gulp-filter": "5.1.0", - "insight": "0.10.1", - "jhipster-core": "3.6.11", - "js-object-pretty-print": "0.3.0", - "js-yaml": "3.12.0", - "lodash": "4.17.10", - "meow": "5.0.0", - "mkdirp": "0.5.1", - "os-locale": "2.1.0", - "parse-gitignore": "1.0.1", - "pluralize": "7.0.0", - "prettier": "1.13.7", - "randexp": "0.4.9", - "semver": "5.5.0", - "shelljs": "0.8.2", - "tabtab": "2.2.2", - "through2": "2.0.3", - "uuid": "3.3.2", - "yeoman-environment": "2.3.0", - "yeoman-generator": "3.0.0" - }, - "dependencies": { - "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" - } - }, - "axios": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.18.0.tgz", - "integrity": "sha1-MtU+SFHv3AoRmTts0AB4nXDAUQI=", - "dev": true, - "requires": { - "follow-redirects": "^1.3.0", - "is-buffer": "^1.1.5" - } - }, - "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" - } - }, - "commander": { - "version": "2.16.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.16.0.tgz", - "integrity": "sha512-sVXqklSaotK9at437sFlFpyOcJonxe0yST/AG9DkQKUdIE6IqGIMv4SfAQSKaJbSdVEJYItASCrBiVQHq1HQew==", - "dev": true - }, - "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" - } - }, - "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 - }, - "prettier": { - "version": "1.13.7", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.13.7.tgz", - "integrity": "sha512-KIU72UmYPGk4MujZGYMFwinB7lOf2LsDNGSOC8ufevsrPLISrZbNJlWstRi3m0AMuszbH+EFSQ/r6w56RSPK6w==", - "dev": true - }, - "semver": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.0.tgz", - "integrity": "sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==", - "dev": true - }, - "shelljs": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.2.tgz", - "integrity": "sha512-pRXeNrCA2Wd9itwhvLp5LZQvPJ0wU6bcjaTMywHHGX5XWhVN2nzSu7WV0q+oUY7mGK3mgSkDDzP3MgjqdyIgbQ==", - "dev": true, - "requires": { - "glob": "^7.0.0", - "interpret": "^1.0.0", - "rechoir": "^0.6.2" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "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" - } - } - } - }, - "genfun": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/genfun/-/genfun-5.0.0.tgz", - "integrity": "sha512-KGDOARWVga7+rnB3z9Sd2Letx515owfk0hSxHGuqjANb1M+x2bGZGqHLiozPsYMdM2OubeMni/Hpwmjq6qIUhA==", - "dev": true - }, - "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-own-enumerable-property-symbols": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.0.tgz", - "integrity": "sha512-CIJYJC4GGF06TakLg8z4GQKvDsx9EMspVxOYih7LerEL/WosUnFIww45CGfxfeKHqlg3twgUrYRT1O3WQqjGCg==", - "dev": true - }, - "get-stdin": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-6.0.0.tgz", - "integrity": "sha512-jp4tHawyV7+fkkSKyvjuLZswblUtz+SQKzSWnBbii16BuZksJlU1wuBYXY75r+duh/llF1ur6oNwi+2ZzjKZ7g==", - "dev": true - }, - "get-stream": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", - "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", - "dev": true, - "requires": { - "pump": "^3.0.0" - } - }, - "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" - } - }, - "gh-got": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/gh-got/-/gh-got-6.0.0.tgz", - "integrity": "sha512-F/mS+fsWQMo1zfgG9MD8KWvTWPPzzhuVwY++fhQ5Ggd+0P+CAMHtzMZhNxG+TqGfHDChJKsbh6otfMGqO2AKBw==", - "dev": true, - "requires": { - "got": "^7.0.0", - "is-plain-obj": "^1.1.0" - } - }, - "github-username": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/github-username/-/github-username-4.1.0.tgz", - "integrity": "sha1-y+KABBiDIG2kISrp5LXxacML9Bc=", - "dev": true, - "requires": { - "gh-got": "^6.0.0" - } - }, - "glob": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", - "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", - "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" - } - } - } - }, - "glob-to-regexp": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.3.0.tgz", - "integrity": "sha1-jFoUlNIGbFcMw7/kSWF1rMTVAqs=", - "dev": true - }, - "global-modules": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", - "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", - "dev": true, - "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=", - "dev": true, - "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": "11.11.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.11.0.tgz", - "integrity": "sha512-WHq43gS+6ufNOEqlrDBxVEbb8ntfXrfAUU2ZOpCxrBdGKW3gyv8mCxAfIBD0DroPKGrJ2eSsXsLtY9MPntsyTw==", - "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" - }, - "dependencies": { - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - } - } - }, - "got": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/got/-/got-7.1.0.tgz", - "integrity": "sha512-Y5WMo7xKKq1muPsxD+KmrR8DH5auG7fBdDVueZwETwV6VytKyU9OX/ddpq2/1hp1vIPvVb4T81dKQz3BivkNLw==", - "dev": true, - "requires": { - "decompress-response": "^3.2.0", - "duplexer3": "^0.1.4", - "get-stream": "^3.0.0", - "is-plain-obj": "^1.1.0", - "is-retry-allowed": "^1.0.0", - "is-stream": "^1.0.0", - "isurl": "^1.0.0-alpha5", - "lowercase-keys": "^1.0.0", - "p-cancelable": "^0.3.0", - "p-timeout": "^1.1.1", - "safe-buffer": "^5.0.1", - "timed-out": "^4.0.0", - "url-parse-lax": "^1.0.0", - "url-to-options": "^1.0.1" - }, - "dependencies": { - "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 - } - } - }, - "graceful-fs": { - "version": "4.1.15", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", - "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", - "dev": true - }, - "grouped-queue": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/grouped-queue/-/grouped-queue-0.3.3.tgz", - "integrity": "sha1-wWfSpTGcWg4JZO9qJbfC34mWyFw=", - "dev": true, - "requires": { - "lodash": "^4.17.2" - } - }, - "growly": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/growly/-/growly-1.3.0.tgz", - "integrity": "sha1-8QdIy+dq+WS3yWyTxrzCivEgwIE=", - "dev": true - }, - "gulp-filter": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/gulp-filter/-/gulp-filter-5.1.0.tgz", - "integrity": "sha1-oF4Rr/sHz33PQafeHLe2OsN4PnM=", - "dev": true, - "requires": { - "multimatch": "^2.0.0", - "plugin-error": "^0.1.2", - "streamfilter": "^1.0.5" - } - }, - "handle-thing": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/handle-thing/-/handle-thing-2.0.0.tgz", - "integrity": "sha512-d4sze1JNC454Wdo2fkuyzCr6aHcbL6PGGuFAz0Li/NcOm1tCHGnWDRmJP85dh9IhQErTc2svWFEX5xHIOo//kQ==", - "dev": true - }, - "handlebars": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.1.1.tgz", - "integrity": "sha512-3Zhi6C0euYZL5sM0Zcy7lInLXKQ+YLcF/olbN010mzGQ4XVm50JeyBnMqofHh696GrciGruC7kCcApPDJvVgwA==", - "dev": true, - "requires": { - "neo-async": "^2.6.0", - "optimist": "^0.6.1", - "source-map": "^0.6.1", - "uglify-js": "^3.1.4" - }, - "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 - } - } - }, - "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.1.3", - "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.3.tgz", - "integrity": "sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g==", - "dev": true, - "requires": { - "ajv": "^6.5.5", - "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==", - "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=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "has-binary2": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-binary2/-/has-binary2-1.0.3.tgz", - "integrity": "sha512-G1LWKhDSvhGeAQ8mPVQlqNcOB2sJdwATtZKl2pDKKHfpf/rYj24lkinxf69blJbnsvtqqNU+L3SL50vzZhXOnw==", - "dev": true, - "requires": { - "isarray": "2.0.1" - }, - "dependencies": { - "isarray": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.1.tgz", - "integrity": "sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4=", - "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-symbol-support-x": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/has-symbol-support-x/-/has-symbol-support-x-1.4.2.tgz", - "integrity": "sha512-3ToOva++HaW+eCpgqZrCfN51IPB+7bJNVT6CUATzueB5Heb8o6Nam0V3HG5dlDvZU1Gn5QLcbahiKw/XVk5JJw==", - "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-to-string-tag-x": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/has-to-string-tag-x/-/has-to-string-tag-x-1.4.1.tgz", - "integrity": "sha512-vdbKfmw+3LoOYVr+mtxHaX5a96+0f3DljYd8JOqvOLsf5mw2Otda2qCDT9qRqLAhrjyQ0h7ual5nOiASpsGNFw==", - "dev": true, - "requires": { - "has-symbol-support-x": "^1.4.1" - } - }, - "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.7", - "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", - "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", - "dev": true, - "requires": { - "inherits": "^2.0.3", - "minimalistic-assert": "^1.0.1" - } - }, - "he": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", - "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", - "dev": true - }, - "hex-color-regex": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/hex-color-regex/-/hex-color-regex-1.1.0.tgz", - "integrity": "sha512-l9sfDFsuqtOqKDsQdqrMRk0U85RZc0RtOR9yPI7mRVOa4FsR/BVnZ0shmQRM96Ji99kYZP/7hn1cedc1+ApsTQ==", - "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": "4.2.1", - "resolved": "https://registry.npmjs.org/hoek/-/hoek-4.2.1.tgz", - "integrity": "sha512-QLg82fGkfnJ/4iy1xZ81/9SIJiq1NGFUMGs6ParyjBZr6jW2Ufj/snDqTHixNlHdPNwN2RLVD0Pi3igeK9+JfA==", - "dev": true - }, - "homedir-polyfill": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz", - "integrity": "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==", - "dev": true, - "requires": { - "parse-passwd": "^1.0.0" - } - }, - "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" - } - }, - "hsl-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/hsl-regex/-/hsl-regex-1.0.0.tgz", - "integrity": "sha1-1JMwx4ntgZ4nakwNJy3/owsY/m4=", - "dev": true - }, - "hsla-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/hsla-regex/-/hsla-regex-1.0.0.tgz", - "integrity": "sha1-wc56MWjIxmFAM6S194d/OyJfnDg=", - "dev": true - }, - "html-comment-regex": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/html-comment-regex/-/html-comment-regex-1.1.2.tgz", - "integrity": "sha512-P+M65QY2JQ5Y0G9KKdlDpo0zK+/OHptU5AaBwUfAIDJZk1MYf32Frm84EcOytfJE0t5JvkAnKlmjsXDnWzCJmQ==", - "dev": true - }, - "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==", - "dev": true, - "requires": { - "whatwg-encoding": "^1.0.1" - } - }, - "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-loader": { - "version": "0.5.5", - "resolved": "https://registry.npmjs.org/html-loader/-/html-loader-0.5.5.tgz", - "integrity": "sha512-7hIW7YinOYUpo//kSYcPB6dCKoceKLmOwjEMmhIobHuWGDVl0Nwe4l68mdG/Ru0wcUxQjVMEoZpkalZ/SE7zog==", - "dev": true, - "requires": { - "es6-templates": "^0.2.3", - "fastparse": "^1.1.1", - "html-minifier": "^3.5.8", - "loader-utils": "^1.1.0", - "object-assign": "^4.1.1" - } - }, - "html-minifier": { - "version": "3.5.21", - "resolved": "https://registry.npmjs.org/html-minifier/-/html-minifier-3.5.21.tgz", - "integrity": "sha512-LKUKwuJDhxNa3uf/LPR/KVjm/l3rBqtYeCOAekvG8F1vItxMUpueGd94i/asDDr8/1u7InxzFA5EeGjhhG5mMA==", - "dev": true, - "requires": { - "camel-case": "3.0.x", - "clean-css": "4.2.x", - "commander": "2.17.x", - "he": "1.2.x", - "param-case": "2.1.x", - "relateurl": "0.2.x", - "uglify-js": "3.4.x" - }, - "dependencies": { - "commander": { - "version": "2.17.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz", - "integrity": "sha512-wPMUt6FnH2yzG95SA6mzjQOEKUU3aLaDEmzs1ti+1E9h+CsrZghRlqEM/EJ4KscsQVG8uNN4uVreUeT8+drlgg==", - "dev": true - } - } - }, - "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": { - "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 - }, - "json5": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", - "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=", - "dev": true - }, - "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.10.1", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.10.1.tgz", - "integrity": "sha512-IgieNijUMbkDovyoKObU1DUhm1iwNYE/fuifEoEHfd1oZKZDaONBSkal7Y01shxsM49R4XaMdGez3WnF9UfiCQ==", - "dev": true, - "requires": { - "domelementtype": "^1.3.1", - "domhandler": "^2.3.0", - "domutils": "^1.5.1", - "entities": "^1.1.1", - "inherits": "^2.0.1", - "readable-stream": "^3.1.1" - }, - "dependencies": { - "readable-stream": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.2.0.tgz", - "integrity": "sha512-RV20kLjdmpZuTF1INEb9IA3L68Nmi+Ri7ppZqo78wj//Pn62fCoJyV9zalccNzDD/OuJpMG4f+pfMl8+L6QdGw==", - "dev": true, - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - } - } - }, - "http-cache-semantics": { - "version": "3.8.1", - "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-3.8.1.tgz", - "integrity": "sha512-5ai2iksyV8ZXmnZhHH4rWPoxxistEexSi5936zIQ1bnNTW5VnA85B6P/VpXiRM017IgRvb2kKo1a//y+0wSp3w==", - "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" - }, - "dependencies": { - "statuses": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", - "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", - "dev": true - } - } - }, - "http-parser-js": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.0.tgz", - "integrity": "sha512-cZdEF7r4gfRIq7ezX9J0T+kQmJNOub71dWbgAXVHDct80TKP4MCETtZQ31xyv38UwgzkWPYF/Xc0ge55dW9Z9w==", - "dev": true - }, - "http-proxy": { - "version": "1.15.2", - "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.15.2.tgz", - "integrity": "sha1-ZC/cr/5S00SNK9o7AHnpQJBk2jE=", - "dev": true, - "requires": { - "eventemitter3": "1.x.x", - "requires-port": "1.x.x" - } - }, - "http-proxy-agent": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-2.1.0.tgz", - "integrity": "sha512-qwHbBLV7WviBl0rQsOzH6o5lwyOIvwp/BdFnvVxXORldu5TmjFfjzBcWUWS5kWAZhmv+JtiDhSuQCp4sBfbIgg==", - "dev": true, - "requires": { - "agent-base": "4", - "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" - } - } - } - }, - "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" - }, - "dependencies": { - "eventemitter3": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.0.tgz", - "integrity": "sha512-ivIvhpq/Y0uSjcHDcOIccjmYjGLcP09MFGE7ysAwkAvkXfpZlC985pH2/ui64DKazbTW/4kN3yqozUxlXzI6cA==", - "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-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.2.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - } - } - }, - "humanize-ms": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", - "integrity": "sha1-xG4xWaKT9riW2ikxbYtv6Lt5u+0=", - "dev": true, - "requires": { - "ms": "^2.0.0" - } - }, - "husky": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/husky/-/husky-1.3.1.tgz", - "integrity": "sha512-86U6sVVVf4b5NYSZ0yvv88dRgBSSXXmHaiq5pP4KDj5JVzdwKgBjEtUPOm8hcoytezFwbU+7gotXNhpHdystlg==", - "dev": true, - "requires": { - "cosmiconfig": "^5.0.7", - "execa": "^1.0.0", - "find-up": "^3.0.0", - "get-stdin": "^6.0.0", - "is-ci": "^2.0.0", - "pkg-dir": "^3.0.0", - "please-upgrade-node": "^3.1.1", - "read-pkg": "^4.0.1", - "run-node": "^1.0.0", - "slash": "^2.0.0" - }, - "dependencies": { - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "execa": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", - "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", - "dev": true, - "requires": { - "cross-spawn": "^6.0.0", - "get-stream": "^4.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" - } - }, - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "p-limit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", - "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.1.0.tgz", - "integrity": "sha512-H2RyIJ7+A3rjkwKC2l5GGtU4H1vkxKCAGsWasNVd0Set+6i4znxbWy6/j16YDPJDWxhsgZiKAstMEP8wCdSpjA==", - "dev": true - }, - "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" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - }, - "pkg-dir": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", - "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", - "dev": true, - "requires": { - "find-up": "^3.0.0" - } - }, - "read-pkg": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-4.0.1.tgz", - "integrity": "sha1-ljYlN48+HE1IyFhytabsfV0JMjc=", - "dev": true, - "requires": { - "normalize-package-data": "^2.3.2", - "parse-json": "^4.0.0", - "pify": "^3.0.0" - } - }, - "slash": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", - "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", - "dev": true - } - } - }, - "iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "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=", - "dev": true - }, - "icss-utils": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-4.1.0.tgz", - "integrity": "sha512-3DEun4VOeMvSczifM3F2cKQrDQ5Pj6WKhkOq6HD4QTnDUAq8MQRxy5TX6Sy1iY6WPBe4gQ3p5vTECjbIkglkkQ==", - "dev": true, - "requires": { - "postcss": "^7.0.14" - } - }, - "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 - }, - "ignore-walk": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-3.0.1.tgz", - "integrity": "sha512-DTVlMx3IYPe0/JJcYP7Gxg7ttZZu3IInhuEhbchuqneY9wWe5Ojy2mXLBaQFUQmo0AW2r3qG7m1mg86js+gnlQ==", - "dev": true, - "requires": { - "minimatch": "^3.0.4" - } - }, - "immutable": { - "version": "3.8.2", - "resolved": "https://registry.npmjs.org/immutable/-/immutable-3.8.2.tgz", - "integrity": "sha1-wkOZUUVbs5kT2vKBN28VMOEErfM=", - "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-fresh": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-2.0.0.tgz", - "integrity": "sha1-2BNVwVYS04bGH53dOSLUMEgipUY=", - "dev": true, - "requires": { - "caller-path": "^2.0.0", - "resolve-from": "^3.0.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": "2.0.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-2.0.0.tgz", - "integrity": "sha512-b6s04m3O+s3CGSbqDIyP4R6aAwAeYlVq9+WUWep6iHa8ETRf9yei1U48C5MmfJmV9AiLYYBKPMq/W+/WRpQmCQ==", - "dev": true, - "requires": { - "pkg-dir": "^3.0.0", - "resolve-cwd": "^2.0.0" - }, - "dependencies": { - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "p-limit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", - "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.1.0.tgz", - "integrity": "sha512-H2RyIJ7+A3rjkwKC2l5GGtU4H1vkxKCAGsWasNVd0Set+6i4znxbWy6/j16YDPJDWxhsgZiKAstMEP8wCdSpjA==", - "dev": true - }, - "pkg-dir": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", - "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", - "dev": true, - "requires": { - "find-up": "^3.0.0" - } - } - } - }, - "imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", - "dev": true - }, - "indent-string": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-3.2.0.tgz", - "integrity": "sha1-Sl/W0nzDMvN+VBmlBNu4NxBckok=", - "dev": true - }, - "indexes-of": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/indexes-of/-/indexes-of-1.0.1.tgz", - "integrity": "sha1-8w9xbI4r00bHtn0985FVZqfAVgc=", - "dev": true - }, - "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 - }, - "inquirer": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-3.0.6.tgz", - "integrity": "sha1-4EqqnQW3o8ubD0B9BDdfBEcZA0c=", - "requires": { - "ansi-escapes": "^1.1.0", - "chalk": "^1.0.0", - "cli-cursor": "^2.1.0", - "cli-width": "^2.0.0", - "external-editor": "^2.0.1", - "figures": "^2.0.0", - "lodash": "^4.3.0", - "mute-stream": "0.0.7", - "run-async": "^2.2.0", - "rx": "^4.1.0", - "string-width": "^2.0.0", - "strip-ansi": "^3.0.0", - "through": "^2.3.6" - } - }, - "insight": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/insight/-/insight-0.10.1.tgz", - "integrity": "sha512-kLGeYQkh18f8KuC68QKdi0iwUcIaayJVB/STpX7x452/7pAUm1yfG4giJwcxbrTh0zNYtc8kBR+6maLMOzglOQ==", - "dev": true, - "requires": { - "async": "^2.1.4", - "chalk": "^2.3.0", - "conf": "^1.3.1", - "inquirer": "^5.0.0", - "lodash.debounce": "^4.0.8", - "os-name": "^2.0.1", - "request": "^2.74.0", - "tough-cookie": "^2.0.0", - "uuid": "^3.0.0" - }, - "dependencies": { - "ansi-escapes": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", - "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==", - "dev": true - }, - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", - "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" - } - }, - "async": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", - "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", - "dev": true, - "requires": { - "lodash": "^4.17.11" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "conf": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/conf/-/conf-1.4.0.tgz", - "integrity": "sha512-bzlVWS2THbMetHqXKB8ypsXN4DQ/1qopGwNJi1eYbpwesJcd86FBjFciCQX/YwAhp9bM7NVnPFqZ5LpV7gP0Dg==", - "dev": true, - "requires": { - "dot-prop": "^4.1.0", - "env-paths": "^1.0.0", - "make-dir": "^1.0.0", - "pkg-up": "^2.0.0", - "write-file-atomic": "^2.3.0" - } - }, - "inquirer": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-5.2.0.tgz", - "integrity": "sha512-E9BmnJbAKLPGonz0HeWHtbKf+EeSP93paWO3ZYoUpq/aowXvYGjjCSuashhXPpzbArIjBbji39THkxTz9ZeEUQ==", - "dev": true, - "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", - "cli-cursor": "^2.1.0", - "cli-width": "^2.0.0", - "external-editor": "^2.1.0", - "figures": "^2.0.0", - "lodash": "^4.3.0", - "mute-stream": "0.0.7", - "run-async": "^2.2.0", - "rxjs": "^5.5.2", - "string-width": "^2.1.0", - "strip-ansi": "^4.0.0", - "through": "^2.3.6" - } - }, - "rxjs": { - "version": "5.5.12", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-5.5.12.tgz", - "integrity": "sha512-xx2itnL5sBbqeeiVgNPVuQQ1nC8Jp2WfNJhXWHmElW9YmrpS9UVnNzhP3EH3HFqexO5Tlp8GhYY+WEcqcVMvGw==", - "dev": true, - "requires": { - "symbol-observable": "1.0.1" - } - }, - "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" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "symbol-observable": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.0.1.tgz", - "integrity": "sha1-g0D8RwLDEi310iKI+IKD9RPT/dQ=", - "dev": true - } - } - }, - "internal-ip": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/internal-ip/-/internal-ip-3.0.1.tgz", - "integrity": "sha512-NXXgESC2nNVtU+pqmC9e6R8B1GpKxzsAQhffvh5AL79qKnodd+L7tnEQmTiUAVngqLalPbSqRA7XGIEL5nCd0Q==", - "dev": true, - "requires": { - "default-gateway": "^2.6.0", - "ipaddr.js": "^1.5.2" - } - }, - "interpret": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz", - "integrity": "sha512-mT34yGKMNceBQUoVn7iCDKDntA7SC6gycMAWzGx1z/CMCTV7b2AAtXlo3nRyHZ1FelRkQbQjprHSYGwzLtkVbw==", - "dev": true - }, - "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 - }, - "ip-regex": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-2.1.0.tgz", - "integrity": "sha1-+ni/XS5pE8kRzp+BnuUUa7bYROk=", - "dev": true - }, - "ipaddr.js": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.8.0.tgz", - "integrity": "sha1-6qM9bd16zo9/b+DJygRA5wZzix4=", - "dev": true - }, - "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=", - "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-callable": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.4.tgz", - "integrity": "sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==", - "dev": true - }, - "is-ci": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", - "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", - "dev": true, - "requires": { - "ci-info": "^2.0.0" - } - }, - "is-color-stop": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-color-stop/-/is-color-stop-1.1.0.tgz", - "integrity": "sha1-z/9HGu5N1cnhWFmPvhKWe1za00U=", - "dev": true, - "requires": { - "css-color-names": "^0.0.4", - "hex-color-regex": "^1.1.0", - "hsl-regex": "^1.0.0", - "hsla-regex": "^1.0.0", - "rgb-regex": "^1.0.1", - "rgba-regex": "^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=", - "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-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-generator-fn": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.0.0.tgz", - "integrity": "sha512-elzyIdM7iKoFHzcrndIqjYomImhxrFRnGP3galODoII4TB9gI7mZ+FnlLQmmjf27SxHS2gKEeyhX5/+YRS6H9g==", - "dev": true - }, - "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-number-like": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/is-number-like/-/is-number-like-1.0.8.tgz", - "integrity": "sha512-6rZi3ezCyFcn5L71ywzz2bS5b2Igl1En3eTlZlvKjpz1n3IZLAYMbKYAIQgFmEu0GENg92ziU/faEOA/aixjbA==", - "dev": true, - "requires": { - "lodash.isfinite": "^3.3.2" - } - }, - "is-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", - "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", - "dev": true - }, - "is-object": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-object/-/is-object-1.0.1.tgz", - "integrity": "sha1-iVJojF7C/9awPsyF52ngKQMINHA=", - "dev": true - }, - "is-observable": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-observable/-/is-observable-1.1.0.tgz", - "integrity": "sha512-NqCa4Sa2d+u7BWc6CukaObG3Fh+CU9bvixbpcXYhy2VvYS7vVGIdAgnIS5Ks3A/cqk4rebLJ9s8zBstT2aKnIA==", - "dev": true, - "requires": { - "symbol-observable": "^1.1.0" - } - }, - "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-obj": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz", - "integrity": "sha1-caUMhCnfync8kqOQpKA7OfzVHT4=", - "dev": true - }, - "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-promise": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", - "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=" - }, - "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-regexp": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-regexp/-/is-regexp-1.0.0.tgz", - "integrity": "sha1-/S2INUXEa6xaYz57mgnof6LLUGk=", - "dev": true - }, - "is-resolvable": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-resolvable/-/is-resolvable-1.1.0.tgz", - "integrity": "sha512-qgDYXFSR5WvEfuS5dMj6oTMEbrrSaM0CrFk2Yiq/gXnBvD9pMa2jGXxyhGLfvhZpuMZe18CJpFxAt3CRs42NMg==", - "dev": true - }, - "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=", - "dev": true - }, - "is-scoped": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-scoped/-/is-scoped-1.0.0.tgz", - "integrity": "sha1-RJypgpnnEwOCViieyytUDcQ3yzA=", - "dev": true, - "requires": { - "scoped-regex": "^1.0.0" - } - }, - "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": "3.0.0", - "resolved": "https://registry.npmjs.org/is-svg/-/is-svg-3.0.0.tgz", - "integrity": "sha512-gi4iHK53LR2ujhLVVj+37Ykh9GLqYHX6JOVXbLAucaG/Cqw9xwdFOjDM2qeifLs1sF1npXXFvDu0r5HNgCMrzQ==", - "dev": true, - "requires": { - "html-comment-regex": "^1.1.0" - } - }, - "is-symbol": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.2.tgz", - "integrity": "sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw==", - "dev": true, - "requires": { - "has-symbols": "^1.0.0" - } - }, - "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.3", - "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-3.0.3.tgz", - "integrity": "sha512-8cJBL5tTd2OS0dM4jz07wQd5g0dCCqIhUxPIGtZfa5L6hWlvV5MHTITy/DBAsF+Oe2LS1X3krBUhNwaGUWpWxw==", - "dev": true, - "requires": { - "buffer-alloc": "^1.2.0" - } - }, - "isemail": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/isemail/-/isemail-3.2.0.tgz", - "integrity": "sha512-zKqkK+O+dGqevc93KNsbZ/TqTUFd46MwWjYOoMrjIMZ51eU7DtQG3Wmd9SQQT7i7RVnuTPEiYEWHU3MSbxC1Tg==", - "dev": true, - "requires": { - "punycode": "2.x.x" - } - }, - "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-api": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/istanbul-api/-/istanbul-api-2.1.1.tgz", - "integrity": "sha512-kVmYrehiwyeBAk/wE71tW6emzLiHGjYIiDrc8sfyty4F8M02/lrgXSm+R1kXysmF20zArvmZXjlE/mg24TVPJw==", - "dev": true, - "requires": { - "async": "^2.6.1", - "compare-versions": "^3.2.1", - "fileset": "^2.0.3", - "istanbul-lib-coverage": "^2.0.3", - "istanbul-lib-hook": "^2.0.3", - "istanbul-lib-instrument": "^3.1.0", - "istanbul-lib-report": "^2.0.4", - "istanbul-lib-source-maps": "^3.0.2", - "istanbul-reports": "^2.1.1", - "js-yaml": "^3.12.0", - "make-dir": "^1.3.0", - "minimatch": "^3.0.4", - "once": "^1.4.0" - }, - "dependencies": { - "async": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", - "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", - "dev": true, - "requires": { - "lodash": "^4.17.11" - } - } - } - }, - "istanbul-lib-coverage": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.3.tgz", - "integrity": "sha512-dKWuzRGCs4G+67VfW9pBFFz2Jpi4vSp/k7zBcJ888ofV5Mi1g5CUML5GvMvV6u9Cjybftu+E8Cgp+k0dI1E5lw==", - "dev": true - }, - "istanbul-lib-hook": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/istanbul-lib-hook/-/istanbul-lib-hook-2.0.3.tgz", - "integrity": "sha512-CLmEqwEhuCYtGcpNVJjLV1DQyVnIqavMLFHV/DP+np/g3qvdxu3gsPqYoJMXm15sN84xOlckFB3VNvRbf5yEgA==", - "dev": true, - "requires": { - "append-transform": "^1.0.0" - } - }, - "istanbul-lib-instrument": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-3.1.0.tgz", - "integrity": "sha512-ooVllVGT38HIk8MxDj/OIHXSYvH+1tq/Vb38s8ixt9GoJadXska4WkGY+0wkmtYCZNYtaARniH/DixUGGLZ0uA==", - "dev": true, - "requires": { - "@babel/generator": "^7.0.0", - "@babel/parser": "^7.0.0", - "@babel/template": "^7.0.0", - "@babel/traverse": "^7.0.0", - "@babel/types": "^7.0.0", - "istanbul-lib-coverage": "^2.0.3", - "semver": "^5.5.0" - } - }, - "istanbul-lib-report": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-2.0.4.tgz", - "integrity": "sha512-sOiLZLAWpA0+3b5w5/dq0cjm2rrNdAfHWaGhmn7XEFW6X++IV9Ohn+pnELAl9K3rfpaeBfbmH9JU5sejacdLeA==", - "dev": true, - "requires": { - "istanbul-lib-coverage": "^2.0.3", - "make-dir": "^1.3.0", - "supports-color": "^6.0.0" - }, - "dependencies": { - "supports-color": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", - "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "istanbul-lib-source-maps": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-3.0.2.tgz", - "integrity": "sha512-JX4v0CiKTGp9fZPmoxpu9YEkPbEqCqBbO3403VabKjH+NRXo72HafD5UgnjTEqHL2SAjaZK1XDuDOkn6I5QVfQ==", - "dev": true, - "requires": { - "debug": "^4.1.1", - "istanbul-lib-coverage": "^2.0.3", - "make-dir": "^1.3.0", - "rimraf": "^2.6.2", - "source-map": "^0.6.1" - }, - "dependencies": { - "debug": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", - "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "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 - } - } - }, - "istanbul-reports": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-2.1.1.tgz", - "integrity": "sha512-FzNahnidyEPBCI0HcufJoSEoKykesRlFcSzQqjH9x0+LC8tnnE/p/90PBLu8iZTxr8yYZNyTtiAujUqyN+CIxw==", - "dev": true, - "requires": { - "handlebars": "^4.1.0" - } - }, - "istextorbinary": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/istextorbinary/-/istextorbinary-2.5.1.tgz", - "integrity": "sha512-pv/JNPWnfpwGjPx7JrtWTwsWsxkrK3fNzcEVnt92YKEIErps4Fsk49+qzCe9iQF2hjqK8Naqf8P9kzoeCuQI1g==", - "dev": true, - "requires": { - "binaryextensions": "^2.1.2", - "editions": "^2.1.3", - "textextensions": "^2.4.0" - } - }, - "isurl": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isurl/-/isurl-1.0.0.tgz", - "integrity": "sha512-1P/yWsxPlDtn7QeRD+ULKQPaIaN6yF368GZ2vDfv0AL0NwpStafjWCDDdn0k8wgFMWpVAqG7oJhxHnlud42i9w==", - "dev": true, - "requires": { - "has-to-string-tag-x": "^1.2.0", - "is-object": "^1.0.1" - } - }, - "jest": { - "version": "24.1.0", - "resolved": "https://registry.npmjs.org/jest/-/jest-24.1.0.tgz", - "integrity": "sha512-+q91L65kypqklvlRFfXfdzUKyngQLOcwGhXQaLmVHv+d09LkNXuBuGxlofTFW42XMzu3giIcChchTsCNUjQ78A==", - "dev": true, - "requires": { - "import-local": "^2.0.0", - "jest-cli": "^24.1.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 - }, - "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" - } - }, - "camelcase": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.2.0.tgz", - "integrity": "sha512-IXFsBS2pC+X0j0N/GE7Dm7j3bsEBp+oTpb7F50dwEVX7rf3IgwO9XatnegTsDtniKCUtEJH4fSU6Asw7uoVLfQ==", - "dev": true - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "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" - } - }, - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "execa": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", - "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", - "dev": true, - "requires": { - "cross-spawn": "^6.0.0", - "get-stream": "^4.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" - } - }, - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "invert-kv": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", - "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==", - "dev": true - }, - "jest-cli": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-24.5.0.tgz", - "integrity": "sha512-P+Jp0SLO4KWN0cGlNtC7JV0dW1eSFR7eRpoOucP2UM0sqlzp/bVHeo71Omonvigrj9AvCKy7NtQANtqJ7FXz8g==", - "dev": true, - "requires": { - "@jest/core": "^24.5.0", - "@jest/test-result": "^24.5.0", - "@jest/types": "^24.5.0", - "chalk": "^2.0.1", - "exit": "^0.1.2", - "import-local": "^2.0.0", - "is-ci": "^2.0.0", - "jest-config": "^24.5.0", - "jest-util": "^24.5.0", - "jest-validate": "^24.5.0", - "prompts": "^2.0.1", - "realpath-native": "^1.1.0", - "yargs": "^12.0.2" - } - }, - "lcid": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz", - "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==", - "dev": true, - "requires": { - "invert-kv": "^2.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "mem": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/mem/-/mem-4.2.0.tgz", - "integrity": "sha512-5fJxa68urlY0Ir8ijatKa3eRz5lwXnRCTvo9+TbTGAuTFJOwpGcY0X05moBd0nW45965Njt4CDI2GFQoG8DvqA==", - "dev": true, - "requires": { - "map-age-cleaner": "^0.1.1", - "mimic-fn": "^2.0.0", - "p-is-promise": "^2.0.0" - } - }, - "mimic-fn": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.0.0.tgz", - "integrity": "sha512-jbex9Yd/3lmICXwYT6gA/j2mNQGU48wCh/VzRd+/Y/PjYQtlg1gLMdZqvu9s/xH7qKvngxRObl56XZR609IMbA==", - "dev": true - }, - "os-locale": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz", - "integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==", - "dev": true, - "requires": { - "execa": "^1.0.0", - "lcid": "^2.0.0", - "mem": "^4.0.0" - } - }, - "p-limit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", - "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.1.0.tgz", - "integrity": "sha512-H2RyIJ7+A3rjkwKC2l5GGtU4H1vkxKCAGsWasNVd0Set+6i4znxbWy6/j16YDPJDWxhsgZiKAstMEP8wCdSpjA==", - "dev": true - }, - "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" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "yargs": { - "version": "12.0.5", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.5.tgz", - "integrity": "sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw==", - "dev": true, - "requires": { - "cliui": "^4.0.0", - "decamelize": "^1.2.0", - "find-up": "^3.0.0", - "get-caller-file": "^1.0.1", - "os-locale": "^3.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 || ^4.0.0", - "yargs-parser": "^11.1.1" - } - }, - "yargs-parser": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-11.1.1.tgz", - "integrity": "sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ==", - "dev": true, - "requires": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" - } - } - } - }, - "jest-changed-files": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-24.5.0.tgz", - "integrity": "sha512-Ikl29dosYnTsH9pYa1Tv9POkILBhN/TLZ37xbzgNsZ1D2+2n+8oEZS2yP1BrHn/T4Rs4Ggwwbp/x8CKOS5YJOg==", - "dev": true, - "requires": { - "@jest/types": "^24.5.0", - "execa": "^1.0.0", - "throat": "^4.0.0" - }, - "dependencies": { - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "execa": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", - "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", - "dev": true, - "requires": { - "cross-spawn": "^6.0.0", - "get-stream": "^4.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" - } - } - } - }, - "jest-config": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-24.5.0.tgz", - "integrity": "sha512-t2UTh0Z2uZhGBNVseF8wA2DS2SuBiLOL6qpLq18+OZGfFUxTM7BzUVKyHFN/vuN+s/aslY1COW95j1Rw81huOQ==", - "dev": true, - "requires": { - "@babel/core": "^7.1.0", - "@jest/types": "^24.5.0", - "babel-jest": "^24.5.0", - "chalk": "^2.0.1", - "glob": "^7.1.1", - "jest-environment-jsdom": "^24.5.0", - "jest-environment-node": "^24.5.0", - "jest-get-type": "^24.3.0", - "jest-jasmine2": "^24.5.0", - "jest-regex-util": "^24.3.0", - "jest-resolve": "^24.5.0", - "jest-util": "^24.5.0", - "jest-validate": "^24.5.0", - "micromatch": "^3.1.10", - "pretty-format": "^24.5.0", - "realpath-native": "^1.1.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-diff": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-24.5.0.tgz", - "integrity": "sha512-mCILZd9r7zqL9Uh6yNoXjwGQx0/J43OD2vvWVKwOEOLZliQOsojXwqboubAQ+Tszrb6DHGmNU7m4whGeB9YOqw==", - "dev": true, - "requires": { - "chalk": "^2.0.1", - "diff-sequences": "^24.3.0", - "jest-get-type": "^24.3.0", - "pretty-format": "^24.5.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-docblock": { - "version": "24.3.0", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-24.3.0.tgz", - "integrity": "sha512-nlANmF9Yq1dufhFlKG9rasfQlrY7wINJbo3q01tu56Jv5eBU5jirylhF2O5ZBnLxzOVBGRDz/9NAwNyBtG4Nyg==", - "dev": true, - "requires": { - "detect-newline": "^2.1.0" - } - }, - "jest-each": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-24.5.0.tgz", - "integrity": "sha512-6gy3Kh37PwIT5sNvNY2VchtIFOOBh8UCYnBlxXMb5sr5wpJUDPTUATX2Axq1Vfk+HWTMpsYPeVYp4TXx5uqUBw==", - "dev": true, - "requires": { - "@jest/types": "^24.5.0", - "chalk": "^2.0.1", - "jest-get-type": "^24.3.0", - "jest-util": "^24.5.0", - "pretty-format": "^24.5.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-environment-jsdom": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-24.5.0.tgz", - "integrity": "sha512-62Ih5HbdAWcsqBx2ktUnor/mABBo1U111AvZWcLKeWN/n/gc5ZvDBKe4Og44fQdHKiXClrNGC6G0mBo6wrPeGQ==", - "dev": true, - "requires": { - "@jest/environment": "^24.5.0", - "@jest/fake-timers": "^24.5.0", - "@jest/types": "^24.5.0", - "jest-mock": "^24.5.0", - "jest-util": "^24.5.0", - "jsdom": "^11.5.1" - } - }, - "jest-environment-node": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-24.5.0.tgz", - "integrity": "sha512-du6FuyWr/GbKLsmAbzNF9mpr2Iu2zWSaq/BNHzX+vgOcts9f2ayXBweS7RAhr+6bLp6qRpMB6utAMF5Ygktxnw==", - "dev": true, - "requires": { - "@jest/environment": "^24.5.0", - "@jest/fake-timers": "^24.5.0", - "@jest/types": "^24.5.0", - "jest-mock": "^24.5.0", - "jest-util": "^24.5.0" - } - }, - "jest-get-type": { - "version": "24.3.0", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-24.3.0.tgz", - "integrity": "sha512-HYF6pry72YUlVcvUx3sEpMRwXEWGEPlJ0bSPVnB3b3n++j4phUEoSPcS6GC0pPJ9rpyPSe4cb5muFo6D39cXow==", - "dev": true - }, - "jest-haste-map": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-24.5.0.tgz", - "integrity": "sha512-mb4Yrcjw9vBgSvobDwH8QUovxApdimGcOkp+V1ucGGw4Uvr3VzZQBJhNm1UY3dXYm4XXyTW2G7IBEZ9pM2ggRQ==", - "dev": true, - "requires": { - "@jest/types": "^24.5.0", - "fb-watchman": "^2.0.0", - "graceful-fs": "^4.1.15", - "invariant": "^2.2.4", - "jest-serializer": "^24.4.0", - "jest-util": "^24.5.0", - "jest-worker": "^24.4.0", - "micromatch": "^3.1.10", - "sane": "^4.0.3" - } - }, - "jest-jasmine2": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-jasmine2/-/jest-jasmine2-24.5.0.tgz", - "integrity": "sha512-sfVrxVcx1rNUbBeyIyhkqZ4q+seNKyAG6iM0S2TYBdQsXjoFDdqWFfsUxb6uXSsbimbXX/NMkJIwUZ1uT9+/Aw==", - "dev": true, - "requires": { - "@babel/traverse": "^7.1.0", - "@jest/environment": "^24.5.0", - "@jest/test-result": "^24.5.0", - "@jest/types": "^24.5.0", - "chalk": "^2.0.1", - "co": "^4.6.0", - "expect": "^24.5.0", - "is-generator-fn": "^2.0.0", - "jest-each": "^24.5.0", - "jest-matcher-utils": "^24.5.0", - "jest-message-util": "^24.5.0", - "jest-runtime": "^24.5.0", - "jest-snapshot": "^24.5.0", - "jest-util": "^24.5.0", - "pretty-format": "^24.5.0", - "throat": "^4.0.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-junit": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/jest-junit/-/jest-junit-6.2.1.tgz", - "integrity": "sha512-zMbwKzZGo9TQOjdBUNQdTEf81QvOrwiQtLIUSEyCwPXYx/G/DJGXEJcqs8viXxn6poJ4Xh4pYGDLD0DKDwtfVA==", - "dev": true, - "requires": { - "jest-validate": "^24.0.0", - "mkdirp": "^0.5.1", - "strip-ansi": "^4.0.0", - "xml": "^1.0.1" - }, - "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 - }, - "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" - } - } - } - }, - "jest-leak-detector": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-24.5.0.tgz", - "integrity": "sha512-LZKBjGovFRx3cRBkqmIg+BZnxbrLqhQl09IziMk3oeh1OV81Hg30RUIx885mq8qBv1PA0comB9bjKcuyNO1bCQ==", - "dev": true, - "requires": { - "pretty-format": "^24.5.0" - } - }, - "jest-matcher-utils": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-24.5.0.tgz", - "integrity": "sha512-QM1nmLROjLj8GMGzg5VBra3I9hLpjMPtF1YqzQS3rvWn2ltGZLrGAO1KQ9zUCVi5aCvrkbS5Ndm2evIP9yZg1Q==", - "dev": true, - "requires": { - "chalk": "^2.0.1", - "jest-diff": "^24.5.0", - "jest-get-type": "^24.3.0", - "pretty-format": "^24.5.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-message-util": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-24.5.0.tgz", - "integrity": "sha512-6ZYgdOojowCGiV0D8WdgctZEAe+EcFU+KrVds+0ZjvpZurUW2/oKJGltJ6FWY2joZwYXN5VL36GPV6pNVRqRnQ==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "@jest/test-result": "^24.5.0", - "@jest/types": "^24.5.0", - "@types/stack-utils": "^1.0.1", - "chalk": "^2.0.1", - "micromatch": "^3.1.10", - "slash": "^2.0.0", - "stack-utils": "^1.0.1" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "slash": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", - "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-mock": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-24.5.0.tgz", - "integrity": "sha512-ZnAtkWrKf48eERgAOiUxVoFavVBziO2pAi2MfZ1+bGXVkDfxWLxU0//oJBkgwbsv6OAmuLBz4XFFqvCFMqnGUw==", - "dev": true, - "requires": { - "@jest/types": "^24.5.0" - } - }, - "jest-pnp-resolver": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.1.tgz", - "integrity": "sha512-pgFw2tm54fzgYvc/OHrnysABEObZCUNFnhjoRjaVOCN8NYc032/gVjPaHD4Aq6ApkSieWtfKAFQtmDKAmhupnQ==", - "dev": true - }, - "jest-preset-angular": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/jest-preset-angular/-/jest-preset-angular-6.0.2.tgz", - "integrity": "sha512-uhrllY41tUvkeR41aX9bU5w3/EvvmwZiJ3UitDhRSEJL2Jvq2N/xKlmw7qvlZoGZnciFjOUJ2WDKv5fmCrvnQA==", - "dev": true, - "requires": { - "@types/jest": "^23.3.1", - "jest-zone-patch": ">=0.0.9 <1.0.0", - "ts-jest": "~23.1.3" - }, - "dependencies": { - "@types/jest": { - "version": "23.3.14", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-23.3.14.tgz", - "integrity": "sha512-Q5hTcfdudEL2yOmluA1zaSyPbzWPmJ3XfSWeP3RyoYvS9hnje1ZyagrZOuQ6+1nQC1Gw+7gap3pLNL3xL6UBug==", - "dev": true - } - } - }, - "jest-regex-util": { - "version": "24.3.0", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-24.3.0.tgz", - "integrity": "sha512-tXQR1NEOyGlfylyEjg1ImtScwMq8Oh3iJbGTjN7p0J23EuVX1MA8rwU69K4sLbCmwzgCUbVkm0FkSF9TdzOhtg==", - "dev": true - }, - "jest-resolve": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-24.5.0.tgz", - "integrity": "sha512-ZIfGqLX1Rg8xJpQqNjdoO8MuxHV1q/i2OO1hLXjgCWFWs5bsedS8UrOdgjUqqNae6DXA+pCyRmdcB7lQEEbXew==", - "dev": true, - "requires": { - "@jest/types": "^24.5.0", - "browser-resolve": "^1.11.3", - "chalk": "^2.0.1", - "jest-pnp-resolver": "^1.2.1", - "realpath-native": "^1.1.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-resolve-dependencies": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-24.5.0.tgz", - "integrity": "sha512-dRVM1D+gWrFfrq2vlL5P9P/i8kB4BOYqYf3S7xczZ+A6PC3SgXYSErX/ScW/469pWMboM1uAhgLF+39nXlirCQ==", - "dev": true, - "requires": { - "@jest/types": "^24.5.0", - "jest-regex-util": "^24.3.0", - "jest-snapshot": "^24.5.0" - } - }, - "jest-runner": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-24.5.0.tgz", - "integrity": "sha512-oqsiS9TkIZV5dVkD+GmbNfWBRPIvxqmlTQ+AQUJUQ07n+4xTSDc40r+aKBynHw9/tLzafC00DIbJjB2cOZdvMA==", - "dev": true, - "requires": { - "@jest/console": "^24.3.0", - "@jest/environment": "^24.5.0", - "@jest/test-result": "^24.5.0", - "@jest/types": "^24.5.0", - "chalk": "^2.4.2", - "exit": "^0.1.2", - "graceful-fs": "^4.1.15", - "jest-config": "^24.5.0", - "jest-docblock": "^24.3.0", - "jest-haste-map": "^24.5.0", - "jest-jasmine2": "^24.5.0", - "jest-leak-detector": "^24.5.0", - "jest-message-util": "^24.5.0", - "jest-resolve": "^24.5.0", - "jest-runtime": "^24.5.0", - "jest-util": "^24.5.0", - "jest-worker": "^24.4.0", - "source-map-support": "^0.5.6", - "throat": "^4.0.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-runtime": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-24.5.0.tgz", - "integrity": "sha512-GTFHzfLdwpaeoDPilNpBrorlPoNZuZrwKKzKJs09vWwHo+9TOsIIuszK8cWOuKC7ss07aN1922Ge8fsGdsqCuw==", - "dev": true, - "requires": { - "@jest/console": "^24.3.0", - "@jest/environment": "^24.5.0", - "@jest/source-map": "^24.3.0", - "@jest/transform": "^24.5.0", - "@jest/types": "^24.5.0", - "@types/yargs": "^12.0.2", - "chalk": "^2.0.1", - "exit": "^0.1.2", - "glob": "^7.1.3", - "graceful-fs": "^4.1.15", - "jest-config": "^24.5.0", - "jest-haste-map": "^24.5.0", - "jest-message-util": "^24.5.0", - "jest-mock": "^24.5.0", - "jest-regex-util": "^24.3.0", - "jest-resolve": "^24.5.0", - "jest-snapshot": "^24.5.0", - "jest-util": "^24.5.0", - "jest-validate": "^24.5.0", - "realpath-native": "^1.1.0", - "slash": "^2.0.0", - "strip-bom": "^3.0.0", - "yargs": "^12.0.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 - }, - "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" - } - }, - "camelcase": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.2.0.tgz", - "integrity": "sha512-IXFsBS2pC+X0j0N/GE7Dm7j3bsEBp+oTpb7F50dwEVX7rf3IgwO9XatnegTsDtniKCUtEJH4fSU6Asw7uoVLfQ==", - "dev": true - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "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" - } - }, - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "execa": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", - "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", - "dev": true, - "requires": { - "cross-spawn": "^6.0.0", - "get-stream": "^4.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" - } - }, - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "invert-kv": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", - "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==", - "dev": true - }, - "lcid": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz", - "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==", - "dev": true, - "requires": { - "invert-kv": "^2.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "mem": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/mem/-/mem-4.2.0.tgz", - "integrity": "sha512-5fJxa68urlY0Ir8ijatKa3eRz5lwXnRCTvo9+TbTGAuTFJOwpGcY0X05moBd0nW45965Njt4CDI2GFQoG8DvqA==", - "dev": true, - "requires": { - "map-age-cleaner": "^0.1.1", - "mimic-fn": "^2.0.0", - "p-is-promise": "^2.0.0" - } - }, - "mimic-fn": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.0.0.tgz", - "integrity": "sha512-jbex9Yd/3lmICXwYT6gA/j2mNQGU48wCh/VzRd+/Y/PjYQtlg1gLMdZqvu9s/xH7qKvngxRObl56XZR609IMbA==", - "dev": true - }, - "os-locale": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz", - "integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==", - "dev": true, - "requires": { - "execa": "^1.0.0", - "lcid": "^2.0.0", - "mem": "^4.0.0" - } - }, - "p-limit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", - "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.1.0.tgz", - "integrity": "sha512-H2RyIJ7+A3rjkwKC2l5GGtU4H1vkxKCAGsWasNVd0Set+6i4znxbWy6/j16YDPJDWxhsgZiKAstMEP8wCdSpjA==", - "dev": true - }, - "slash": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", - "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", - "dev": true - }, - "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" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "yargs": { - "version": "12.0.5", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.5.tgz", - "integrity": "sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw==", - "dev": true, - "requires": { - "cliui": "^4.0.0", - "decamelize": "^1.2.0", - "find-up": "^3.0.0", - "get-caller-file": "^1.0.1", - "os-locale": "^3.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 || ^4.0.0", - "yargs-parser": "^11.1.1" - } - }, - "yargs-parser": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-11.1.1.tgz", - "integrity": "sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ==", - "dev": true, - "requires": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" - } - } - } - }, - "jest-serializer": { - "version": "24.4.0", - "resolved": "https://registry.npmjs.org/jest-serializer/-/jest-serializer-24.4.0.tgz", - "integrity": "sha512-k//0DtglVstc1fv+GY/VHDIjrtNjdYvYjMlbLUed4kxrE92sIUewOi5Hj3vrpB8CXfkJntRPDRjCrCvUhBdL8Q==", - "dev": true - }, - "jest-snapshot": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-24.5.0.tgz", - "integrity": "sha512-eBEeJb5ROk0NcpodmSKnCVgMOo+Qsu5z9EDl3tGffwPzK1yV37mjGWF2YeIz1NkntgTzP+fUL4s09a0+0dpVWA==", - "dev": true, - "requires": { - "@babel/types": "^7.0.0", - "@jest/types": "^24.5.0", - "chalk": "^2.0.1", - "expect": "^24.5.0", - "jest-diff": "^24.5.0", - "jest-matcher-utils": "^24.5.0", - "jest-message-util": "^24.5.0", - "jest-resolve": "^24.5.0", - "mkdirp": "^0.5.1", - "natural-compare": "^1.4.0", - "pretty-format": "^24.5.0", - "semver": "^5.5.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-sonar-reporter": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/jest-sonar-reporter/-/jest-sonar-reporter-2.0.0.tgz", - "integrity": "sha512-ZervDCgEX5gdUbdtWsjdipLN3bKJwpxbvhkYNXTAYvAckCihobSLr9OT/IuyNIRT1EZMDDwR6DroWtrq+IL64w==", - "dev": true, - "requires": { - "xml": "^1.0.1" - } - }, - "jest-util": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-24.5.0.tgz", - "integrity": "sha512-Xy8JsD0jvBz85K7VsTIQDuY44s+hYJyppAhcsHsOsGisVtdhar6fajf2UOf2mEVEgh15ZSdA0zkCuheN8cbr1Q==", - "dev": true, - "requires": { - "@jest/console": "^24.3.0", - "@jest/fake-timers": "^24.5.0", - "@jest/source-map": "^24.3.0", - "@jest/test-result": "^24.5.0", - "@jest/types": "^24.5.0", - "@types/node": "*", - "callsites": "^3.0.0", - "chalk": "^2.0.1", - "graceful-fs": "^4.1.15", - "is-ci": "^2.0.0", - "mkdirp": "^0.5.1", - "slash": "^2.0.0", - "source-map": "^0.6.0" - }, - "dependencies": { - "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" - } - }, - "callsites": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.0.0.tgz", - "integrity": "sha512-tWnkwu9YEq2uzlBDI4RcLn8jrFvF9AOi8PxDNU3hZZjJcjkcRAq3vCI+vZcg1SuxISDYe86k9VZFwAxDiJGoAw==", - "dev": true - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "slash": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", - "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", - "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 - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-validate": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-24.5.0.tgz", - "integrity": "sha512-gg0dYszxjgK2o11unSIJhkOFZqNRQbWOAB2/LOUdsd2LfD9oXiMeuee8XsT0iRy5EvSccBgB4h/9HRbIo3MHgQ==", - "dev": true, - "requires": { - "@jest/types": "^24.5.0", - "camelcase": "^5.0.0", - "chalk": "^2.0.1", - "jest-get-type": "^24.3.0", - "leven": "^2.1.0", - "pretty-format": "^24.5.0" - }, - "dependencies": { - "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" - } - }, - "camelcase": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.2.0.tgz", - "integrity": "sha512-IXFsBS2pC+X0j0N/GE7Dm7j3bsEBp+oTpb7F50dwEVX7rf3IgwO9XatnegTsDtniKCUtEJH4fSU6Asw7uoVLfQ==", - "dev": true - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-watcher": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-24.5.0.tgz", - "integrity": "sha512-/hCpgR6bg0nKvD3nv4KasdTxuhwfViVMHUATJlnGCD0r1QrmIssimPbmc5KfAQblAVxkD8xrzuij9vfPUk1/rA==", - "dev": true, - "requires": { - "@jest/test-result": "^24.5.0", - "@jest/types": "^24.5.0", - "@types/node": "*", - "@types/yargs": "^12.0.9", - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.1", - "jest-util": "^24.5.0", - "string-length": "^2.0.0" - }, - "dependencies": { - "ansi-escapes": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", - "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==", - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-worker": { - "version": "24.4.0", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-24.4.0.tgz", - "integrity": "sha512-BH9X/klG9vxwoO99ZBUbZFfV8qO0XNZ5SIiCyYK2zOuJBl6YJVAeNIQjcoOVNu4HGEHeYEKsUWws8kSlSbZ9YQ==", - "dev": true, - "requires": { - "@types/node": "*", - "merge-stream": "^1.0.1", - "supports-color": "^6.1.0" - }, - "dependencies": { - "supports-color": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", - "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "jest-zone-patch": { - "version": "0.0.10", - "resolved": "https://registry.npmjs.org/jest-zone-patch/-/jest-zone-patch-0.0.10.tgz", - "integrity": "sha512-K5uHLHgMgi2Eyj74gbY+xSeGGekb5U48bXsgDwgipRbFdaekyZK+TAcp8auamqU4UjrAt5S4sIUZz/2bBNyTTA==", - "dev": true - }, - "jhipster-core": { - "version": "3.6.11", - "resolved": "https://registry.npmjs.org/jhipster-core/-/jhipster-core-3.6.11.tgz", - "integrity": "sha512-OibJay1+nwKk+mfRfuTrt2rW2h7BmGNfKWR7TQO4oYqG+I096EvJxZkIMCcjA9KuKLOZvnzfEi4UbtKyRTmHkg==", - "dev": true, - "requires": { - "chevrotain": "4.2.0", - "fs-extra": "7.0.1", - "lodash": "4.17.11", - "winston": "3.2.1" - }, - "dependencies": { - "fs-extra": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz", - "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "jsonfile": "^4.0.0", - "universalify": "^0.1.0" - } - }, - "jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.6" - } - } - } - }, - "joi": { - "version": "11.4.0", - "resolved": "https://registry.npmjs.org/joi/-/joi-11.4.0.tgz", - "integrity": "sha512-O7Uw+w/zEWgbL6OcHbyACKSj0PkQeUgmehdoXVSxt92QFCq4+1390Rwh5moI2K/OgC7D8RHRZqHZxT2husMJHA==", - "dev": true, - "requires": { - "hoek": "4.x.x", - "isemail": "3.x.x", - "topo": "2.x.x" - } - }, - "js-object-pretty-print": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/js-object-pretty-print/-/js-object-pretty-print-0.3.0.tgz", - "integrity": "sha1-RnDkUAZu4ezPNRdMfRl/WqOLz3Q=", - "dev": 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" - } - }, - "jsbn": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", - "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", - "dev": true - }, - "jsdom": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-11.12.0.tgz", - "integrity": "sha512-y8Px43oyiBM13Zc1z780FrfNLJCXTL40EWlty/LXUtcjykRBNgLlCjWXpfSPBl2iv+N7koQN+dvqszHZgT/Fjw==", - "dev": true, - "requires": { - "abab": "^2.0.0", - "acorn": "^5.5.3", - "acorn-globals": "^4.1.0", - "array-equal": "^1.0.0", - "cssom": ">= 0.3.2 < 0.4.0", - "cssstyle": "^1.0.0", - "data-urls": "^1.0.0", - "domexception": "^1.0.1", - "escodegen": "^1.9.1", - "html-encoding-sniffer": "^1.0.2", - "left-pad": "^1.3.0", - "nwsapi": "^2.0.7", - "parse5": "4.0.0", - "pn": "^1.1.0", - "request": "^2.87.0", - "request-promise-native": "^1.0.5", - "sax": "^1.2.4", - "symbol-tree": "^3.2.2", - "tough-cookie": "^2.3.4", - "w3c-hr-time": "^1.0.1", - "webidl-conversions": "^4.0.2", - "whatwg-encoding": "^1.0.3", - "whatwg-mimetype": "^2.1.0", - "whatwg-url": "^6.4.1", - "ws": "^5.2.0", - "xml-name-validator": "^3.0.0" - }, - "dependencies": { - "ws": { - "version": "5.2.2", - "resolved": "https://registry.npmjs.org/ws/-/ws-5.2.2.tgz", - "integrity": "sha512-jaHFD6PFv6UgoIVda6qZllptQsMlDEJkTQcybzzXDYM1XO9Y8em691FGMPmM46WGyLU4z9KMgQN+qrux/nhlHA==", - "dev": true, - "requires": { - "async-limiter": "~1.0.0" - } - } - } - }, - "jsesc": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", - "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", - "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.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "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, - "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": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", - "dev": true, - "requires": { - "minimist": "^1.2.0" - } - }, - "jsonfile": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-3.0.1.tgz", - "integrity": "sha1-pezG9l9T9mLEQVx2daAzHQmS7GY=", - "dev": true, - "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=", - "dev": true - }, - "jsonparse": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", - "integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA=", - "dev": 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" - } - }, - "jstransform": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/jstransform/-/jstransform-11.0.3.tgz", - "integrity": "sha1-CaeJk+CuTU70SH9hVakfYZDLQiM=", - "dev": true, - "requires": { - "base62": "^1.1.0", - "commoner": "^0.10.1", - "esprima-fb": "^15001.1.0-dev-harmony-fb", - "object-assign": "^2.0.0", - "source-map": "^0.4.2" - }, - "dependencies": { - "esprima-fb": { - "version": "15001.1.0-dev-harmony-fb", - "resolved": "https://registry.npmjs.org/esprima-fb/-/esprima-fb-15001.1.0-dev-harmony-fb.tgz", - "integrity": "sha1-MKlHMDxrjV6VW+4rmbHSMyBqaQE=", - "dev": true - }, - "object-assign": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-2.1.1.tgz", - "integrity": "sha1-Q8NuXVaf+OSBbE76i+AtJpZ8GKo=", - "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" - } - } - } - }, - "killable": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/killable/-/killable-1.0.1.tgz", - "integrity": "sha512-LzqtLKlUwirEUyl/nicirVmNiPvYs7l5n8wOPP7fyJVpUPkvCnW/vuiXGpylGUlnPDnB7311rARzAt3Mhswpjg==", - "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 - }, - "kleur": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.2.tgz", - "integrity": "sha512-3h7B2WRT5LNXOtQiAaWonilegHcPSf9nLVXlSTci8lu1dZUuui61+EsPEZqSVxY7rXYmB2DVKMQILxaO5WL61Q==", - "dev": true - }, - "kuler": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/kuler/-/kuler-1.0.1.tgz", - "integrity": "sha512-J9nVUucG1p/skKul6DU3PUZrhs0LPulNaeUOox0IyXDi8S4CztTHs1gQphhuZmzXG7VOQSf6NJfKuzteQLv9gQ==", - "dev": true, - "requires": { - "colornames": "^1.1.1" - } - }, - "last-call-webpack-plugin": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/last-call-webpack-plugin/-/last-call-webpack-plugin-3.0.0.tgz", - "integrity": "sha512-7KI2l2GIZa9p2spzPIVZBYyNKkN+e/SQPpnjlTiPhdbDW3F86tdKKELxKpzJ5sgU19wQWsACULZmpTPYHeWO5w==", - "dev": true, - "requires": { - "lodash": "^4.17.5", - "webpack-sources": "^1.1.0" - } - }, - "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" - } - }, - "left-pad": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz", - "integrity": "sha512-XI5MPzVNApjAyhQzphX8BkmKsKUxD4LdyK24iZeQGinBN9yTQT3bFlCBy/aVx2HrNcqQGsdot8ghrjyrvMCoEA==", - "dev": true - }, - "leven": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/leven/-/leven-2.1.0.tgz", - "integrity": "sha1-wuep93IJTe6dNCAq6KzORoeHVYA=", - "dev": true - }, - "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" - } - }, - "limiter": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/limiter/-/limiter-1.1.4.tgz", - "integrity": "sha512-XCpr5bElgDI65vVgstP8TWjv6/QKWm9GU5UG0Pr5sLQ3QLo8NVKsioe+Jed5/3vFOe3IQuqE7DKwTvKQkjTHvg==", - "dev": true - }, - "lint-staged": { - "version": "8.1.3", - "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-8.1.3.tgz", - "integrity": "sha512-6TGkikL1B+6mIOuSNq2TV6oP21IhPMnV8q0cf9oYZ296ArTVNcbFh1l1pfVOHHbBIYLlziWNsQ2q45/ffmJ4AA==", - "dev": true, - "requires": { - "@iamstarkov/listr-update-renderer": "0.4.1", - "chalk": "^2.3.1", - "commander": "^2.14.1", - "cosmiconfig": "^5.0.2", - "debug": "^3.1.0", - "dedent": "^0.7.0", - "del": "^3.0.0", - "execa": "^1.0.0", - "find-parent-dir": "^0.3.0", - "g-status": "^2.0.2", - "is-glob": "^4.0.0", - "is-windows": "^1.0.2", - "listr": "^0.14.2", - "lodash": "^4.17.5", - "log-symbols": "^2.2.0", - "micromatch": "^3.1.8", - "npm-which": "^3.0.1", - "p-map": "^1.1.1", - "path-is-inside": "^1.0.2", - "pify": "^3.0.0", - "please-upgrade-node": "^3.0.2", - "staged-git-files": "1.1.2", - "string-argv": "^0.0.2", - "stringify-object": "^3.2.2", - "yup": "^0.26.10" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "debug": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "execa": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", - "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", - "dev": true, - "requires": { - "cross-spawn": "^6.0.0", - "get-stream": "^4.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" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "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 - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "listr": { - "version": "0.14.3", - "resolved": "https://registry.npmjs.org/listr/-/listr-0.14.3.tgz", - "integrity": "sha512-RmAl7su35BFd/xoMamRjpIE4j3v+L28o8CT5YhAXQJm1fD+1l9ngXY8JAQRJ+tFK2i5njvi0iRUKV09vPwA0iA==", - "dev": true, - "requires": { - "@samverschueren/stream-to-observable": "^0.3.0", - "is-observable": "^1.1.0", - "is-promise": "^2.1.0", - "is-stream": "^1.1.0", - "listr-silent-renderer": "^1.1.1", - "listr-update-renderer": "^0.5.0", - "listr-verbose-renderer": "^0.5.0", - "p-map": "^2.0.0", - "rxjs": "^6.3.3" - }, - "dependencies": { - "p-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-2.0.0.tgz", - "integrity": "sha512-GO107XdrSUmtHxVoi60qc9tUl/KkNKm+X2CF4P9amalpGxv5YqVPJNfSb0wcA+syCopkZvYYIzW8OVTQW59x/w==", - "dev": true - } - } - }, - "listr-silent-renderer": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/listr-silent-renderer/-/listr-silent-renderer-1.1.1.tgz", - "integrity": "sha1-kktaN1cVN3C/Go4/v3S4u/P5JC4=", - "dev": true - }, - "listr-update-renderer": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/listr-update-renderer/-/listr-update-renderer-0.5.0.tgz", - "integrity": "sha512-tKRsZpKz8GSGqoI/+caPmfrypiaq+OQCbd+CovEC24uk1h952lVj5sC7SqyFUm+OaJ5HN/a1YLt5cit2FMNsFA==", - "dev": true, - "requires": { - "chalk": "^1.1.3", - "cli-truncate": "^0.2.1", - "elegant-spinner": "^1.0.1", - "figures": "^1.7.0", - "indent-string": "^3.0.0", - "log-symbols": "^1.0.2", - "log-update": "^2.3.0", - "strip-ansi": "^3.0.1" - }, - "dependencies": { - "figures": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-1.7.0.tgz", - "integrity": "sha1-y+Hjr/zxzUS4DK3+0o3Hk6lwHS4=", - "dev": true, - "requires": { - "escape-string-regexp": "^1.0.5", - "object-assign": "^4.1.0" - } - }, - "log-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-1.0.2.tgz", - "integrity": "sha1-N2/3tY6jCGoPCfrMdGF+ylAeGhg=", - "dev": true, - "requires": { - "chalk": "^1.0.0" - } - } - } - }, - "listr-verbose-renderer": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/listr-verbose-renderer/-/listr-verbose-renderer-0.5.0.tgz", - "integrity": "sha512-04PDPqSlsqIOaaaGZ+41vq5FejI9auqTInicFRndCBgE3bXG8D6W1I+mWhk+1nqbHmyhla/6BUrd5OSiHwKRXw==", - "dev": true, - "requires": { - "chalk": "^2.4.1", - "cli-cursor": "^2.1.0", - "date-fns": "^1.27.2", - "figures": "^2.0.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.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=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "parse-json": "^2.2.0", - "pify": "^2.0.0", - "strip-bom": "^3.0.0" - } - }, - "loader-runner": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-2.4.0.tgz", - "integrity": "sha512-Jsmr89RcXGIwivFY21FcRrisYZfvLMTWx5kOLc+JTxtpBOG6xML0vzbc6SEQG2FO9/4Fc3wW4LVcB5DmGflaRw==", - "dev": true - }, - "loader-utils": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.2.3.tgz", - "integrity": "sha512-fkpz8ejdnEMG3s37wGL07iSBDg99O9D5yflE9RGNH3hRdx9SOwYfnGYdZOUIZitN8E+E2vkq3MUMYMvPYl5ZZA==", - "dev": true, - "requires": { - "big.js": "^5.2.2", - "emojis-list": "^2.0.0", - "json5": "^1.0.1" - } - }, - "localtunnel": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/localtunnel/-/localtunnel-1.9.1.tgz", - "integrity": "sha512-HWrhOslklDvxgOGFLxi6fQVnvpl6XdX4sPscfqMZkzi3gtt9V7LKBWYvNUcpHSVvjwCQ6xzXacVvICNbNcyPnQ==", - "dev": true, - "requires": { - "axios": "0.17.1", - "debug": "2.6.9", - "openurl": "1.1.1", - "yargs": "6.6.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 - }, - "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" - } - }, - "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" - } - }, - "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" - } - }, - "os-locale": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz", - "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", - "dev": true, - "requires": { - "lcid": "^1.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" - } - }, - "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" - } - }, - "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" - } - }, - "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" - } - }, - "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" - } - }, - "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" - } - }, - "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 - }, - "y18n": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz", - "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=", - "dev": true - }, - "yargs": { - "version": "6.6.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-6.6.0.tgz", - "integrity": "sha1-eC7CHvQDNF+DCoCMo9UTr1YGUgg=", - "dev": 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": "^4.2.0" - } - }, - "yargs-parser": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-4.2.1.tgz", - "integrity": "sha1-KczqwNxPA8bIe0qfIX3RjJ90hxw=", - "dev": true, - "requires": { - "camelcase": "^3.0.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.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" - }, - "lodash._reinterpolate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", - "integrity": "sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=", - "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.difference": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz", - "integrity": "sha1-nMtOUF1Ia5FlE0V3KIWi3yf9AXw=", - "dev": true - }, - "lodash.get": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", - "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=", - "dev": true - }, - "lodash.isfinite": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/lodash.isfinite/-/lodash.isfinite-3.3.2.tgz", - "integrity": "sha1-+4m2WpqAKBgz8LdHizpRBPiY67M=", - "dev": true - }, - "lodash.memoize": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", - "integrity": "sha1-vMbEmkKihA7Zl/Mj6tpezRguC/4=", - "dev": true - }, - "lodash.pad": { - "version": "4.5.1", - "resolved": "https://registry.npmjs.org/lodash.pad/-/lodash.pad-4.5.1.tgz", - "integrity": "sha1-QzCUmoM6fI2iLMIPaibE1Z3runA=", - "dev": true - }, - "lodash.padend": { - "version": "4.6.1", - "resolved": "https://registry.npmjs.org/lodash.padend/-/lodash.padend-4.6.1.tgz", - "integrity": "sha1-U8y6BH0G4VjTEfRdpiX05J5vFm4=", - "dev": true - }, - "lodash.padstart": { - "version": "4.6.1", - "resolved": "https://registry.npmjs.org/lodash.padstart/-/lodash.padstart-4.6.1.tgz", - "integrity": "sha1-0uPuv/DZ05rVD1y9G1KnvOa7YRs=", - "dev": true - }, - "lodash.sortby": { - "version": "4.7.0", - "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", - "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=", - "dev": 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 - }, - "lodash.template": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-4.4.0.tgz", - "integrity": "sha1-5zoDhcg1VZF0bgILmWecaQ5o+6A=", - "dev": true, - "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=", - "dev": true, - "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=", - "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" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "log-update": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/log-update/-/log-update-2.3.0.tgz", - "integrity": "sha1-iDKP19HOeTiykoN0bwsbwSayRwg=", - "dev": true, - "requires": { - "ansi-escapes": "^3.0.0", - "cli-cursor": "^2.0.0", - "wrap-ansi": "^3.0.1" - }, - "dependencies": { - "ansi-escapes": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", - "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==", - "dev": true - }, - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", - "dev": true - }, - "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" - } - }, - "wrap-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-3.0.1.tgz", - "integrity": "sha1-KIoE2H7aXChuBg3+jxNc6NAH+Lo=", - "dev": true, - "requires": { - "string-width": "^2.1.1", - "strip-ansi": "^4.0.0" - } - } - } - }, - "logform": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/logform/-/logform-2.1.2.tgz", - "integrity": "sha512-+lZh4OpERDBLqjiwDLpAWNQu6KMjnlXH2ByZwCuSqVPJletw0kTWJf5CgSNAUKn1KUkv3m2cUz/LK8zyEy7wzQ==", - "dev": true, - "requires": { - "colors": "^1.2.1", - "fast-safe-stringify": "^2.0.4", - "fecha": "^2.3.3", - "ms": "^2.1.1", - "triple-beam": "^1.3.0" - }, - "dependencies": { - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - } - } - }, - "loglevel": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.6.1.tgz", - "integrity": "sha1-4PyVEztu8nbNyIh82vJKpvFW+Po=", - "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 - }, - "lowercase-keys": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", - "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==", - "dev": true - }, - "lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "requires": { - "yallist": "^3.0.2" - } - }, - "macos-release": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/macos-release/-/macos-release-1.1.0.tgz", - "integrity": "sha512-mmLbumEYMi5nXReB9js3WGsB8UE6cDBWyIO62Z4DNx6GbRhDxHNjA1MlzSpJ2S2KM1wyiPRA0d19uHWYYvMHjA==", - "dev": true - }, - "magic-string": { - "version": "0.25.2", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.2.tgz", - "integrity": "sha512-iLs9mPjh9IuTtRsqqhNGYcZXGei0Nh/A4xirrsqW7c+QhKVFL2vm7U09ru6cHRD22azaP/wMDgI+HCqbETMTtg==", - "dev": true, - "requires": { - "sourcemap-codec": "^1.4.4" - } - }, - "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" - }, - "dependencies": { - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - } - } - }, - "make-fetch-happen": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-4.0.1.tgz", - "integrity": "sha512-7R5ivfy9ilRJ1EMKIOziwrns9fGeAD4bAha8EB7BIiBBLHm2KeTUGCrICFt2rbHfzheTLynv50GnNTK1zDTrcQ==", - "dev": true, - "requires": { - "agentkeepalive": "^3.4.1", - "cacache": "^11.0.1", - "http-cache-semantics": "^3.8.1", - "http-proxy-agent": "^2.1.0", - "https-proxy-agent": "^2.2.1", - "lru-cache": "^4.1.2", - "mississippi": "^3.0.0", - "node-fetch-npm": "^2.0.2", - "promise-retry": "^1.1.1", - "socks-proxy-agent": "^4.0.0", - "ssri": "^6.0.0" - }, - "dependencies": { - "lru-cache": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", - "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", - "dev": true, - "requires": { - "pseudomap": "^1.0.2", - "yallist": "^2.1.2" - } - }, - "yallist": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", - "dev": true - } - } - }, - "makeerror": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.11.tgz", - "integrity": "sha1-4BpckQnyr3lmDk6LlYd5AYT1qWw=", - "dev": true, - "requires": { - "tmpl": "1.0.x" - } - }, - "map-age-cleaner": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz", - "integrity": "sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==", - "dev": true, - "requires": { - "p-defer": "^1.0.0" - } - }, - "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": "2.0.0", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-2.0.0.tgz", - "integrity": "sha1-plzSkIepJZi4eRJXpSPgISIqwfk=", - "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" - } - }, - "matcher": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/matcher/-/matcher-1.1.1.tgz", - "integrity": "sha512-+BmqxWIubKTRKNWx/ahnCkk3mG8m7OturVlqq6HiojGJTd5hVYbgZm6WzcYPCoB+KBT4Vd6R7WSRG2OADNaCjg==", - "dev": true, - "requires": { - "escape-string-regexp": "^1.0.4" - } - }, - "math-random": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/math-random/-/math-random-1.0.4.tgz", - "integrity": "sha512-rUxjysqif/BZQH2yhd5Aaq7vXMSx9NdEsQcyA07uEzIvxgI7zIr33gGsh+RU0/XjmQpCW7RsVof1vlkvQVCK5A==", - "dev": true - }, - "md5.js": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", - "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", - "dev": true, - "requires": { - "hash-base": "^3.0.0", - "inherits": "^2.0.1", - "safe-buffer": "^5.1.2" - } - }, - "mdn-data": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-1.1.4.tgz", - "integrity": "sha512-FSYbp3lyKjyj3E7fMl6rYvUdX0FBXaluGqlFoYESWQlyUTq8R+wp0rkFxoYFqZlHCvsUXGjyJmLQSnXToYhOSA==", - "dev": true - }, - "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" - } - }, - "mem-fs": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/mem-fs/-/mem-fs-1.1.3.tgz", - "integrity": "sha1-uK6NLj/Lb10/kWXBLUVRoGXZicw=", - "dev": true, - "requires": { - "through2": "^2.0.0", - "vinyl": "^1.1.0", - "vinyl-file": "^2.0.0" - } - }, - "mem-fs-editor": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/mem-fs-editor/-/mem-fs-editor-5.1.0.tgz", - "integrity": "sha512-2Yt2GCYEbcotYbIJagmow4gEtHDqzpq5XN94+yAx/NT5+bGqIjkXnm3KCUQfE6kRfScGp9IZknScoGRKu8L78w==", - "dev": true, - "requires": { - "commondir": "^1.0.1", - "deep-extend": "^0.6.0", - "ejs": "^2.5.9", - "glob": "^7.0.3", - "globby": "^8.0.1", - "isbinaryfile": "^3.0.2", - "mkdirp": "^0.5.0", - "multimatch": "^2.0.0", - "rimraf": "^2.2.8", - "through2": "^2.0.0", - "vinyl": "^2.0.1" - }, - "dependencies": { - "clone": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", - "integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18=", - "dev": true - }, - "clone-stats": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-1.0.0.tgz", - "integrity": "sha1-s3gt/4u1R04Yuba/D9/ngvh3doA=", - "dev": true - }, - "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" - } - }, - "globby": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/globby/-/globby-8.0.2.tgz", - "integrity": "sha512-yTzMmKygLp8RUpG1Ymu2VXPSJQZjNAZPD4ywgYEaG7e4tBJeUQBO8OpXrf1RCNcEs5alsoJYPAMiIHP0cmeC7w==", - "dev": true, - "requires": { - "array-union": "^1.0.1", - "dir-glob": "2.0.0", - "fast-glob": "^2.0.2", - "glob": "^7.1.2", - "ignore": "^3.3.5", - "pify": "^3.0.0", - "slash": "^1.0.0" - } - }, - "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" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - }, - "replace-ext": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-1.0.0.tgz", - "integrity": "sha1-3mMSg3P8v3w8z6TeWkgMRaZ5WOs=", - "dev": true - }, - "vinyl": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-2.2.0.tgz", - "integrity": "sha512-MBH+yP0kC/GQ5GwBqrTPTzEfiiLjta7hTtvQtbxBgTeSXsmKQRQecjibMbxIXzVT3Y9KJK+drOz1/k+vsu8Nkg==", - "dev": true, - "requires": { - "clone": "^2.1.1", - "clone-buffer": "^1.0.0", - "clone-stats": "^1.0.0", - "cloneable-readable": "^1.0.0", - "remove-trailing-separator": "^1.0.1", - "replace-ext": "^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": "5.0.0", - "resolved": "https://registry.npmjs.org/meow/-/meow-5.0.0.tgz", - "integrity": "sha512-CbTqYU17ABaLefO8vCU153ZZlprKYWDljcndKKDCFcYQITzWCXZAVk4QMFZPgvzrnUQ3uItnIE/LoUOwrT15Ig==", - "dev": true, - "requires": { - "camelcase-keys": "^4.0.0", - "decamelize-keys": "^1.0.0", - "loud-rejection": "^1.0.0", - "minimist-options": "^3.0.1", - "normalize-package-data": "^2.3.4", - "read-pkg-up": "^3.0.0", - "redent": "^2.0.0", - "trim-newlines": "^2.0.0", - "yargs-parser": "^10.0.0" - }, - "dependencies": { - "load-json-file": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", - "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "parse-json": "^4.0.0", - "pify": "^3.0.0", - "strip-bom": "^3.0.0" - } - }, - "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" - } - }, - "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" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - }, - "read-pkg": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", - "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", - "dev": true, - "requires": { - "load-json-file": "^4.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^3.0.0" - } - }, - "read-pkg-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-3.0.0.tgz", - "integrity": "sha1-PtSWaF26D4/hGNBpHcUfSh/5bwc=", - "dev": true, - "requires": { - "find-up": "^2.0.0", - "read-pkg": "^3.0.0" - } - }, - "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" - } - } - } - }, - "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 - }, - "merge-stream": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-1.0.1.tgz", - "integrity": "sha1-QEEgLVCKNCugAXQAjfDCUbjBNeE=", - "dev": true, - "requires": { - "readable-stream": "^2.0.1" - } - }, - "merge2": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.2.3.tgz", - "integrity": "sha512-gdUU1Fwj5ep4kplwcmftruWofEFt6lfpkkr3h860CXbAB9c3hGb55EOL2ali0Td5oebvW0E1+3Sr+Ur7XfKpRA==", - "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.4.1", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz", - "integrity": "sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ==", - "dev": true - }, - "mime-db": { - "version": "1.38.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.38.0.tgz", - "integrity": "sha512-bqVioMFFzc2awcdJZIzR3HjZFX20QhilVS7hytkKrv7xFAn8bM1gzc/FOX2awLISvWe0PV8ptFKcon+wZ5qYkg==", - "dev": true - }, - "mime-types": { - "version": "2.1.22", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.22.tgz", - "integrity": "sha512-aGl6TZGnhm/li6F7yx82bJiBZwgiEa4Hf6CNr8YO+r5UHr53tSTYZb102zyU50DOWWKeOv0uQLRL0/9EiKWCog==", - "dev": true, - "requires": { - "mime-db": "~1.38.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==" - }, - "mimic-response": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", - "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==", - "dev": true - }, - "mini-css-extract-plugin": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-0.5.0.tgz", - "integrity": "sha512-IuaLjruM0vMKhUUT51fQdQzBYTX49dLj8w68ALEAe2A4iYNpIC4eMac67mt3NzycvjOlf07/kYxJDc0RTl1Wqw==", - "dev": true, - "requires": { - "loader-utils": "^1.1.0", - "schema-utils": "^1.0.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": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" - }, - "minimist-options": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/minimist-options/-/minimist-options-3.0.2.tgz", - "integrity": "sha512-FyBrT/d0d4+uiZRbqznPXqw3IpZZG3gl3wKWiX784FycUKVwBt0uLBFkQrtE4tZOrgo78nZp2jnKz3L65T5LdQ==", - "dev": true, - "requires": { - "arrify": "^1.0.1", - "is-plain-obj": "^1.1.0" - } - }, - "minipass": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-2.3.5.tgz", - "integrity": "sha512-Gi1W4k059gyRbyVUZQ4mEqLm0YIUiGYfvxhF6SIlk3ui1WVxMTGfGdQ2SInh3PDrRTVvPKgULkpJtT4RH10+VA==", - "dev": true, - "requires": { - "safe-buffer": "^5.1.2", - "yallist": "^3.0.0" - } - }, - "minizlib": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-1.2.1.tgz", - "integrity": "sha512-7+4oTUOWKg7AuL3vloEWekXY2/D20cevzsrNT2kGWm+39J9hGTCBv8VI5Pm5lXZ/o3/mdR4f8rflAPhnQb8mPA==", - "dev": true, - "requires": { - "minipass": "^2.2.1" - } - }, - "mississippi": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mississippi/-/mississippi-3.0.0.tgz", - "integrity": "sha512-x471SsVjUtBRtcvd4BzKE9kFC+/2TeWgKCgw0bZcw1b9l2X3QX5vCWgF+KaZaYm87Ss//rHnWryupDrgLvmSkA==", - "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": "^3.0.0", - "pumpify": "^1.3.3", - "stream-each": "^1.1.0", - "through2": "^2.0.0" - } - }, - "mitt": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/mitt/-/mitt-1.1.3.tgz", - "integrity": "sha512-mUDCnVNsAi+eD6qA0HkRkwYczbLHJ49z17BGe2PYRhZL4wpZUFZGJHU7/5tmvohoma+Hdn0Vh/oJTiPEmgSruA==", - "dev": true - }, - "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" - }, - "dependencies": { - "minimist": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", - "dev": true - } - } - }, - "moment": { - "version": "2.24.0", - "resolved": "https://registry.npmjs.org/moment/-/moment-2.24.0.tgz", - "integrity": "sha512-bV7f+6l2QigeBBZSM/6yTNq4P2fNpSWj/0e7jQcy87A8e7o2nAfP/34/2ky5Vw4B9S446EtIhodAzkFCcR4dQg==" - }, - "moment-locales-webpack-plugin": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/moment-locales-webpack-plugin/-/moment-locales-webpack-plugin-1.0.7.tgz", - "integrity": "sha512-KjYpaAhmuzGFZl6534FlZoK7QtW3vqlxd+A17W9DlgHJ5yhXANy7AZJl7iYtZpWjAfMTAWiVrQ7YDZdkFO6uRw==", - "dev": true, - "requires": { - "lodash.difference": "^4.5.0" - } - }, - "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 - }, - "multimatch": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/multimatch/-/multimatch-2.1.0.tgz", - "integrity": "sha1-nHkGoi+0wCkZ4vX3UWG0zb1LKis=", - "dev": true, - "requires": { - "array-differ": "^1.0.0", - "array-union": "^1.0.1", - "arrify": "^1.0.0", - "minimatch": "^3.0.0" - } - }, - "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.13.1", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.13.1.tgz", - "integrity": "sha512-I6YB/YEuDeUZMmhscXKxGgZlFnhsn5y0hgOZBadkzfTRrZBtJDZeg6eQf7PYMIEclwmorTKK8GztsyOUSVBREA==", - "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" - } - }, - "natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", - "dev": true - }, - "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.6.0", - "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.0.tgz", - "integrity": "sha512-MFh0d/Wa7vkKO3Y3LlacqAEeHK0mckVqzDieUKTT+KGxi+zIpeVsFxymkIiRpbpDziHc290Xr9A1O4Om7otoRA==", - "dev": true - }, - "ng-jhipster": { - "version": "0.9.1", - "resolved": "https://registry.npmjs.org/ng-jhipster/-/ng-jhipster-0.9.1.tgz", - "integrity": "sha512-/ViJ6bNtc/4w6valKNvHKyvXF1cn1OBnSEh3Q8aEUHtmoyr9owReTGHT7ylNclthUsxztRMUS4GrMMEQ5kM09Q==", - "requires": { - "tslib": "^1.9.0" - } - }, - "ngx-cookie": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/ngx-cookie/-/ngx-cookie-2.0.1.tgz", - "integrity": "sha512-3+agXZkoPxRP3IyELf7Eiuhk6TX+EAX974kkCR6Xjm+N7boEA+Fin2Q90AAE4XZzY48skkVzLH96TOikb5yU3g==" - }, - "ngx-infinite-scroll": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/ngx-infinite-scroll/-/ngx-infinite-scroll-7.0.1.tgz", - "integrity": "sha512-be9DAAuabV7VGI06/JUnS6pXC6mcBOzA4+SBCwOcP9WwJ2r5GjdZyOa34ls9hi1MnCOj3zrXLvPKQ/UDp6csIw==", - "requires": { - "opencollective": "^1.0.3" - } - }, - "ngx-webstorage": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/ngx-webstorage/-/ngx-webstorage-2.0.1.tgz", - "integrity": "sha512-AhBkl1v5sBLYiGC1DuHxM90B8OewqyhYhm+KGtJIFxMh5dj3tlNgPokmWCtKcUZF26m8MgxDDuP5e6NeDCpYQw==" - }, - "nice-try": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", - "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", - "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-fetch": { - "version": "1.6.3", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-1.6.3.tgz", - "integrity": "sha1-3CNO3WSJmC1Y6PDbT2lQKavNjAQ=", - "requires": { - "encoding": "^0.1.11", - "is-stream": "^1.0.1" - } - }, - "node-fetch-npm": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/node-fetch-npm/-/node-fetch-npm-2.0.2.tgz", - "integrity": "sha512-nJIxm1QmAj4v3nfCvEeCrYSoVwXyxLnaPBK5W1W5DGEJwjlKuC2VEUycGw5oxk+4zZahRrB84PUJJgEmhFTDFw==", - "dev": true, - "requires": { - "encoding": "^0.1.11", - "json-parse-better-errors": "^1.0.0", - "safe-buffer": "^5.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-int64": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", - "integrity": "sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs=", - "dev": true - }, - "node-libs-browser": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/node-libs-browser/-/node-libs-browser-2.2.0.tgz", - "integrity": "sha512-5MQunG/oyOaBdttrL40dA7bUfPORLRWMUJLQtMg7nluxUvk5XwnLdL9twQHFAjRx/y7mIMkLKT9++qPbbk6BZA==", - "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": "^3.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.11.0", - "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-modules-regexp": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz", - "integrity": "sha1-jZ2+KJZKSsVxLpExZCEHxx6Q7EA=", - "dev": true - }, - "node-notifier": { - "version": "5.4.0", - "resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-5.4.0.tgz", - "integrity": "sha512-SUDEb+o71XR5lXSTyivXd9J7fCloE3SyP4lSgt3lU2oSANiox+SxlNRGPjDKrwU1YN3ix2KN/VGGCg0t01rttQ==", - "dev": true, - "requires": { - "growly": "^1.3.0", - "is-wsl": "^1.1.0", - "semver": "^5.5.0", - "shellwords": "^0.1.1", - "which": "^1.3.0" - } - }, - "node-releases": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.11.tgz", - "integrity": "sha512-8v1j5KfP+s5WOTa1spNUAOfreajQPN12JXbRR0oDE+YrJBQCXBnNqUDj27EKpPLOoSiU3tKi3xGPB+JaOdUEQQ==", - "dev": true, - "requires": { - "semver": "^5.3.0" - } - }, - "normalize-package-data": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", - "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", - "dev": true, - "requires": { - "hosted-git-info": "^2.1.4", - "resolve": "^1.10.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 - }, - "normalize-url": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-3.3.0.tgz", - "integrity": "sha512-U+JJi7duF1o+u2pynbp2zXDW2/PADgC30f0GsHZtRh+HOcXHnw137TrNlyxxRvWW5fjKd3bcLHPxofWuCjaeZg==", - "dev": true - }, - "npm-bundled": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-1.0.6.tgz", - "integrity": "sha512-8/JCaftHwbd//k6y2rEWp6k1wxVfpFzB6t1p825+cUb7Ym2XQfhwIC5KwhrvzZRJu+LtDE585zVaS32+CGtf0g==", - "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-packlist": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-1.4.1.tgz", - "integrity": "sha512-+TcdO7HJJ8peiiYhvPxsEDhF3PJFGUGRcFsGve3vxvxdcpO2Z4Z7rkosRM0kWj6LfbK/P0gu3dzk5RU1ffvFcw==", - "dev": true, - "requires": { - "ignore-walk": "^3.0.1", - "npm-bundled": "^1.0.1" - } - }, - "npm-path": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/npm-path/-/npm-path-2.0.4.tgz", - "integrity": "sha512-IFsj0R9C7ZdR5cP+ET342q77uSRdtWOlWpih5eC+lu29tIDbNEgDbzgVJ5UFvYHWhxDZ5TFkJafFioO0pPQjCw==", - "dev": true, - "requires": { - "which": "^1.2.10" - } - }, - "npm-pick-manifest": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/npm-pick-manifest/-/npm-pick-manifest-2.2.3.tgz", - "integrity": "sha512-+IluBC5K201+gRU85vFlUwX3PFShZAbAgDNp2ewJdWMVSppdo/Zih0ul2Ecky/X7b51J7LrrUAP+XOmOCvYZqA==", - "dev": true, - "requires": { - "figgy-pudding": "^3.5.1", - "npm-package-arg": "^6.0.0", - "semver": "^5.4.1" - } - }, - "npm-registry-fetch": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/npm-registry-fetch/-/npm-registry-fetch-3.9.0.tgz", - "integrity": "sha512-srwmt8YhNajAoSAaDWndmZgx89lJwIZ1GWxOuckH4Coek4uHv5S+o/l9FLQe/awA+JwTnj4FJHldxhlXdZEBmw==", - "dev": true, - "requires": { - "JSONStream": "^1.3.4", - "bluebird": "^3.5.1", - "figgy-pudding": "^3.4.1", - "lru-cache": "^4.1.3", - "make-fetch-happen": "^4.0.1", - "npm-package-arg": "^6.1.0" - }, - "dependencies": { - "lru-cache": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", - "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", - "dev": true, - "requires": { - "pseudomap": "^1.0.2", - "yallist": "^2.1.2" - } - }, - "yallist": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", - "dev": true - } - } - }, - "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" - } - }, - "npm-which": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/npm-which/-/npm-which-3.0.1.tgz", - "integrity": "sha1-kiXybsOihcIJyuZ8OxGmtKtxQKo=", - "dev": true, - "requires": { - "commander": "^2.9.0", - "npm-path": "^2.0.2", - "which": "^1.2.10" - } - }, - "npmlog": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-2.0.4.tgz", - "integrity": "sha1-mLUlMPJRTKkNCexbIsiEZyI3VpI=", - "dev": true, - "requires": { - "ansi": "~0.3.1", - "are-we-there-yet": "~1.1.2", - "gauge": "~1.2.5" - } - }, - "nth-check": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-1.0.2.tgz", - "integrity": "sha512-WeBOdju8SnzPN5vTUJYxYUxLeXpCaVP5i5e0LF8fg7WORF2Wd7wFX/pk0tYZk7s8T+J7VLy0Da6J1+wCT0AtHg==", - "dev": true, - "requires": { - "boolbase": "~1.0.0" - } - }, - "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 - }, - "nwsapi": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.1.1.tgz", - "integrity": "sha512-T5GaA1J/d34AC8mkrFD2O0DR17kwJ702ZOtJOsS8RpbsQZVOC2/xYFb1i/cw+xdM54JIlMuojjDOYct8GIWtwg==", - "dev": true - }, - "oauth-sign": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", - "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", - "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=" - }, - "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.1.0", - "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.0.tgz", - "integrity": "sha512-6OO5X1+2tYkNyNEx6TsCxEqFfRWaqx6EtMiSbGrw8Ob8v9Ne+Hl8rBAgLBZn5wjEz3s/s6U1WXFUFOcxxAwUpg==", - "dev": true - }, - "object-path": { - "version": "0.9.2", - "resolved": "https://registry.npmjs.org/object-path/-/object-path-0.9.2.tgz", - "integrity": "sha1-D9mnT8X60a45aLWGvaXGMr1sBaU=", - "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.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" - } - }, - "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" - } - }, - "object.values": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.0.tgz", - "integrity": "sha512-8mf0nKLAoFX6VlNVdhGj31SVYpaNFtUnuoOXWyFEstsWRgU837AK+JYM0iAxwkSzGRbwn8cbFmgbyxj1j4VbXg==", - "dev": true, - "requires": { - "define-properties": "^1.1.3", - "es-abstract": "^1.12.0", - "function-bind": "^1.1.1", - "has": "^1.0.3" - } - }, - "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.2", - "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", - "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", - "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" - } - }, - "one-time": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/one-time/-/one-time-0.0.4.tgz", - "integrity": "sha1-+M33eISCb+Tf+T46nMN7HkSAdC4=", - "dev": true - }, - "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" - } - }, - "opencollective": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/opencollective/-/opencollective-1.0.3.tgz", - "integrity": "sha1-ruY3K8KBRFg2kMPKja7PwSDdDvE=", - "requires": { - "babel-polyfill": "6.23.0", - "chalk": "1.1.3", - "inquirer": "3.0.6", - "minimist": "1.2.0", - "node-fetch": "1.6.3", - "opn": "4.0.2" - } - }, - "openurl": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/openurl/-/openurl-1.1.1.tgz", - "integrity": "sha1-OHW0sO96UsFW8NtB1GCduw+Us4c=", - "dev": true - }, - "opn": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/opn/-/opn-4.0.2.tgz", - "integrity": "sha1-erwi5kTf9jsKltWrfyeQwPAavJU=", - "requires": { - "object-assign": "^4.0.1", - "pinkie-promise": "^2.0.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": { - "minimist": { - "version": "0.0.10", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz", - "integrity": "sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=", - "dev": true - } - } - }, - "optimize-css-assets-webpack-plugin": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/optimize-css-assets-webpack-plugin/-/optimize-css-assets-webpack-plugin-5.0.1.tgz", - "integrity": "sha512-Rqm6sSjWtx9FchdP0uzTQDc7GXDKnwVEGoSxjezPkzMewx7gEWE9IMUYKmigTRC4U3RaNSwYVnUDLuIdtTpm0A==", - "dev": true, - "requires": { - "cssnano": "^4.1.0", - "last-call-webpack-plugin": "^3.0.0" - } - }, - "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" - }, - "dependencies": { - "wordwrap": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", - "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", - "dev": true - } - } - }, - "original": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/original/-/original-1.0.2.tgz", - "integrity": "sha512-hyBVl6iqqUOJ8FqRe+l/gS8H+kKYjrEndd5Pm1MfBtsEKA038HkkdbAl/72EAXGyonD/PFsvmVG+EvcIpliMBg==", - "dev": true, - "requires": { - "url-parse": "^1.4.3" - } - }, - "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": "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" - } - }, - "os-name": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/os-name/-/os-name-2.0.1.tgz", - "integrity": "sha1-uaOGNhwXrjohc27wWZQFyajF3F4=", - "dev": true, - "requires": { - "macos-release": "^1.0.0", - "win-release": "^1.0.0" - } - }, - "os-shim": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/os-shim/-/os-shim-0.1.3.tgz", - "integrity": "sha1-a2LDeRz3kJ6jXtRuF2WLtBfLORc=", - "dev": true - }, - "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=" - }, - "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-cancelable": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-0.3.0.tgz", - "integrity": "sha512-RVbZPLso8+jFeq1MfNvgXtCRED2raz/dKpacfTNxsx6pLEpEomM7gah6VeHSYV3+vo0OAi4MkArtQcWWXuQoyw==", - "dev": true - }, - "p-defer": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", - "integrity": "sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=", - "dev": true - }, - "p-each-series": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-each-series/-/p-each-series-1.0.0.tgz", - "integrity": "sha1-kw89Et0fUOdDRFeiLNbwSsatf3E=", - "dev": true, - "requires": { - "p-reduce": "^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-is-promise": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-2.0.0.tgz", - "integrity": "sha512-pzQPhYMCAgLAKPWD2jC3Se9fEfrD9npNos0y150EeqZll7akhEgGhTW/slB6lHku8AvYGiJ+YJ5hfHKePPgFWg==", - "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-reduce": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-reduce/-/p-reduce-1.0.0.tgz", - "integrity": "sha1-GMKw3ZNqRpClKfgjH1ig/bakffo=", - "dev": true - }, - "p-timeout": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-1.2.1.tgz", - "integrity": "sha1-XrOzU7f86Z8QGhA4iAuwVOu+o4Y=", - "dev": true, - "requires": { - "p-finally": "^1.0.0" - } - }, - "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 - }, - "pacote": { - "version": "9.4.0", - "resolved": "https://registry.npmjs.org/pacote/-/pacote-9.4.0.tgz", - "integrity": "sha512-WQ1KL/phGMkedYEQx9ODsjj7xvwLSpdFJJdEXrLyw5SILMxcTNt5DTxT2Z93fXuLFYJBlZJdnwdalrQdB/rX5w==", - "dev": true, - "requires": { - "bluebird": "^3.5.3", - "cacache": "^11.3.2", - "figgy-pudding": "^3.5.1", - "get-stream": "^4.1.0", - "glob": "^7.1.3", - "lru-cache": "^5.1.1", - "make-fetch-happen": "^4.0.1", - "minimatch": "^3.0.4", - "minipass": "^2.3.5", - "mississippi": "^3.0.0", - "mkdirp": "^0.5.1", - "normalize-package-data": "^2.4.0", - "npm-package-arg": "^6.1.0", - "npm-packlist": "^1.1.12", - "npm-pick-manifest": "^2.2.3", - "npm-registry-fetch": "^3.8.0", - "osenv": "^0.1.5", - "promise-inflight": "^1.0.1", - "promise-retry": "^1.1.1", - "protoduck": "^5.0.1", - "rimraf": "^2.6.2", - "safe-buffer": "^5.1.2", - "semver": "^5.6.0", - "ssri": "^6.0.1", - "tar": "^4.4.8", - "unique-filename": "^1.1.1", - "which": "^1.3.1" - } - }, - "pako": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.10.tgz", - "integrity": "sha512-0DTvPVU3ed8+HNXOu5Bs+o//Mbdj9VNQMUOe9oKCwh8l0GNwpTDMKCWbRjgtD291AWnkAgkqA/LOnQS8AmS1tw==", - "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.4", - "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.4.tgz", - "integrity": "sha512-Qs5duJcuvNExRfFZ99HDD3z4mAi3r9Wl/FOjEOijlxwCZs7E7mW2vjTpgQ4J8LpTF8x5v+1Vn5UQFejmWT11aw==", - "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", - "safe-buffer": "^5.1.1" - } - }, - "parse-gitignore": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parse-gitignore/-/parse-gitignore-1.0.1.tgz", - "integrity": "sha512-UGyowyjtx26n65kdAMWhm6/3uy5uSrpcuH7tt+QEVudiBoVS+eqHxD5kbi9oWVRwj7sCzXqwuM+rUGw7earl6A==", - "dev": true - }, - "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" - } - }, - "parse-passwd": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", - "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=", - "dev": true - }, - "parse5": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", - "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", - "dev": true - }, - "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.6", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", - "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", - "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": "2.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-2.0.0.tgz", - "integrity": "sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM=", - "dev": true, - "requires": { - "pify": "^2.0.0" - } - }, - "pbkdf2": { - "version": "3.0.17", - "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.17.tgz", - "integrity": "sha512-U/il5MsrZp7mGg3mSQfn742na2T+1/vHDCG5/iTI3X9MKUuYUZVLQhyRsg06mCgDBTd57TxzgZt7P+fYfjRLtA==", - "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": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", - "dev": true - }, - "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" - } - }, - "pirates": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.1.tgz", - "integrity": "sha512-WuNqLTbMI3tmfef2TKxlQmAiLHKtFhlsCZnPIpuv2Ow0RDVO8lfy1Opf4NUzlMXLjPl+Men7AuVdX6TA+s+uGA==", - "dev": true, - "requires": { - "node-modules-regexp": "^1.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" - } - }, - "pkg-up": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-2.0.0.tgz", - "integrity": "sha1-yBmscoBZpGHKscOImivjxJoATX8=", - "dev": true, - "requires": { - "find-up": "^2.1.0" - } - }, - "please-upgrade-node": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.1.1.tgz", - "integrity": "sha512-KY1uHnQ2NlQHqIJQpnh/i54rKkuxCEBx+voJIS/Mvb+L2iYd2NMotwduhKTMjfC1uKoX3VXOxLjIYG66dfJTVQ==", - "dev": true, - "requires": { - "semver-compare": "^1.0.0" - } - }, - "plugin-error": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/plugin-error/-/plugin-error-0.1.2.tgz", - "integrity": "sha1-O5uzM1zPAPQl4HQ34ZJ2ln2kes4=", - "dev": true, - "requires": { - "ansi-cyan": "^0.1.1", - "ansi-red": "^0.1.1", - "arr-diff": "^1.0.1", - "arr-union": "^2.0.1", - "extend-shallow": "^1.1.2" - }, - "dependencies": { - "arr-diff": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-1.1.0.tgz", - "integrity": "sha1-aHwydYFjWI/vfeezb6vklesaOZo=", - "dev": true, - "requires": { - "arr-flatten": "^1.0.1", - "array-slice": "^0.2.3" - } - }, - "arr-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-2.1.0.tgz", - "integrity": "sha1-IPnqtexw9cfSFbEHexw5Fh0pLH0=", - "dev": true - }, - "extend-shallow": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-1.1.4.tgz", - "integrity": "sha1-Gda/lN/AnXa6cR85uHLSH/TdkHE=", - "dev": true, - "requires": { - "kind-of": "^1.1.0" - } - }, - "kind-of": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-1.1.0.tgz", - "integrity": "sha1-FAo9LUGjbS78+pN3tiwk+ElaXEQ=", - "dev": true - } - } - }, - "pluralize": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-7.0.0.tgz", - "integrity": "sha512-ARhBOdzS3e41FbkW/XWrTEtukqqLoK5+Z/4UeDaLuSW+39JPeFgs4gCGqsrJHVZX0fUrx//4OF0K1CUGwlIFow==", - "dev": true - }, - "pn": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/pn/-/pn-1.1.0.tgz", - "integrity": "sha512-2qHaIQr2VLRFoxe2nASzsV6ef4yOOH+Fi9FBOVH6cqeSgUnoyySPZkxzLuzd+RYOQTRpROA0ztTMqxROKSb/nA==", - "dev": true - }, - "portfinder": { - "version": "1.0.20", - "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.20.tgz", - "integrity": "sha512-Yxe4mTyDzTd59PZJY4ojZR8F+E5e97iq2ZOHPz3HDgSvYC5siNad2tLooQ5y5QHyQhc3xVqvyk/eNA3wuoa7Sw==", - "dev": true, - "requires": { - "async": "^1.5.2", - "debug": "^2.2.0", - "mkdirp": "0.5.x" - } - }, - "portscanner": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/portscanner/-/portscanner-2.1.1.tgz", - "integrity": "sha1-6rtAnk3iSVD1oqUW01rnaTQ/u5Y=", - "dev": true, - "requires": { - "async": "1.5.2", - "is-number-like": "^1.0.3" - } - }, - "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": "7.0.14", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-7.0.14.tgz", - "integrity": "sha512-NsbD6XUUMZvBxtQAJuWDJeeC4QFsmWsfozWxCJPWf3M55K9iu2iMDaKqyoOdTJ1R4usBXuxlVFAIo8rZPQD4Bg==", - "dev": true, - "requires": { - "chalk": "^2.4.2", - "source-map": "^0.6.1", - "supports-color": "^6.1.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "dependencies": { - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.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 - }, - "supports-color": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", - "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "postcss-calc": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/postcss-calc/-/postcss-calc-7.0.1.tgz", - "integrity": "sha512-oXqx0m6tb4N3JGdmeMSc/i91KppbYsFZKdH0xMOqK8V1rJlzrKlTdokz8ozUXLVejydRN6u2IddxpcijRj2FqQ==", - "dev": true, - "requires": { - "css-unit-converter": "^1.1.1", - "postcss": "^7.0.5", - "postcss-selector-parser": "^5.0.0-rc.4", - "postcss-value-parser": "^3.3.1" - }, - "dependencies": { - "cssesc": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-2.0.0.tgz", - "integrity": "sha512-MsCAG1z9lPdoO/IUMLSBWBSVxVtJ1395VGIQ+Fc2gNdkQ1hNDnQdw3YhA71WJCBW1vdwA0cAnk/DnW6bqoEUYg==", - "dev": true - }, - "postcss-selector-parser": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-5.0.0.tgz", - "integrity": "sha512-w+zLE5Jhg6Liz8+rQOWEAwtwkyqpfnmsinXjXg6cY7YIONZZtgvE0v2O0uhQBs0peNomOJwWRKt6JBfTdTd3OQ==", - "dev": true, - "requires": { - "cssesc": "^2.0.0", - "indexes-of": "^1.0.1", - "uniq": "^1.0.1" - } - } - } - }, - "postcss-colormin": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/postcss-colormin/-/postcss-colormin-4.0.3.tgz", - "integrity": "sha512-WyQFAdDZpExQh32j0U0feWisZ0dmOtPl44qYmJKkq9xFWY3p+4qnRzCHeNrkeRhwPHz9bQ3mo0/yVkaply0MNw==", - "dev": true, - "requires": { - "browserslist": "^4.0.0", - "color": "^3.0.0", - "has": "^1.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-convert-values": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/postcss-convert-values/-/postcss-convert-values-4.0.1.tgz", - "integrity": "sha512-Kisdo1y77KUC0Jmn0OXU/COOJbzM8cImvw1ZFsBgBgMgb1iL23Zs/LXRe3r+EZqM3vGYKdQ2YJVQ5VkJI+zEJQ==", - "dev": true, - "requires": { - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-discard-comments": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-discard-comments/-/postcss-discard-comments-4.0.2.tgz", - "integrity": "sha512-RJutN259iuRf3IW7GZyLM5Sw4GLTOH8FmsXBnv8Ab/Tc2k4SR4qbV4DNbyyY4+Sjo362SyDmW2DQ7lBSChrpkg==", - "dev": true, - "requires": { - "postcss": "^7.0.0" - } - }, - "postcss-discard-duplicates": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-discard-duplicates/-/postcss-discard-duplicates-4.0.2.tgz", - "integrity": "sha512-ZNQfR1gPNAiXZhgENFfEglF93pciw0WxMkJeVmw8eF+JZBbMD7jp6C67GqJAXVZP2BWbOztKfbsdmMp/k8c6oQ==", - "dev": true, - "requires": { - "postcss": "^7.0.0" - } - }, - "postcss-discard-empty": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/postcss-discard-empty/-/postcss-discard-empty-4.0.1.tgz", - "integrity": "sha512-B9miTzbznhDjTfjvipfHoqbWKwd0Mj+/fL5s1QOz06wufguil+Xheo4XpOnc4NqKYBCNqqEzgPv2aPBIJLox0w==", - "dev": true, - "requires": { - "postcss": "^7.0.0" - } - }, - "postcss-discard-overridden": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/postcss-discard-overridden/-/postcss-discard-overridden-4.0.1.tgz", - "integrity": "sha512-IYY2bEDD7g1XM1IDEsUT4//iEYCxAmP5oDSFMVU/JVvT7gh+l4fmjciLqGgwjdWpQIdb0Che2VX00QObS5+cTg==", - "dev": true, - "requires": { - "postcss": "^7.0.0" - } - }, - "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" - }, - "dependencies": { - "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" - } - }, - "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" - } - } - } - }, - "postcss-loader": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/postcss-loader/-/postcss-loader-3.0.0.tgz", - "integrity": "sha512-cLWoDEY5OwHcAjDnkyRQzAXfs2jrKjXpO/HQFcc5b5u/r7aa471wdmChmwfnv7x2u840iat/wi0lQ5nbRgSkUA==", - "dev": true, - "requires": { - "loader-utils": "^1.1.0", - "postcss": "^7.0.0", - "postcss-load-config": "^2.0.0", - "schema-utils": "^1.0.0" - } - }, - "postcss-merge-longhand": { - "version": "4.0.11", - "resolved": "https://registry.npmjs.org/postcss-merge-longhand/-/postcss-merge-longhand-4.0.11.tgz", - "integrity": "sha512-alx/zmoeXvJjp7L4mxEMjh8lxVlDFX1gqWHzaaQewwMZiVhLo42TEClKaeHbRf6J7j82ZOdTJ808RtN0ZOZwvw==", - "dev": true, - "requires": { - "css-color-names": "0.0.4", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0", - "stylehacks": "^4.0.0" - } - }, - "postcss-merge-rules": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/postcss-merge-rules/-/postcss-merge-rules-4.0.3.tgz", - "integrity": "sha512-U7e3r1SbvYzO0Jr3UT/zKBVgYYyhAz0aitvGIYOYK5CPmkNih+WDSsS5tvPrJ8YMQYlEMvsZIiqmn7HdFUaeEQ==", - "dev": true, - "requires": { - "browserslist": "^4.0.0", - "caniuse-api": "^3.0.0", - "cssnano-util-same-parent": "^4.0.0", - "postcss": "^7.0.0", - "postcss-selector-parser": "^3.0.0", - "vendors": "^1.0.0" - }, - "dependencies": { - "postcss-selector-parser": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-3.1.1.tgz", - "integrity": "sha1-T4dfSvsMllc9XPTXQBGu4lCn6GU=", - "dev": true, - "requires": { - "dot-prop": "^4.1.1", - "indexes-of": "^1.0.1", - "uniq": "^1.0.1" - } - } - } - }, - "postcss-minify-font-values": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-minify-font-values/-/postcss-minify-font-values-4.0.2.tgz", - "integrity": "sha512-j85oO6OnRU9zPf04+PZv1LYIYOprWm6IA6zkXkrJXyRveDEuQggG6tvoy8ir8ZwjLxLuGfNkCZEQG7zan+Hbtg==", - "dev": true, - "requires": { - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-minify-gradients": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-minify-gradients/-/postcss-minify-gradients-4.0.2.tgz", - "integrity": "sha512-qKPfwlONdcf/AndP1U8SJ/uzIJtowHlMaSioKzebAXSG4iJthlWC9iSWznQcX4f66gIWX44RSA841HTHj3wK+Q==", - "dev": true, - "requires": { - "cssnano-util-get-arguments": "^4.0.0", - "is-color-stop": "^1.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-minify-params": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-minify-params/-/postcss-minify-params-4.0.2.tgz", - "integrity": "sha512-G7eWyzEx0xL4/wiBBJxJOz48zAKV2WG3iZOqVhPet/9geefm/Px5uo1fzlHu+DOjT+m0Mmiz3jkQzVHe6wxAWg==", - "dev": true, - "requires": { - "alphanum-sort": "^1.0.0", - "browserslist": "^4.0.0", - "cssnano-util-get-arguments": "^4.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0", - "uniqs": "^2.0.0" - } - }, - "postcss-minify-selectors": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-minify-selectors/-/postcss-minify-selectors-4.0.2.tgz", - "integrity": "sha512-D5S1iViljXBj9kflQo4YutWnJmwm8VvIsU1GeXJGiG9j8CIg9zs4voPMdQDUmIxetUOh60VilsNzCiAFTOqu3g==", - "dev": true, - "requires": { - "alphanum-sort": "^1.0.0", - "has": "^1.0.0", - "postcss": "^7.0.0", - "postcss-selector-parser": "^3.0.0" - }, - "dependencies": { - "postcss-selector-parser": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-3.1.1.tgz", - "integrity": "sha1-T4dfSvsMllc9XPTXQBGu4lCn6GU=", - "dev": true, - "requires": { - "dot-prop": "^4.1.1", - "indexes-of": "^1.0.1", - "uniq": "^1.0.1" - } - } - } - }, - "postcss-modules-extract-imports": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-2.0.0.tgz", - "integrity": "sha512-LaYLDNS4SG8Q5WAWqIJgdHPJrDDr/Lv775rMBFUbgjTz6j34lUznACHcdRWroPvXANP2Vj7yNK57vp9eFqzLWQ==", - "dev": true, - "requires": { - "postcss": "^7.0.5" - } - }, - "postcss-modules-local-by-default": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-2.0.6.tgz", - "integrity": "sha512-oLUV5YNkeIBa0yQl7EYnxMgy4N6noxmiwZStaEJUSe2xPMcdNc8WmBQuQCx18H5psYbVxz8zoHk0RAAYZXP9gA==", - "dev": true, - "requires": { - "postcss": "^7.0.6", - "postcss-selector-parser": "^6.0.0", - "postcss-value-parser": "^3.3.1" - } - }, - "postcss-modules-scope": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-2.1.0.tgz", - "integrity": "sha512-91Rjps0JnmtUB0cujlc8KIKCsJXWjzuxGeT/+Q2i2HXKZ7nBUeF9YQTZZTNvHVoNYj1AthsjnGLtqDUE0Op79A==", - "dev": true, - "requires": { - "postcss": "^7.0.6", - "postcss-selector-parser": "^6.0.0" - } - }, - "postcss-modules-values": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-2.0.0.tgz", - "integrity": "sha512-Ki7JZa7ff1N3EIMlPnGTZfUMe69FFwiQPnVSXC9mnn3jozCRBYIxiZd44yJOV2AmabOo4qFf8s0dC/+lweG7+w==", - "dev": true, - "requires": { - "icss-replace-symbols": "^1.1.0", - "postcss": "^7.0.6" - } - }, - "postcss-normalize-charset": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/postcss-normalize-charset/-/postcss-normalize-charset-4.0.1.tgz", - "integrity": "sha512-gMXCrrlWh6G27U0hF3vNvR3w8I1s2wOBILvA87iNXaPvSNo5uZAMYsZG7XjCUf1eVxuPfyL4TJ7++SGZLc9A3g==", - "dev": true, - "requires": { - "postcss": "^7.0.0" - } - }, - "postcss-normalize-display-values": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-normalize-display-values/-/postcss-normalize-display-values-4.0.2.tgz", - "integrity": "sha512-3F2jcsaMW7+VtRMAqf/3m4cPFhPD3EFRgNs18u+k3lTJJlVe7d0YPO+bnwqo2xg8YiRpDXJI2u8A0wqJxMsQuQ==", - "dev": true, - "requires": { - "cssnano-util-get-match": "^4.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-normalize-positions": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-normalize-positions/-/postcss-normalize-positions-4.0.2.tgz", - "integrity": "sha512-Dlf3/9AxpxE+NF1fJxYDeggi5WwV35MXGFnnoccP/9qDtFrTArZ0D0R+iKcg5WsUd8nUYMIl8yXDCtcrT8JrdA==", - "dev": true, - "requires": { - "cssnano-util-get-arguments": "^4.0.0", - "has": "^1.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-normalize-repeat-style": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-normalize-repeat-style/-/postcss-normalize-repeat-style-4.0.2.tgz", - "integrity": "sha512-qvigdYYMpSuoFs3Is/f5nHdRLJN/ITA7huIoCyqqENJe9PvPmLhNLMu7QTjPdtnVf6OcYYO5SHonx4+fbJE1+Q==", - "dev": true, - "requires": { - "cssnano-util-get-arguments": "^4.0.0", - "cssnano-util-get-match": "^4.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-normalize-string": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-normalize-string/-/postcss-normalize-string-4.0.2.tgz", - "integrity": "sha512-RrERod97Dnwqq49WNz8qo66ps0swYZDSb6rM57kN2J+aoyEAJfZ6bMx0sx/F9TIEX0xthPGCmeyiam/jXif0eA==", - "dev": true, - "requires": { - "has": "^1.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-normalize-timing-functions": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-normalize-timing-functions/-/postcss-normalize-timing-functions-4.0.2.tgz", - "integrity": "sha512-acwJY95edP762e++00Ehq9L4sZCEcOPyaHwoaFOhIwWCDfik6YvqsYNxckee65JHLKzuNSSmAdxwD2Cud1Z54A==", - "dev": true, - "requires": { - "cssnano-util-get-match": "^4.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-normalize-unicode": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/postcss-normalize-unicode/-/postcss-normalize-unicode-4.0.1.tgz", - "integrity": "sha512-od18Uq2wCYn+vZ/qCOeutvHjB5jm57ToxRaMeNuf0nWVHaP9Hua56QyMF6fs/4FSUnVIw0CBPsU0K4LnBPwYwg==", - "dev": true, - "requires": { - "browserslist": "^4.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-normalize-url": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/postcss-normalize-url/-/postcss-normalize-url-4.0.1.tgz", - "integrity": "sha512-p5oVaF4+IHwu7VpMan/SSpmpYxcJMtkGppYf0VbdH5B6hN8YNmVyJLuY9FmLQTzY3fag5ESUUHDqM+heid0UVA==", - "dev": true, - "requires": { - "is-absolute-url": "^2.0.0", - "normalize-url": "^3.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-normalize-whitespace": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-normalize-whitespace/-/postcss-normalize-whitespace-4.0.2.tgz", - "integrity": "sha512-tO8QIgrsI3p95r8fyqKV+ufKlSHh9hMJqACqbv2XknufqEDhDvbguXGBBqxw9nsQoXWf0qOqppziKJKHMD4GtA==", - "dev": true, - "requires": { - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-ordered-values": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/postcss-ordered-values/-/postcss-ordered-values-4.1.2.tgz", - "integrity": "sha512-2fCObh5UanxvSxeXrtLtlwVThBvHn6MQcu4ksNT2tsaV2Fg76R2CV98W7wNSlX+5/pFwEyaDwKLLoEV7uRybAw==", - "dev": true, - "requires": { - "cssnano-util-get-arguments": "^4.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-reduce-initial": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/postcss-reduce-initial/-/postcss-reduce-initial-4.0.3.tgz", - "integrity": "sha512-gKWmR5aUulSjbzOfD9AlJiHCGH6AEVLaM0AV+aSioxUDd16qXP1PCh8d1/BGVvpdWn8k/HiK7n6TjeoXN1F7DA==", - "dev": true, - "requires": { - "browserslist": "^4.0.0", - "caniuse-api": "^3.0.0", - "has": "^1.0.0", - "postcss": "^7.0.0" - } - }, - "postcss-reduce-transforms": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-reduce-transforms/-/postcss-reduce-transforms-4.0.2.tgz", - "integrity": "sha512-EEVig1Q2QJ4ELpJXMZR8Vt5DQx8/mo+dGWSR7vWXqcob2gQLyQGsionYcGKATXvQzMPn6DSN1vTN7yFximdIAg==", - "dev": true, - "requires": { - "cssnano-util-get-match": "^4.0.0", - "has": "^1.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0" - } - }, - "postcss-selector-parser": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.2.tgz", - "integrity": "sha512-36P2QR59jDTOAiIkqEprfJDsoNrvwFei3eCqKd1Y0tUsBimsq39BLp7RD+JWny3WgB1zGhJX8XVePwm9k4wdBg==", - "dev": true, - "requires": { - "cssesc": "^3.0.0", - "indexes-of": "^1.0.1", - "uniq": "^1.0.1" - }, - "dependencies": { - "cssesc": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", - "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", - "dev": true - } - } - }, - "postcss-svgo": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-svgo/-/postcss-svgo-4.0.2.tgz", - "integrity": "sha512-C6wyjo3VwFm0QgBy+Fu7gCYOkCmgmClghO+pjcxvrcBKtiKt0uCF+hvbMO1fyv5BMImRK90SMb+dwUnfbGd+jw==", - "dev": true, - "requires": { - "is-svg": "^3.0.0", - "postcss": "^7.0.0", - "postcss-value-parser": "^3.0.0", - "svgo": "^1.0.0" - } - }, - "postcss-unique-selectors": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/postcss-unique-selectors/-/postcss-unique-selectors-4.0.1.tgz", - "integrity": "sha512-+JanVaryLo9QwZjKrmJgkI4Fn8SBgRO6WXQBJi7KiAVPlmxikB5Jzc4EvXMT2H0/m0RjrVVm9rGNhZddm/8Spg==", - "dev": true, - "requires": { - "alphanum-sort": "^1.0.0", - "postcss": "^7.0.0", - "uniqs": "^2.0.0" - } - }, - "postcss-value-parser": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-3.3.1.tgz", - "integrity": "sha512-pISE66AbVkp4fDQ7VHBwRNXzAAKJjw4Vw7nWI/+Q3vuly7SNfgYXvm6i5IgFylHGK5sP/xHAbB7N49OS4gWNyQ==", - "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 - }, - "prepend-http": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", - "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=", - "dev": true - }, - "preserve": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/preserve/-/preserve-0.2.0.tgz", - "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=", - "dev": true - }, - "prettier": { - "version": "1.16.4", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.16.4.tgz", - "integrity": "sha512-ZzWuos7TI5CKUeQAtFd6Zhm2s6EpAD/ZLApIhsF9pRvRtM1RFo61dM/4MSRUA0SuLugA/zgrZD8m0BaY46Og7g==", - "dev": true - }, - "pretty-bytes": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-5.1.0.tgz", - "integrity": "sha512-wa5+qGVg9Yt7PB6rYm3kXlKzgzgivYTLRandezh43jjRqgyDyP+9YxfJpJiLs9yKD1WeU8/OvtToWpW7255FtA==", - "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" - } - }, - "pretty-format": { - "version": "24.5.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-24.5.0.tgz", - "integrity": "sha512-/3RuSghukCf8Riu5Ncve0iI+BzVkbRU5EeUoArKARZobREycuH5O4waxvaNIloEXdb0qwgmEAed5vTpX1HNROQ==", - "dev": true, - "requires": { - "@jest/types": "^24.5.0", - "ansi-regex": "^4.0.0", - "ansi-styles": "^3.2.0", - "react-is": "^16.8.4" - }, - "dependencies": { - "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", - "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" - } - } - } - }, - "private": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/private/-/private-0.1.8.tgz", - "integrity": "sha512-VvivMrbvd2nKkiG38qjULzlc+4Vx4wm/whI9pQD35YrARNnhxeiRktSOhSukRLFNlzg6Br/cJPet5J/u19r/mg==", - "dev": true - }, - "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, - "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 - }, - "promise-retry": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-1.1.1.tgz", - "integrity": "sha1-ZznpaOMFHaIM5kl/srUPaRHfPW0=", - "dev": true, - "requires": { - "err-code": "^1.0.0", - "retry": "^0.10.0" - } - }, - "prompts": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.0.4.tgz", - "integrity": "sha512-HTzM3UWp/99A0gk51gAegwo1QRYA7xjcZufMNe33rCclFszUYAuHe1fIN/3ZmiHeGPkUsNaRyQm1hHOfM0PKxA==", - "dev": true, - "requires": { - "kleur": "^3.0.2", - "sisteransi": "^1.0.0" - } - }, - "property-expr": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/property-expr/-/property-expr-1.5.1.tgz", - "integrity": "sha512-CGuc0VUTGthpJXL36ydB6jnbyOf/rAHFvmVrJlH+Rg0DqqLFQGAP6hIaxD/G0OAmBJPhXDHuEJigrp0e0wFV6g==", - "dev": true - }, - "protoduck": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/protoduck/-/protoduck-5.0.1.tgz", - "integrity": "sha512-WxoCeDCoCBY55BMvj4cAEjdVUFGRWed9ZxPlqTKYyw1nDDTQ4pqmnIMAGfJlg7Dx35uB/M+PHJPTmGOvaCaPTg==", - "dev": true, - "requires": { - "genfun": "^5.0.0" - } - }, - "proxy-addr": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.4.tgz", - "integrity": "sha512-5erio2h9jp5CHGwcybmxmVqHmnCBZeewlfJ0pex+UW7Qny7OOZXTtH56TGNyBizkgiOwhJtMKrVzDTeKcySZwA==", - "dev": true, - "requires": { - "forwarded": "~0.1.2", - "ipaddr.js": "1.8.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 - }, - "psl": { - "version": "1.1.31", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.1.31.tgz", - "integrity": "sha512-/6pt4+C+T+wZUieKR620OpzN/LlnNKuWjy1iFLQ/UG35JqHlR/89MP1d96dUfkf6Dne3TuLQzOYEYshJ+Hx8mw==", - "dev": true - }, - "public-encrypt": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", - "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", - "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", - "safe-buffer": "^5.1.2" - } - }, - "pump": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", - "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", - "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" - }, - "dependencies": { - "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" - } - } - } - }, - "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.5.1", - "resolved": "https://registry.npmjs.org/q/-/q-1.5.1.tgz", - "integrity": "sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=", - "dev": true - }, - "qs": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.2.3.tgz", - "integrity": "sha1-HPyyXBCpsrSDBT/zn138kjOQjP4=", - "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.1.0", - "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.1.0.tgz", - "integrity": "sha512-sluvZZ1YiTLD5jsqZcDmFyV2EwToyXZBfpoVOmktMmW+VEnhgakFHnasVph65fOjGPTWN0Nw3+XQaSeMayr0kg==", - "dev": true - }, - "quick-lru": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-1.1.0.tgz", - "integrity": "sha1-Q2CxfGETatOAeDl/8RQW4Ybc+7g=", - "dev": true - }, - "randexp": { - "version": "0.4.9", - "resolved": "https://registry.npmjs.org/randexp/-/randexp-0.4.9.tgz", - "integrity": "sha512-maAX1cnBkzIZ89O4tSQUOF098xjGMC8N+9vuY/WfHwg87THw6odD2Br35donlj5e6KnB1SB0QBHhTQhhDHuTPQ==", - "dev": true, - "requires": { - "drange": "^1.0.0", - "ret": "^0.2.0" - }, - "dependencies": { - "ret": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/ret/-/ret-0.2.2.tgz", - "integrity": "sha512-M0b3YWQs7R3Z917WRQy1HHA7Ba7D8hvZg6UE5mLykJxQVE2ju0IXbGlaHPPlkY+WN7wFP+wUMXmBFA0aV6vYGQ==", - "dev": true - } - } - }, - "randomatic": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/randomatic/-/randomatic-3.1.1.tgz", - "integrity": "sha512-TuDE5KxZ0J461RVjrJZCJc+J+zCkTb1MbH9AQUq68sMhOMcy9jLcb3BrZKgp9q9Ncltdg4QVqWrH02W2EFFVYw==", - "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.1.0", - "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", - "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", - "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.3", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.3.tgz", - "integrity": "sha512-9esiElv1BrZoI3rCDuOuKCBRbuApGGaDPQfjSflGxdy4oyzqghxu6klEkkVIvBje+FF0BX9coEv8KqW6X/7njw==", - "dev": true, - "requires": { - "bytes": "3.0.0", - "http-errors": "1.6.3", - "iconv-lite": "0.4.23", - "unpipe": "1.0.0" - }, - "dependencies": { - "iconv-lite": { - "version": "0.4.23", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.23.tgz", - "integrity": "sha512-neyTUVFtahjf0mB3dZT77u+8O0QB89jFdnBkd5P1JgYPbPaia3gXXOVL2fq8VyU2gMMD7SaN7QukTB/pmXYvDA==", - "dev": true, - "requires": { - "safer-buffer": ">= 2.1.2 < 3" - } - } - } - }, - "react": { - "version": "0.14.9", - "resolved": "https://registry.npmjs.org/react/-/react-0.14.9.tgz", - "integrity": "sha1-kRCmSXxJ1EuhwO3TF67CnC4NkdE=", - "dev": true, - "requires": { - "envify": "^3.0.0", - "fbjs": "^0.6.1" - } - }, - "react-dom": { - "version": "0.14.9", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-0.14.9.tgz", - "integrity": "sha1-BQZKPc8PsYgKOyv8nVjFXY2fYpM=", - "dev": true - }, - "react-is": { - "version": "16.8.4", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.8.4.tgz", - "integrity": "sha512-PVadd+WaUDOAciICm/J1waJaSvgq+4rHE/K70j0PFqKhkTBsPv/82UGQJNXAngz1fOQLLxI6z1sEDmJDQhCTAA==", - "dev": true - }, - "read-chunk": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/read-chunk/-/read-chunk-2.1.0.tgz", - "integrity": "sha1-agTAkoAF7Z1C4aasVgDhnLx/9lU=", - "dev": true, - "requires": { - "pify": "^3.0.0", - "safe-buffer": "^5.1.1" - }, - "dependencies": { - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - } - } - }, - "read-pkg": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", - "integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=", - "dev": true, - "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=", - "dev": true, - "requires": { - "find-up": "^2.0.0", - "read-pkg": "^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.2.1", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.2.1.tgz", - "integrity": "sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.11", - "micromatch": "^3.1.10", - "readable-stream": "^2.0.2" - } - }, - "realpath-native": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/realpath-native/-/realpath-native-1.1.0.tgz", - "integrity": "sha512-wlgPA6cCIIg9gKz0fgAPjnzh4yR/LnXovwuo9hvyGvx3h8nX4+/iLZplfUWasXpqD8BdnGnP5njOFjkUwPzvjA==", - "dev": true, - "requires": { - "util.promisify": "^1.0.0" - } - }, - "recast": { - "version": "0.11.23", - "resolved": "https://registry.npmjs.org/recast/-/recast-0.11.23.tgz", - "integrity": "sha1-RR/TAEqx5N+bTktmN2sqIZEkYtM=", - "dev": true, - "requires": { - "ast-types": "0.9.6", - "esprima": "~3.1.0", - "private": "~0.1.5", - "source-map": "~0.5.0" - }, - "dependencies": { - "esprima": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", - "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", - "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 - } - } - }, - "rechoir": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz", - "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", - "dev": true, - "requires": { - "resolve": "^1.1.6" - } - }, - "redent": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/redent/-/redent-2.0.0.tgz", - "integrity": "sha1-wbIAe0LVfrE4kHmzyDM2OdXhzKo=", - "dev": true, - "requires": { - "indent-string": "^3.0.0", - "strip-indent": "^2.0.0" - } - }, - "reflect-metadata": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", - "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==", - "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.10.5", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.10.5.tgz", - "integrity": "sha1-M2w+/BIgrc7dosn6tntaeVWjNlg=" - }, - "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" - } - }, - "regexp-to-ast": { - "version": "0.3.5", - "resolved": "https://registry.npmjs.org/regexp-to-ast/-/regexp-to-ast-0.3.5.tgz", - "integrity": "sha512-1CJygtdvsfNFwiyjaMLBWtg2tfEqx/jSZ8S6TV+GlNL8kiH8rb4cm5Pb7A/C2BpyM/fA8ZJEudlCwi/jvAY+Ow==", - "dev": true - }, - "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" - } - }, - "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.3", - "resolved": "https://registry.npmjs.org/renderkid/-/renderkid-2.0.3.tgz", - "integrity": "sha512-z8CLQp7EZBPCwCnncgf9C4XAi3WR0dv+uWu/PjIyhhAb5d6IJ/QZqlHFprHeKT+59//V6BNUsLbvN8+2LarxGA==", - "dev": true, - "requires": { - "css-select": "^1.1.0", - "dom-converter": "^0.2", - "htmlparser2": "^3.3.0", - "strip-ansi": "^3.0.0", - "utila": "^0.4.0" - } - }, - "repeat-element": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.3.tgz", - "integrity": "sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g==", - "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 - }, - "replace-ext": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-0.0.1.tgz", - "integrity": "sha1-KbvZIHinOfC8zitO5B6DeVNSKSQ=", - "dev": true - }, - "request": { - "version": "2.88.0", - "resolved": "https://registry.npmjs.org/request/-/request-2.88.0.tgz", - "integrity": "sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg==", - "dev": true, - "requires": { - "aws-sign2": "~0.7.0", - "aws4": "^1.8.0", - "caseless": "~0.12.0", - "combined-stream": "~1.0.6", - "extend": "~3.0.2", - "forever-agent": "~0.6.1", - "form-data": "~2.3.2", - "har-validator": "~5.1.0", - "http-signature": "~1.2.0", - "is-typedarray": "~1.0.0", - "isstream": "~0.1.2", - "json-stringify-safe": "~5.0.1", - "mime-types": "~2.1.19", - "oauth-sign": "~0.9.0", - "performance-now": "^2.1.0", - "qs": "~6.5.2", - "safe-buffer": "^5.1.2", - "tough-cookie": "~2.4.3", - "tunnel-agent": "^0.6.0", - "uuid": "^3.3.2" - }, - "dependencies": { - "punycode": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", - "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", - "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 - }, - "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==", - "dev": true, - "requires": { - "psl": "^1.1.24", - "punycode": "^1.4.1" - } - } - } - }, - "request-promise-core": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.2.tgz", - "integrity": "sha512-UHYyq1MO8GsefGEt7EprS8UrXsm1TxEvFUX1IMTuSLU2Rh7fTIdFtl8xD7JiEYiWU2dl+NYAjCTksTehQUxPag==", - "dev": true, - "requires": { - "lodash": "^4.17.11" - } - }, - "request-promise-native": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/request-promise-native/-/request-promise-native-1.0.7.tgz", - "integrity": "sha512-rIMnbBdgNViL37nZ1b3L/VfPOpSi0TqVDQPAvO6U14lMzOLrt5nilxCQqtDKhZeDiW0/hkCXGoQjhgJd/tCh6w==", - "dev": true, - "requires": { - "request-promise-core": "1.1.2", - "stealthy-require": "^1.1.1", - "tough-cookie": "^2.3.3" - } - }, - "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.10.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.10.0.tgz", - "integrity": "sha512-3sUr9aq5OfSg2S9pNtPA9hL1FVEAjvfOC4leW0SNf/mpnaakz2a9femSd6LqAww2RaFctwyf1lCqnTHuF1rxDg==", - "dev": true, - "requires": { - "path-parse": "^1.0.6" - } - }, - "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-dir": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", - "integrity": "sha1-eaQGRMNivoLybv/nOcm7U4IEb0M=", - "dev": true, - "requires": { - "expand-tilde": "^2.0.0", - "global-modules": "^1.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 - }, - "resp-modifier": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/resp-modifier/-/resp-modifier-6.0.2.tgz", - "integrity": "sha1-sSTeXE+6/LpUH0j/pzlw9KpFa08=", - "dev": true, - "requires": { - "debug": "^2.2.0", - "minimatch": "^3.0.2" - } - }, - "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==", - "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 - }, - "rgb-regex": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/rgb-regex/-/rgb-regex-1.0.1.tgz", - "integrity": "sha1-wODWiC3w4jviVKR16O3UGRX+rrE=", - "dev": true - }, - "rgba-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/rgba-regex/-/rgba-regex-1.0.0.tgz", - "integrity": "sha1-QzdOLiyglosO8VI0YLfXMP8i7rM=", - "dev": true - }, - "rimraf": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", - "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", - "dev": true, - "requires": { - "glob": "^7.1.3" - } - }, - "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" - } - }, - "rsvp": { - "version": "4.8.4", - "resolved": "https://registry.npmjs.org/rsvp/-/rsvp-4.8.4.tgz", - "integrity": "sha512-6FomvYPfs+Jy9TfXmBpBuMWNH94SgCsZmJKcanySzgNNP6LjWxBvyLTa9KaMfDDM5oxRfrKDB0r/qeRsLwnBfA==", - "dev": true - }, - "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" - } - }, - "run-node": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/run-node/-/run-node-1.0.0.tgz", - "integrity": "sha512-kc120TBlQ3mih1LSzdAJXo4xn/GWS2ec0l3S+syHDXP9uRr0JAT8Qd3mdMuyjqCzeZktgP3try92cEgf9Nks8A==", - "dev": true - }, - "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" - } - }, - "rx": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/rx/-/rx-4.1.0.tgz", - "integrity": "sha1-pfE/957zt0D+MKqAP7CfmIBdR4I=" - }, - "rxjs": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.4.0.tgz", - "integrity": "sha512-Z9Yfa11F6B9Sg/BK9MnqnQ+aQYicPLtilXBp2yUtDt2JRCE0h26d33EnfO3ZxoNxG0T92OUucP3Ct7cpfkdFfw==", - "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==" - }, - "sane": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/sane/-/sane-4.1.0.tgz", - "integrity": "sha512-hhbzAgTIX8O7SHfp2c8/kREfEn4qO/9q8C9beyY6+tvZ87EpoZ3i1RIEvp27YBswnNbY9mWd6paKVmKbAgLfZA==", - "dev": true, - "requires": { - "@cnakazawa/watch": "^1.0.3", - "anymatch": "^2.0.0", - "capture-exit": "^2.0.0", - "exec-sh": "^0.3.2", - "execa": "^1.0.0", - "fb-watchman": "^2.0.0", - "micromatch": "^3.1.4", - "minimist": "^1.1.1", - "walker": "~1.0.5" - }, - "dependencies": { - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "execa": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", - "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", - "dev": true, - "requires": { - "cross-spawn": "^6.0.0", - "get-stream": "^4.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" - } - } - } - }, - "sass": { - "version": "1.17.0", - "resolved": "https://registry.npmjs.org/sass/-/sass-1.17.0.tgz", - "integrity": "sha512-aFi9RQqrCYkHB2DaLKBBbdUhos1N5o3l1ke9N5JqWzgSPmYwZsdmA+ViPVatUy/RPA21uejgYVUXM7GCh8lcdw==", - "dev": true, - "requires": { - "chokidar": "^2.0.0" - } - }, - "sass-loader": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-7.1.0.tgz", - "integrity": "sha512-+G+BKGglmZM2GUSfT9TLuEp6tzehHPjAMoRRItOojWIqIGPloVCMhNIQuG639eJ+y033PaGTSjLaTHts8Kw79w==", - "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", - "semver": "^5.5.0" - }, - "dependencies": { - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - } - } - }, - "sax": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", - "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", - "dev": true - }, - "schema-utils": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz", - "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", - "dev": true, - "requires": { - "ajv": "^6.1.0", - "ajv-errors": "^1.0.0", - "ajv-keywords": "^3.1.0" - } - }, - "scoped-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/scoped-regex/-/scoped-regex-1.0.0.tgz", - "integrity": "sha1-o0a7Gs1CB65wvXwMfKnlZra63bg=", - "dev": true - }, - "select-hose": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz", - "integrity": "sha1-Yl2GWPhlr0Psliv8N2o3NZpJlMo=", - "dev": true - }, - "selfsigned": { - "version": "1.10.4", - "resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-1.10.4.tgz", - "integrity": "sha512-9AukTiDmHXGXWtWjembZ5NDmVvP2695EtpgbCsxCa68w3c88B+alqbmZ4O3hZ4VWGXeGWzEVdvqgAJD8DQPCDw==", - "dev": true, - "requires": { - "node-forge": "0.7.5" - } - }, - "semver": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz", - "integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==", - "dev": true - }, - "semver-compare": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", - "integrity": "sha1-De4hahyUGrN+nvsXiPavxf9VN/w=", - "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.4.0", - "resolved": "https://registry.npmjs.org/semver-intersect/-/semver-intersect-1.4.0.tgz", - "integrity": "sha512-d8fvGg5ycKAq0+I6nfWeCx6ffaWJCsBYU0H2Rq56+/zFePYfT8mXkB3tWBSjR5BerkHNZ5eTPIk1/LBYas35xQ==", - "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": { - "statuses": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz", - "integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==", - "dev": true - } - } - }, - "serialize-javascript": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-1.6.1.tgz", - "integrity": "sha512-A5MOagrPFga4YaKQSWHryl7AXvbQkEqpw4NNYMTNYUNV51bA8ABHgYFpqKx+YFFrw59xMV1qGH1R4AgoNIVgCw==", - "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" - } - }, - "server-destroy": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/server-destroy/-/server-destroy-1.0.1.tgz", - "integrity": "sha1-8Tv5KOQrnD55OD5hzDmYtdFObN0=", - "dev": true - }, - "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-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 - }, - "shelljs": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.3.tgz", - "integrity": "sha512-fc0BKlAWiLpwZljmOvAOTE/gXawtCoNrP5oaY7KIaQbbyHeQVg01pSEuEGvGh3HEdBU4baCD7wQBwADmM/7f7A==", - "dev": true, - "requires": { - "glob": "^7.0.0", - "interpret": "^1.0.0", - "rechoir": "^0.6.2" - } - }, - "shellwords": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/shellwords/-/shellwords-0.1.1.tgz", - "integrity": "sha512-vFwSUfQvqybiICwZY5+DAWIPLKsWO31Q91JSKl3UYv+K5c2QRPzn0qzec6QPu1Qc9eHYItiP3NdJqNVqetYAww==", - "dev": true - }, - "signal-exit": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", - "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=" - }, - "simple-git": { - "version": "1.107.0", - "resolved": "https://registry.npmjs.org/simple-git/-/simple-git-1.107.0.tgz", - "integrity": "sha512-t4OK1JRlp4ayKRfcW6owrWcRVLyHRUlhGd0uN6ZZTqfDq8a5XpcUdOKiGRNobHEuMtNqzp0vcJNvhYWwh5PsQA==", - "dev": true, - "requires": { - "debug": "^4.0.1" - }, - "dependencies": { - "debug": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", - "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - } - } - }, - "simple-progress-webpack-plugin": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/simple-progress-webpack-plugin/-/simple-progress-webpack-plugin-1.1.2.tgz", - "integrity": "sha512-bNQfb3qSqbtsfxg6d0dGechUUJH2lZqKG5+bj2aoJmEA0rSzcm+2JVfC2YgkDABfuGItZ/O5ttt6BssWZW4SNg==", - "dev": true, - "requires": { - "chalk": "2.3.x", - "figures": "2.0.x", - "log-update": "2.3.x" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.2.tgz", - "integrity": "sha512-ZM4j2/ld/YZDc3Ma8PgN7gyAk+kHMMMyzLNryCPGhWrsfAuDVeuid5bpRFTDgMH9JBK2lA4dyyAkkZYF/WcqDQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "simple-swizzle": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", - "integrity": "sha1-pNprY1/8zMoz9w0Xy5JZLeleVXo=", - "dev": true, - "requires": { - "is-arrayish": "^0.3.1" - }, - "dependencies": { - "is-arrayish": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", - "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==", - "dev": true - } - } - }, - "sisteransi": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.0.tgz", - "integrity": "sha512-N+z4pHB4AmUv0SjveWRd6q1Nj5w62m5jodv+GD8lvmbY/83T/rpbJGZOnK5T149OldDj4Db07BSv9xY4K6NTPQ==", - "dev": true - }, - "slash": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz", - "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=", - "dev": true - }, - "slice-ansi": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-0.0.4.tgz", - "integrity": "sha1-7b+JA/ZvfOL46v1s7tZeJkyDGzU=", - "dev": true - }, - "smart-buffer": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.0.2.tgz", - "integrity": "sha512-JDhEpTKzXusOqXZ0BUIdH+CjFdO/CR3tLlf5CN34IypI+xMmXW1uB16OOY8z3cICbJlDAVJzNbwBhNO0wt9OAw==", - "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" - } - }, - "source-map": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true - } - } - }, - "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" - } - } - } - }, - "socket.io": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-2.1.1.tgz", - "integrity": "sha512-rORqq9c+7W0DAK3cleWNSyfv/qKXV99hV4tZe+gGLfBECw3XEhBy7x85F3wypA9688LKjtwO9pX9L33/xQI8yA==", - "dev": true, - "requires": { - "debug": "~3.1.0", - "engine.io": "~3.2.0", - "has-binary2": "~1.0.2", - "socket.io-adapter": "~1.1.0", - "socket.io-client": "2.1.1", - "socket.io-parser": "~3.2.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" - } - }, - "engine.io-client": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-3.2.1.tgz", - "integrity": "sha512-y5AbkytWeM4jQr7m/koQLc5AxpRKC1hEVUb/s1FUAWEJq5AzJJ4NLvzuKPuxtDi5Mq755WuDvZ6Iv2rXj4PTzw==", - "dev": true, - "requires": { - "component-emitter": "1.2.1", - "component-inherit": "0.0.3", - "debug": "~3.1.0", - "engine.io-parser": "~2.1.1", - "has-cors": "1.1.0", - "indexof": "0.0.1", - "parseqs": "0.0.5", - "parseuri": "0.0.5", - "ws": "~3.3.1", - "xmlhttprequest-ssl": "~1.5.4", - "yeast": "0.1.2" - } - }, - "isarray": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.1.tgz", - "integrity": "sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4=", - "dev": true - }, - "socket.io-client": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-2.1.1.tgz", - "integrity": "sha512-jxnFyhAuFxYfjqIgduQlhzqTcOEQSn+OHKVfAxWaNWa7ecP7xSNk2Dx/3UEsDcY7NcFafxvNvKPmmO7HTwTxGQ==", - "dev": true, - "requires": { - "backo2": "1.0.2", - "base64-arraybuffer": "0.1.5", - "component-bind": "1.0.0", - "component-emitter": "1.2.1", - "debug": "~3.1.0", - "engine.io-client": "~3.2.0", - "has-binary2": "~1.0.2", - "has-cors": "1.1.0", - "indexof": "0.0.1", - "object-component": "0.0.3", - "parseqs": "0.0.5", - "parseuri": "0.0.5", - "socket.io-parser": "~3.2.0", - "to-array": "0.1.4" - } - }, - "socket.io-parser": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-3.2.0.tgz", - "integrity": "sha512-FYiBx7rc/KORMJlgsXysflWx/RIvtqZbyGLlHZvjfmPTPeuD/I8MaW7cfFrj5tRltICJdgwflhfZ3NVVbVLFQA==", - "dev": true, - "requires": { - "component-emitter": "1.2.1", - "debug": "~3.1.0", - "isarray": "2.0.1" - } - }, - "ws": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-3.3.3.tgz", - "integrity": "sha512-nnWLa/NwZSt4KQJu51MYlCcSQ5g7INpOrOMt4XV8j4dqTXdmlUmSHQ8/oLC069ckre0fRsgfvsKwbTdtKLCDkA==", - "dev": true, - "requires": { - "async-limiter": "~1.0.0", - "safe-buffer": "~5.1.0", - "ultron": "~1.1.0" - } - } - } - }, - "socket.io-adapter": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-1.1.1.tgz", - "integrity": "sha1-KoBeihTWNyEk3ZFZrUUC+MsH8Gs=", - "dev": true - }, - "socket.io-client": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-2.2.0.tgz", - "integrity": "sha512-56ZrkTDbdTLmBIyfFYesgOxsjcLnwAKoN4CiPyTVkMQj3zTUh0QAx3GbvIvLpFEOvQWu92yyWICxB0u7wkVbYA==", - "dev": true, - "requires": { - "backo2": "1.0.2", - "base64-arraybuffer": "0.1.5", - "component-bind": "1.0.0", - "component-emitter": "1.2.1", - "debug": "~3.1.0", - "engine.io-client": "~3.3.1", - "has-binary2": "~1.0.2", - "has-cors": "1.1.0", - "indexof": "0.0.1", - "object-component": "0.0.3", - "parseqs": "0.0.5", - "parseuri": "0.0.5", - "socket.io-parser": "~3.3.0", - "to-array": "0.1.4" - }, - "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" - } - } - } - }, - "socket.io-parser": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-3.3.0.tgz", - "integrity": "sha512-hczmV6bDgdaEbVqhAeVMM/jfUfzuEZHsQg6eOmLgJht6G3mPKMxYm75w2+qhAQZ+4X+1+ATZ+QFKeOZD5riHng==", - "dev": true, - "requires": { - "component-emitter": "1.2.1", - "debug": "~3.1.0", - "isarray": "2.0.1" - }, - "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" - } - }, - "isarray": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.1.tgz", - "integrity": "sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4=", - "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.3.0", - "resolved": "https://registry.npmjs.org/sockjs-client/-/sockjs-client-1.3.0.tgz", - "integrity": "sha512-R9jxEzhnnrdxLCNln0xg5uGHqMnkhPSTzUZH2eXcR03S/On9Yvoq2wyUZILRUhZCNVu2PmwWVoyuiPz8th8zbg==", - "dev": true, - "requires": { - "debug": "^3.2.5", - "eventsource": "^1.0.7", - "faye-websocket": "~0.11.1", - "inherits": "^2.0.3", - "json3": "^3.3.2", - "url-parse": "^1.4.3" - }, - "dependencies": { - "debug": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "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" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - } - } - }, - "socks": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/socks/-/socks-2.3.2.tgz", - "integrity": "sha512-pCpjxQgOByDHLlNqlnh/mNSAxIUkyBBuwwhTcV+enZGbDaClPvHdvm6uvOwZfFJkam7cGhBNbb4JxiP8UZkRvQ==", - "dev": true, - "requires": { - "ip": "^1.1.5", - "smart-buffer": "4.0.2" - } - }, - "socks-proxy-agent": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-4.0.2.tgz", - "integrity": "sha512-NT6syHhI9LmuEMSK6Kd2V7gNv5KFZoLE7V5udWmn0de+3Mkj3UMA/AJPLyeNUVmElCurSHtUdM3ETpR3z770Wg==", - "dev": true, - "requires": { - "agent-base": "~4.2.1", - "socks": "~2.3.2" - } - }, - "source-list-map": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz", - "integrity": "sha512-qnQ7gVMxGNxsiL4lEuJwe/To8UnK7fAnmbGEEH8RpLouuKbeEm0lhbQVFIrNSuB+G7tVrAlVsZgETT5nljf+Iw==", - "dev": true - }, - "source-map": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", - "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", - "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.11", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.11.tgz", - "integrity": "sha512-//sajEx/fGL3iw6fltKMdPvy8kL3kJ2O3iuYlRoT3k9Kb4BjOoZ+BZzaNHeuaruSt+Kf3Zk9tnfAQg9/AJqUVQ==", - "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 - }, - "sourcemap-codec": { - "version": "1.4.4", - "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.4.tgz", - "integrity": "sha512-CYAPYdBu34781kLHkaW3m6b/uUSyMOC2R61gcYMWooeuaGtjof86ZA/8T+qVPPt7np1085CR9hmMGrySwEc8Xg==", - "dev": true - }, - "spawn-sync": { - "version": "1.0.15", - "resolved": "https://registry.npmjs.org/spawn-sync/-/spawn-sync-1.0.15.tgz", - "integrity": "sha1-sAeZVX63+wyDdsKdROih6mfldHY=", - "dev": true, - "requires": { - "concat-stream": "^1.4.7", - "os-shim": "^0.1.2" - } - }, - "spdx-correct": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.0.tgz", - "integrity": "sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q==", - "dev": true, - "requires": { - "spdx-expression-parse": "^3.0.0", - "spdx-license-ids": "^3.0.0" - } - }, - "spdx-exceptions": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz", - "integrity": "sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA==", - "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.3", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.3.tgz", - "integrity": "sha512-uBIcIl3Ih6Phe3XHK1NqboJLdGfwr1UN3k6wSD1dZpmPsIkb8AGNbZYJ1fOBk834+Gxy8rpfDxrS6XLEMZMY2g==", - "dev": true - }, - "spdy": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/spdy/-/spdy-4.0.0.tgz", - "integrity": "sha512-ot0oEGT/PGUpzf/6uk4AWLqkq+irlqHXkrdbk51oWONh3bxQmBuljxPNl66zlRRcIJStWq0QkLUCPOPjgjvU0Q==", - "dev": true, - "requires": { - "debug": "^4.1.0", - "handle-thing": "^2.0.0", - "http-deceiver": "^1.2.7", - "select-hose": "^2.0.0", - "spdy-transport": "^3.0.0" - }, - "dependencies": { - "debug": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", - "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - } - } - }, - "spdy-transport": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/spdy-transport/-/spdy-transport-3.0.0.tgz", - "integrity": "sha512-hsLVFE5SjA6TCisWeJXFKniGGOpBgMLmerfO2aCyCU5s7nJ/rpAepqmFifv/GCbSbueEeAJJnmSQ2rKC/g8Fcw==", - "dev": true, - "requires": { - "debug": "^4.1.0", - "detect-node": "^2.0.4", - "hpack.js": "^2.1.6", - "obuf": "^1.1.2", - "readable-stream": "^3.0.6", - "wbuf": "^1.7.3" - }, - "dependencies": { - "debug": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", - "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - }, - "readable-stream": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.2.0.tgz", - "integrity": "sha512-RV20kLjdmpZuTF1INEb9IA3L68Nmi+Ri7ppZqo78wj//Pn62fCoJyV9zalccNzDD/OuJpMG4f+pfMl8+L6QdGw==", - "dev": true, - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - } - } - }, - "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.1.2", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.2.tgz", - "integrity": "sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug==", - "dev": true - }, - "sshpk": { - "version": "1.16.1", - "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", - "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", - "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": "6.0.1", - "resolved": "https://registry.npmjs.org/ssri/-/ssri-6.0.1.tgz", - "integrity": "sha512-3Wge10hNcT1Kur4PDFwEieXSCMCJs/7WvSACcrMYrNp+b8kDL1/0wJch5Ni2WrtwEa2IO8OsVfeKIciKCDx/QA==", - "dev": true, - "requires": { - "figgy-pudding": "^3.5.1" - } - }, - "stable": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.8.tgz", - "integrity": "sha512-ji9qxRnOVfcuLDySj9qzhGSEFVobyt1kIOSkj1qZzYLzq7Tos/oUUWvotUPQLlrsidqsK6tBH89Bc9kL5zHA6w==", - "dev": true - }, - "stack-trace": { - "version": "0.0.10", - "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", - "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", - "dev": true - }, - "stack-utils": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-1.0.2.tgz", - "integrity": "sha512-MTX+MeG5U994cazkjd/9KNAapsHnibjMLnfXodlkXw76JEea0UiNzrqidzo1emMwk7w5Qhc9jd4Bn9TBb1MFwA==", - "dev": true - }, - "stackframe": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/stackframe/-/stackframe-1.0.4.tgz", - "integrity": "sha512-to7oADIniaYwS3MhtCa/sQhrxidCCQiF/qp4/m5iN3ipf0Y7Xlri0f6eG29r08aL7JYl8n32AF3Q5GYBZ7K8vw==", - "dev": true - }, - "staged-git-files": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/staged-git-files/-/staged-git-files-1.1.2.tgz", - "integrity": "sha512-0Eyrk6uXW6tg9PYkhi/V/J4zHp33aNyi2hOCmhFLqLTIhbgqWn5jlSzI+IU0VqrZq6+DbHcabQl/WP6P3BG0QA==", - "dev": true - }, - "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" - } - } - } - }, - "statuses": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", - "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=", - "dev": true - }, - "stealthy-require": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/stealthy-require/-/stealthy-require-1.1.1.tgz", - "integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=", - "dev": true - }, - "stream-browserify": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.2.tgz", - "integrity": "sha512-nX6hmklHs/gr2FuxYDltq8fJA1GDlxKQCz8O/IM4atRqBH8OORmBNgfvW5gG10GT/qQ9u0CzIvr2X5Pkt6ntqg==", - "dev": true, - "requires": { - "inherits": "~2.0.1", - "readable-stream": "^2.0.2" - } - }, - "stream-each": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/stream-each/-/stream-each-1.2.3.tgz", - "integrity": "sha512-vlMC2f8I2u/bZGqkdfLQW/13Zihpej/7PmSiMQsbYddxuTsJp8vRe2x2FvVExZg7FaOds43ROAuFJwPR4MTZLw==", - "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 - }, - "stream-throttle": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/stream-throttle/-/stream-throttle-0.1.3.tgz", - "integrity": "sha1-rdV8jXzHOoFjDTHNVdOWHPr7qcM=", - "dev": true, - "requires": { - "commander": "^2.2.0", - "limiter": "^1.0.5" - } - }, - "streamfilter": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/streamfilter/-/streamfilter-1.0.7.tgz", - "integrity": "sha512-Gk6KZM+yNA1JpW0KzlZIhjo3EaBJDkYfXtYSbOwNIQ7Zd6006E6+sCFlW1NDvFG/vnXhKmw6TJJgiEQg/8lXfQ==", - "dev": true, - "requires": { - "readable-stream": "^2.0.2" - } - }, - "string-argv": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.0.2.tgz", - "integrity": "sha1-2sMECGkMIfPDYwo/86BYd73L1zY=", - "dev": true - }, - "string-length": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/string-length/-/string-length-2.0.0.tgz", - "integrity": "sha1-1A27aGo6zpYMHP/KVivyxF+DY+0=", - "dev": true, - "requires": { - "astral-regex": "^1.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=", - "dev": true - }, - "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" - } - } - } - }, - "string-template": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/string-template/-/string-template-0.2.1.tgz", - "integrity": "sha1-QpMuWYo1LQH8IuwzZ9nYTuxsmt0=", - "dev": true - }, - "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==", - "dev": true, - "requires": { - "safe-buffer": "~5.1.0" - } - }, - "stringify-object": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz", - "integrity": "sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==", - "dev": true, - "requires": { - "get-own-enumerable-property-symbols": "^3.0.0", - "is-obj": "^1.0.1", - "is-regexp": "^1.0.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": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", - "dev": true - }, - "strip-bom-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-bom-stream/-/strip-bom-stream-2.0.0.tgz", - "integrity": "sha1-+H217yYT9paKpUWr/h7HKLaoKco=", - "dev": true, - "requires": { - "first-chunk-stream": "^2.0.0", - "strip-bom": "^2.0.0" - }, - "dependencies": { - "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-comments": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/strip-comments/-/strip-comments-1.0.2.tgz", - "integrity": "sha512-kL97alc47hoyIQSV165tTt9rG5dn4w1dNnBhOQ3bOU1Nc1hel09jnXANaHJ7vzHLd4Ju8kseDGzlev96pghLFw==", - "dev": true, - "requires": { - "babel-extract-comments": "^1.0.0", - "babel-plugin-transform-object-rest-spread": "^6.26.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": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", - "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=", - "dev": true - }, - "style-loader": { - "version": "0.23.1", - "resolved": "https://registry.npmjs.org/style-loader/-/style-loader-0.23.1.tgz", - "integrity": "sha512-XK+uv9kWwhZMZ1y7mysB+zoihsEj4wneFWAS5qoiLwzW0WzSqMrrsIy+a3zkQJq0ipFtBpX5W3MqyRIBF/WFGg==", - "dev": true, - "requires": { - "loader-utils": "^1.1.0", - "schema-utils": "^1.0.0" - } - }, - "stylehacks": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/stylehacks/-/stylehacks-4.0.3.tgz", - "integrity": "sha512-7GlLk9JwlElY4Y6a/rmbH2MhVlTyVmiJd1PfTCqFaIBEGMYNsrO/v3SeGTdhBThLg4Z+NbOk/qFMwCa+J+3p/g==", - "dev": true, - "requires": { - "browserslist": "^4.0.0", - "postcss": "^7.0.0", - "postcss-selector-parser": "^3.0.0" - }, - "dependencies": { - "postcss-selector-parser": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-3.1.1.tgz", - "integrity": "sha1-T4dfSvsMllc9XPTXQBGu4lCn6GU=", - "dev": true, - "requires": { - "dot-prop": "^4.1.1", - "indexes-of": "^1.0.1", - "uniq": "^1.0.1" - } - } - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - }, - "svgo": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/svgo/-/svgo-1.2.0.tgz", - "integrity": "sha512-xBfxJxfk4UeVN8asec9jNxHiv3UAMv/ujwBWGYvQhhMb2u3YTGKkiybPcLFDLq7GLLWE9wa73e0/m8L5nTzQbw==", - "dev": true, - "requires": { - "chalk": "^2.4.1", - "coa": "^2.0.2", - "css-select": "^2.0.0", - "css-select-base-adapter": "^0.1.1", - "css-tree": "1.0.0-alpha.28", - "css-url-regex": "^1.1.0", - "csso": "^3.5.1", - "js-yaml": "^3.12.0", - "mkdirp": "~0.5.1", - "object.values": "^1.1.0", - "sax": "~1.2.4", - "stable": "^0.1.8", - "unquote": "~1.1.1", - "util.promisify": "~1.0.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "css-select": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/css-select/-/css-select-2.0.2.tgz", - "integrity": "sha512-dSpYaDVoWaELjvZ3mS6IKZM/y2PMPa/XYoEfYNZePL4U/XgyxZNroHEHReDx/d+VgXh9VbCTtFqLkFbmeqeaRQ==", - "dev": true, - "requires": { - "boolbase": "^1.0.0", - "css-what": "^2.1.2", - "domutils": "^1.7.0", - "nth-check": "^1.0.2" - } - }, - "domutils": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.7.0.tgz", - "integrity": "sha512-Lgd2XcJ/NjEw+7tFvfKxOzCYKZsdct5lczQ2ZaQY8Djz7pfAD3Gbp8ySJWtreII/vDlMVmxwa6pHmdxIYgttDg==", - "dev": true, - "requires": { - "dom-serializer": "0", - "domelementtype": "1" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "swagger-ui": { - "version": "2.2.10", - "resolved": "https://registry.npmjs.org/swagger-ui/-/swagger-ui-2.2.10.tgz", - "integrity": "sha1-sl56IWZOXZC/OR2zDbCN5B6FLXs=" - }, - "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 - }, - "symbol-tree": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.2.tgz", - "integrity": "sha1-rifbOPZgp64uHDt9G8KQgZuFGeY=", - "dev": true - }, - "synchronous-promise": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/synchronous-promise/-/synchronous-promise-2.0.6.tgz", - "integrity": "sha512-TyOuWLwkmtPL49LHCX1caIwHjRzcVd62+GF6h8W/jHOeZUFHpnd2XJDVuUlaTaLPH1nuu2M69mfHr5XbQJnf/g==", - "dev": true - }, - "tabtab": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/tabtab/-/tabtab-2.2.2.tgz", - "integrity": "sha1-egR/FDsBC0y9MfhX6ClhUSy/ThQ=", - "dev": true, - "requires": { - "debug": "^2.2.0", - "inquirer": "^1.0.2", - "lodash.difference": "^4.5.0", - "lodash.uniq": "^4.5.0", - "minimist": "^1.2.0", - "mkdirp": "^0.5.1", - "npmlog": "^2.0.3", - "object-assign": "^4.1.0" - }, - "dependencies": { - "cli-cursor": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-1.0.2.tgz", - "integrity": "sha1-ZNo/fValRBLll5S9Ytw1KV6PKYc=", - "dev": true, - "requires": { - "restore-cursor": "^1.0.1" - } - }, - "external-editor": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-1.1.1.tgz", - "integrity": "sha1-Etew24UPf/fnCBuvQAVwAGDEYAs=", - "dev": true, - "requires": { - "extend": "^3.0.0", - "spawn-sync": "^1.0.15", - "tmp": "^0.0.29" - } - }, - "figures": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-1.7.0.tgz", - "integrity": "sha1-y+Hjr/zxzUS4DK3+0o3Hk6lwHS4=", - "dev": true, - "requires": { - "escape-string-regexp": "^1.0.5", - "object-assign": "^4.1.0" - } - }, - "inquirer": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-1.2.3.tgz", - "integrity": "sha1-TexvMvN+97sLLtPx0aXD9UUHSRg=", - "dev": true, - "requires": { - "ansi-escapes": "^1.1.0", - "chalk": "^1.0.0", - "cli-cursor": "^1.0.1", - "cli-width": "^2.0.0", - "external-editor": "^1.1.0", - "figures": "^1.3.5", - "lodash": "^4.3.0", - "mute-stream": "0.0.6", - "pinkie-promise": "^2.0.0", - "run-async": "^2.2.0", - "rx": "^4.1.0", - "string-width": "^1.0.1", - "strip-ansi": "^3.0.0", - "through": "^2.3.6" - } - }, - "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" - } - }, - "mute-stream": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.6.tgz", - "integrity": "sha1-SJYrGeFp/R38JAs/HnMXYnu8R9s=", - "dev": true - }, - "onetime": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-1.1.0.tgz", - "integrity": "sha1-ofeDj4MUxRbwXs78vEzP4EtO14k=", - "dev": true - }, - "restore-cursor": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-1.0.1.tgz", - "integrity": "sha1-NGYfRohjJ/7SmRR5FSJS35LapUE=", - "dev": true, - "requires": { - "exit-hook": "^1.0.0", - "onetime": "^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=", - "dev": true, - "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "strip-ansi": "^3.0.0" - } - }, - "tmp": { - "version": "0.0.29", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.29.tgz", - "integrity": "sha1-8lEl/w3Z2jzLDC3Tce4SiLuRKMA=", - "dev": true, - "requires": { - "os-tmpdir": "~1.0.1" - } - } - } - }, - "tapable": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.1.1.tgz", - "integrity": "sha512-9I2ydhj8Z9veORCw5PRm4u9uebCn0mcCa6scWoNcbZ6dAtoo2618u9UUzxgmsCOreJpqDDuv61LvwofW7hLcBA==", - "dev": true - }, - "tar": { - "version": "4.4.8", - "resolved": "https://registry.npmjs.org/tar/-/tar-4.4.8.tgz", - "integrity": "sha512-LzHF64s5chPQQS0IYBn9IN5h3i98c12bo4NCO7e0sGM2llXQ3p2FGC5sdENN4cTW48O915Sh+x+EXx7XW96xYQ==", - "dev": true, - "requires": { - "chownr": "^1.1.1", - "fs-minipass": "^1.2.5", - "minipass": "^2.3.4", - "minizlib": "^1.1.1", - "mkdirp": "^0.5.0", - "safe-buffer": "^5.1.2", - "yallist": "^3.0.2" - } - }, - "terser": { - "version": "3.17.0", - "resolved": "https://registry.npmjs.org/terser/-/terser-3.17.0.tgz", - "integrity": "sha512-/FQzzPJmCpjAH9Xvk2paiWrFq+5M6aVOf+2KRbwhByISDX/EujxsK+BAvrhb6H+2rtrLCHK9N01wO014vrIwVQ==", - "dev": true, - "requires": { - "commander": "^2.19.0", - "source-map": "~0.6.1", - "source-map-support": "~0.5.10" - }, - "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 - } - } - }, - "terser-webpack-plugin": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-1.2.2.tgz", - "integrity": "sha512-1DMkTk286BzmfylAvLXwpJrI7dWa5BnFmscV/2dCr8+c56egFcbaeFAl7+sujAjdmpLam21XRdhA4oifLyiWWg==", - "dev": true, - "requires": { - "cacache": "^11.0.2", - "find-cache-dir": "^2.0.0", - "schema-utils": "^1.0.0", - "serialize-javascript": "^1.4.0", - "source-map": "^0.6.1", - "terser": "^3.16.1", - "webpack-sources": "^1.1.0", - "worker-farm": "^1.5.2" - }, - "dependencies": { - "find-cache-dir": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-2.1.0.tgz", - "integrity": "sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==", - "dev": true, - "requires": { - "commondir": "^1.0.1", - "make-dir": "^2.0.0", - "pkg-dir": "^3.0.0" - } - }, - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "make-dir": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", - "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", - "dev": true, - "requires": { - "pify": "^4.0.1", - "semver": "^5.6.0" - } - }, - "p-limit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", - "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.1.0.tgz", - "integrity": "sha512-H2RyIJ7+A3rjkwKC2l5GGtU4H1vkxKCAGsWasNVd0Set+6i4znxbWy6/j16YDPJDWxhsgZiKAstMEP8wCdSpjA==", - "dev": true - }, - "pify": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", - "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", - "dev": true - }, - "pkg-dir": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", - "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", - "dev": true, - "requires": { - "find-up": "^3.0.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 - } - } - }, - "test-exclude": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-5.1.0.tgz", - "integrity": "sha512-gwf0S2fFsANC55fSeSqpb8BYk6w3FDvwZxfNjeF6FRgvFa43r+7wRiA/Q0IxoRU37wB/LE8IQ4221BsNucTaCA==", - "dev": true, - "requires": { - "arrify": "^1.0.1", - "minimatch": "^3.0.4", - "read-pkg-up": "^4.0.0", - "require-main-filename": "^1.0.1" - }, - "dependencies": { - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "load-json-file": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", - "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "parse-json": "^4.0.0", - "pify": "^3.0.0", - "strip-bom": "^3.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "p-limit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", - "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.1.0.tgz", - "integrity": "sha512-H2RyIJ7+A3rjkwKC2l5GGtU4H1vkxKCAGsWasNVd0Set+6i4znxbWy6/j16YDPJDWxhsgZiKAstMEP8wCdSpjA==", - "dev": true - }, - "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" - } - }, - "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" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - }, - "read-pkg": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", - "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", - "dev": true, - "requires": { - "load-json-file": "^4.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^3.0.0" - } - }, - "read-pkg-up": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-4.0.0.tgz", - "integrity": "sha512-6etQSH7nJGsK0RbG/2TeDzZFa8shjQ1um+SwQQ5cwKy0dhSXdOncEhb1CPpvQG4h7FyOV6EB6YlV0yJvZQNAkA==", - "dev": true, - "requires": { - "find-up": "^3.0.0", - "read-pkg": "^3.0.0" - } - } - } - }, - "text-hex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz", - "integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==", - "dev": true - }, - "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 - }, - "textextensions": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/textextensions/-/textextensions-2.4.0.tgz", - "integrity": "sha512-qftQXnX1DzpSV8EddtHIT0eDDEiBF8ywhFYR2lI9xrGtxqKN+CvLXhACeCIGbCpQfxxERbrkZEFb8cZcDKbVZA==", - "dev": true - }, - "tfunk": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/tfunk/-/tfunk-3.1.0.tgz", - "integrity": "sha1-OORBT8ZJd9h6/apy+sttKfgve1s=", - "dev": true, - "requires": { - "chalk": "^1.1.1", - "object-path": "^0.9.0" - } - }, - "thread-loader": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/thread-loader/-/thread-loader-2.1.2.tgz", - "integrity": "sha512-7xpuc9Ifg6WU+QYw/8uUqNdRwMD+N5gjwHKMqETrs96Qn+7BHwECpt2Brzr4HFlf4IAkZsayNhmGdbkBsTJ//w==", - "dev": true, - "requires": { - "loader-runner": "^2.3.1", - "loader-utils": "^1.1.0", - "neo-async": "^2.6.0" - } - }, - "throat": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/throat/-/throat-4.1.0.tgz", - "integrity": "sha1-iQN8vJLFarGJJua6TLsgDhVnKmo=", - "dev": true - }, - "through": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=" - }, - "through2": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", - "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", - "dev": true, - "requires": { - "readable-stream": "~2.3.6", - "xtend": "~4.0.1" - } - }, - "thunky": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.0.3.tgz", - "integrity": "sha512-YwT8pjmNcAXBZqrubu22P4FYsh2D4dxRmnWBOL8Jk8bUcRUtc5326kx32tuTmFDAZtLOGEVNl8POAR8j896Iow==", - "dev": true - }, - "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=", - "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" - } - }, - "timsort": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/timsort/-/timsort-0.3.0.tgz", - "integrity": "sha1-QFQRqOfmM5/mTbmiNN4R3DHgK9Q=", - "dev": true - }, - "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=", - "dev": true - }, - "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": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", - "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" - } - }, - "to-string-loader": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/to-string-loader/-/to-string-loader-1.1.5.tgz", - "integrity": "sha1-e3qheJG3u0lHp6Eb+wO1/enG5pU=", - "dev": true, - "requires": { - "loader-utils": "^0.2.16" - }, - "dependencies": { - "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 - }, - "json5": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", - "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=", - "dev": true - }, - "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" - } - } - } - }, - "topo": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/topo/-/topo-2.0.2.tgz", - "integrity": "sha1-zVYVdSU5BXwNwEkaYhw7xvvh0YI=", - "dev": true, - "requires": { - "hoek": "4.x.x" - } - }, - "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.5.0", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", - "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", - "dev": true, - "requires": { - "psl": "^1.1.28", - "punycode": "^2.1.1" - } - }, - "tr46": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz", - "integrity": "sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk=", - "dev": true, - "requires": { - "punycode": "^2.1.0" - } - }, - "tree-kill": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.1.tgz", - "integrity": "sha512-4hjqbObwlh2dLyW4tcz0Ymw0ggoaVDMveUB9w8kFSQScdRLo0gxO9J7WFcUBo+W3C1TLdFIEwNOWebgZZ0RH9Q==", - "dev": true - }, - "trim-newlines": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-2.0.0.tgz", - "integrity": "sha1-tAPQuRvlDDMd/EuC7s6yLD3hbSA=", - "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 - }, - "triple-beam": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.3.0.tgz", - "integrity": "sha512-XrHUvV5HpdLmIj4uVMxHggLbFSZYIn7HEWsqePZcI50pco+MPqJ50wMGY794X7AOOhxOBAjbkqfAbEe/QMp2Lw==", - "dev": true - }, - "ts-jest": { - "version": "23.1.4", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-23.1.4.tgz", - "integrity": "sha512-9rCSxbWfoZxxeXnSoEIzRNr9hDIQ8iEJAWmSRsWhDHDT8OeuGfURhJQUE8jtJlkyEygs6rngH8RYtHz9cfjmEA==", - "dev": true, - "requires": { - "closest-file-data": "^0.1.4", - "fs-extra": "6.0.1", - "json5": "^0.5.0", - "lodash": "^4.17.10" - }, - "dependencies": { - "fs-extra": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-6.0.1.tgz", - "integrity": "sha512-GnyIkKhhzXZUWFCaJzvyDLEEgDkPfb4/TPvJCJVuS8MWZgoSsErf++QpiAlDnKFcqhRlm+tIOcencCjyJE6ZCA==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "jsonfile": "^4.0.0", - "universalify": "^0.1.0" - } - }, - "json5": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", - "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=", - "dev": true - }, - "jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.6" - } - } - } - }, - "ts-loader": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-5.3.3.tgz", - "integrity": "sha512-KwF1SplmOJepnoZ4eRIloH/zXL195F51skt7reEsS6jvDqzgc/YSbz9b8E07GxIUwLXdcD4ssrJu6v8CwaTafA==", - "dev": true, - "requires": { - "chalk": "^2.3.0", - "enhanced-resolve": "^4.0.0", - "loader-utils": "^1.0.2", - "micromatch": "^3.1.4", - "semver": "^5.0.1" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "tslib": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz", - "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" - }, - "tslint": { - "version": "5.12.1", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.12.1.tgz", - "integrity": "sha512-sfodBHOucFg6egff8d1BvuofoOQ/nOeYNfbp7LDlKBcLNrL3lmS5zoiDGyOMdT7YsEXAwWpTdAHwOGOc8eRZAw==", - "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.27.2" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "tslint-config-prettier": { - "version": "1.18.0", - "resolved": "https://registry.npmjs.org/tslint-config-prettier/-/tslint-config-prettier-1.18.0.tgz", - "integrity": "sha512-xPw9PgNPLG3iKRxmK7DWr+Ea/SzrvfHtjFt5LBl61gk2UBG/DB9kCXRjv+xyIU1rUtnayLeMUVJBcMX8Z17nDg==", - "dev": true - }, - "tslint-loader": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/tslint-loader/-/tslint-loader-3.6.0.tgz", - "integrity": "sha512-Me9Qf/87BOfCY8uJJw+J7VMF4U8WiMXKLhKKKugMydF0xMhMOt9wo2mjYTNhwbF9H7SHh8PAIwRG8roisTNekQ==", - "dev": true, - "requires": { - "loader-utils": "^1.0.2", - "mkdirp": "^0.5.1", - "object-assign": "^4.1.1", - "rimraf": "^2.4.4", - "semver": "^5.3.0" - } - }, - "tsutils": { - "version": "2.29.0", - "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.29.0.tgz", - "integrity": "sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA==", - "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 - }, - "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": "3.2.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.2.4.tgz", - "integrity": "sha512-0RNDbSdEokBeEAkgNbxJ+BLwSManFy9TeXz8uW+48j/xhEXv1ePME60olyzw2XzUqUBNAYFeJadIqAgNqIACwg==", - "dev": true - }, - "ua-parser-js": { - "version": "0.7.17", - "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.17.tgz", - "integrity": "sha512-uRdSdu1oA1rncCQL7sCj8vSyZkgtL7faaw9Tc9rZ3mGgraQ7+Pdx7w5mnOSF3gw9ZNG6oc+KXfkon3bKuROm0g==", - "dev": true - }, - "uglify-js": { - "version": "3.4.10", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.4.10.tgz", - "integrity": "sha512-Y2VsbPVs0FIshJztycsO2SfPk7/KAF/T72qzv9u5EpQ4kB2hQoHlhNQTsNyy6ul7lQtqJN/AoWeS23OzEiEFxw==", - "dev": true, - "requires": { - "commander": "~2.19.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 - } - } - }, - "ultron": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ultron/-/ultron-1.1.1.tgz", - "integrity": "sha512-UIEXBNeYmKptWH6z8ZnqTeS8fV74zG0/eRU9VGkpzz+LIJNs8W/zM/L+7ctCkRrgbNnnR0xxw4bKOr0cW0N0Og==", - "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" - } - } - } - }, - "uniq": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz", - "integrity": "sha1-sxxa6CVIRKOoKBVBzisEuGWnNP8=", - "dev": true - }, - "uniqs": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/uniqs/-/uniqs-2.0.0.tgz", - "integrity": "sha1-/+3ks2slKQaW5uFl1KWe25mOawI=", - "dev": true - }, - "unique-filename": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz", - "integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==", - "dev": true, - "requires": { - "unique-slug": "^2.0.0" - } - }, - "unique-slug": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.1.tgz", - "integrity": "sha512-n9cU6+gITaVu7VGj1Z8feKMmfAjEAQGhwD9fE3zvpRRa0wEIx8ODYkVGfSc94M2OX00tUFV8wH3zYbm1I8mxFg==", - "dev": true, - "requires": { - "imurmurhash": "^0.1.4" - } - }, - "universalify": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", - "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", - "dev": true - }, - "unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", - "dev": true - }, - "unquote": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/unquote/-/unquote-1.1.1.tgz", - "integrity": "sha1-j97XMk7G6IoP+LkF58CYzcCG1UQ=", - "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 - } - } - }, - "untildify": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/untildify/-/untildify-3.0.3.tgz", - "integrity": "sha512-iSk/J8efr8uPT/Z4eSUywnqyrQU7DSdMfdqK4iWEaUVVmcP5JcnpRqmVMwcwcnmI1ATFNgC5V90u09tBynNFKA==", - "dev": true - }, - "upath": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/upath/-/upath-1.1.2.tgz", - "integrity": "sha512-kXpym8nmDmlCBr7nKdIx8P2jNBa+pBpIUFRnKJ4dr8htyYGJFokkr2ZvERRtUN+9SY+JqXouNgUPtv6JQva/2Q==", - "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": "4.2.2", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", - "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", - "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-parse": { - "version": "1.4.4", - "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.4.4.tgz", - "integrity": "sha512-/92DTTorg4JjktLNLe6GPS2/RvAd/RGr6LuktmWSMLEOa6rjnlrFXNgSbSmkNvCoL2T028A0a1JaJLzRMlFoHg==", - "dev": true, - "requires": { - "querystringify": "^2.0.0", - "requires-port": "^1.0.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=", - "dev": true, - "requires": { - "prepend-http": "^1.0.1" - } - }, - "url-to-options": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/url-to-options/-/url-to-options-1.0.1.tgz", - "integrity": "sha1-FQWgOiiaSMvXpDTvuu7FBV9WM6k=", - "dev": true - }, - "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 - }, - "util": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/util/-/util-0.11.1.tgz", - "integrity": "sha512-HShAsny+zS2TZfaXxD9tYj4HQGlBezXZMZuM/S5PKLLoZkShZiGk9o5CzukI1LVHZvjdvZ2Sj1aW/Ndn2NB/HQ==", - "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 - }, - "v8-compile-cache": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.0.2.tgz", - "integrity": "sha512-1wFuMUIM16MDJRCrpbpuEPTUGmM5QMUg0cr3KFwra2XgOgFcPGDQHDh3CszSCD2Zewc/dh/pamNEW8CbfDebUw==", - "dev": true - }, - "validate-npm-package-license": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", - "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", - "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 - }, - "vendors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/vendors/-/vendors-1.0.2.tgz", - "integrity": "sha512-w/hry/368nO21AN9QljsaIhb9ZiZtZARoVH5f3CsFbawdLdayCgKRPup7CggujvySMxx0I91NOyxdVENohprLQ==", - "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" - } - }, - "vinyl": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-1.2.0.tgz", - "integrity": "sha1-XIgDbPVl5d8FVYv8kR+GVt8hiIQ=", - "dev": true, - "requires": { - "clone": "^1.0.0", - "clone-stats": "^0.0.1", - "replace-ext": "0.0.1" - } - }, - "vinyl-file": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/vinyl-file/-/vinyl-file-2.0.0.tgz", - "integrity": "sha1-p+v1/779obfRjRQPyweyI++2dRo=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "pify": "^2.3.0", - "pinkie-promise": "^2.0.0", - "strip-bom": "^2.0.0", - "strip-bom-stream": "^2.0.0", - "vinyl": "^1.1.0" - }, - "dependencies": { - "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" - } - } - } - }, - "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" - } - }, - "w3c-hr-time": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.1.tgz", - "integrity": "sha1-gqwr/2PZUOqeMYmlimViX+3xkEU=", - "dev": true, - "requires": { - "browser-process-hrtime": "^0.1.2" - } - }, - "walker": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.7.tgz", - "integrity": "sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=", - "dev": true, - "requires": { - "makeerror": "1.0.x" - } - }, - "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" - } - }, - "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==", - "dev": true - }, - "webpack": { - "version": "4.29.3", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-4.29.3.tgz", - "integrity": "sha512-xPJvFeB+8tUflXFq+OgdpiSnsCD5EANyv56co5q8q8+YtEasn5Sj3kzY44mta+csCIEB0vneSxnuaHkOL2h94A==", - "dev": true, - "requires": { - "@webassemblyjs/ast": "1.7.11", - "@webassemblyjs/helper-module-context": "1.7.11", - "@webassemblyjs/wasm-edit": "1.7.11", - "@webassemblyjs/wasm-parser": "1.7.11", - "acorn": "^6.0.5", - "acorn-dynamic-import": "^4.0.0", - "ajv": "^6.1.0", - "ajv-keywords": "^3.1.0", - "chrome-trace-event": "^1.0.0", - "enhanced-resolve": "^4.1.0", - "eslint-scope": "^4.0.0", - "json-parse-better-errors": "^1.0.2", - "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": "^1.0.0", - "tapable": "^1.1.0", - "terser-webpack-plugin": "^1.1.0", - "watchpack": "^1.5.0", - "webpack-sources": "^1.3.0" - }, - "dependencies": { - "acorn": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz", - "integrity": "sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==", - "dev": true - } - } - }, - "webpack-cli": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-3.2.3.tgz", - "integrity": "sha512-Ik3SjV6uJtWIAN5jp5ZuBMWEAaP5E4V78XJ2nI+paFPh8v4HPSwo/myN0r29Xc/6ZKnd2IdrAlpSgNOu2CDQ6Q==", - "dev": true, - "requires": { - "chalk": "^2.4.1", - "cross-spawn": "^6.0.5", - "enhanced-resolve": "^4.1.0", - "findup-sync": "^2.0.0", - "global-modules": "^1.0.0", - "import-local": "^2.0.0", - "interpret": "^1.1.0", - "loader-utils": "^1.1.0", - "supports-color": "^5.5.0", - "v8-compile-cache": "^2.0.2", - "yargs": "^12.0.4" - }, - "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 - }, - "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" - } - }, - "camelcase": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.2.0.tgz", - "integrity": "sha512-IXFsBS2pC+X0j0N/GE7Dm7j3bsEBp+oTpb7F50dwEVX7rf3IgwO9XatnegTsDtniKCUtEJH4fSU6Asw7uoVLfQ==", - "dev": true - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "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" - } - }, - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "execa": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", - "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", - "dev": true, - "requires": { - "cross-spawn": "^6.0.0", - "get-stream": "^4.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" - } - }, - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "invert-kv": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", - "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==", - "dev": true - }, - "lcid": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz", - "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==", - "dev": true, - "requires": { - "invert-kv": "^2.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "mem": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/mem/-/mem-4.2.0.tgz", - "integrity": "sha512-5fJxa68urlY0Ir8ijatKa3eRz5lwXnRCTvo9+TbTGAuTFJOwpGcY0X05moBd0nW45965Njt4CDI2GFQoG8DvqA==", - "dev": true, - "requires": { - "map-age-cleaner": "^0.1.1", - "mimic-fn": "^2.0.0", - "p-is-promise": "^2.0.0" - } - }, - "mimic-fn": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.0.0.tgz", - "integrity": "sha512-jbex9Yd/3lmICXwYT6gA/j2mNQGU48wCh/VzRd+/Y/PjYQtlg1gLMdZqvu9s/xH7qKvngxRObl56XZR609IMbA==", - "dev": true - }, - "os-locale": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz", - "integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==", - "dev": true, - "requires": { - "execa": "^1.0.0", - "lcid": "^2.0.0", - "mem": "^4.0.0" - } - }, - "p-limit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", - "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.1.0.tgz", - "integrity": "sha512-H2RyIJ7+A3rjkwKC2l5GGtU4H1vkxKCAGsWasNVd0Set+6i4znxbWy6/j16YDPJDWxhsgZiKAstMEP8wCdSpjA==", - "dev": true - }, - "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" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "yargs": { - "version": "12.0.5", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.5.tgz", - "integrity": "sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw==", - "dev": true, - "requires": { - "cliui": "^4.0.0", - "decamelize": "^1.2.0", - "find-up": "^3.0.0", - "get-caller-file": "^1.0.1", - "os-locale": "^3.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 || ^4.0.0", - "yargs-parser": "^11.1.1" - } - }, - "yargs-parser": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-11.1.1.tgz", - "integrity": "sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ==", - "dev": true, - "requires": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" - } - } - } - }, - "webpack-dev-middleware": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-3.4.0.tgz", - "integrity": "sha512-Q9Iyc0X9dP9bAsYskAVJ/hmIZZQwf/3Sy4xCAZgL5cUkjZmUZLt4l5HpbST/Pdgjn3u6pE7u5OdGd1apgzRujA==", - "dev": true, - "requires": { - "memory-fs": "~0.4.1", - "mime": "^2.3.1", - "range-parser": "^1.0.3", - "webpack-log": "^2.0.0" - }, - "dependencies": { - "mime": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.0.tgz", - "integrity": "sha512-ikBcWwyqXQSHKtciCcctu9YfPbFYZ4+gbHEmE0Q8jzcTYQg5dHCr3g2wwAZjPoJfQVXZq6KXAjpXOTf5/cjT7w==", - "dev": true - } - } - }, - "webpack-dev-server": { - "version": "3.1.14", - "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-3.1.14.tgz", - "integrity": "sha512-mGXDgz5SlTxcF3hUpfC8hrQ11yhAttuUQWf1Wmb+6zo3x6rb7b9mIfuQvAPLdfDRCGRGvakBWHdHOa0I9p/EVQ==", - "dev": true, - "requires": { - "ansi-html": "0.0.7", - "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": "^2.0.0", - "internal-ip": "^3.0.1", - "ip": "^1.1.5", - "killable": "^1.0.0", - "loglevel": "^1.4.1", - "opn": "^5.1.0", - "portfinder": "^1.0.9", - "schema-utils": "^1.0.0", - "selfsigned": "^1.9.1", - "semver": "^5.6.0", - "serve-index": "^1.7.2", - "sockjs": "0.3.19", - "sockjs-client": "1.3.0", - "spdy": "^4.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^5.1.0", - "url": "^0.11.0", - "webpack-dev-middleware": "3.4.0", - "webpack-log": "^2.0.0", - "yargs": "12.0.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 - }, - "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" - } - } - } - }, - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "debug": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "decamelize": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-2.0.0.tgz", - "integrity": "sha512-Ikpp5scV3MSYxY39ymh45ZLEecsTdv/Xj2CaQfI8RLMuwi7XvjX9H/fhraiSuU+C5w5NTDu4ZU72xNiZnurBPg==", - "dev": true, - "requires": { - "xregexp": "4.0.0" - } - }, - "execa": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", - "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", - "dev": true, - "requires": { - "cross-spawn": "^6.0.0", - "get-stream": "^4.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" - } - }, - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "invert-kv": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", - "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==", - "dev": true - }, - "lcid": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz", - "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==", - "dev": true, - "requires": { - "invert-kv": "^2.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "mem": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/mem/-/mem-4.2.0.tgz", - "integrity": "sha512-5fJxa68urlY0Ir8ijatKa3eRz5lwXnRCTvo9+TbTGAuTFJOwpGcY0X05moBd0nW45965Njt4CDI2GFQoG8DvqA==", - "dev": true, - "requires": { - "map-age-cleaner": "^0.1.1", - "mimic-fn": "^2.0.0", - "p-is-promise": "^2.0.0" - } - }, - "mimic-fn": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.0.0.tgz", - "integrity": "sha512-jbex9Yd/3lmICXwYT6gA/j2mNQGU48wCh/VzRd+/Y/PjYQtlg1gLMdZqvu9s/xH7qKvngxRObl56XZR609IMbA==", - "dev": true - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - }, - "opn": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/opn/-/opn-5.5.0.tgz", - "integrity": "sha512-PqHpggC9bLV0VeWcdKhkpxY+3JTzetLSqTCWL/z/tFIbI6G8JCjondXklT1JinczLz2Xib62sSp0T/gKT4KksA==", - "dev": true, - "requires": { - "is-wsl": "^1.1.0" - } - }, - "os-locale": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz", - "integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==", - "dev": true, - "requires": { - "execa": "^1.0.0", - "lcid": "^2.0.0", - "mem": "^4.0.0" - } - }, - "p-limit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", - "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.1.0.tgz", - "integrity": "sha512-H2RyIJ7+A3rjkwKC2l5GGtU4H1vkxKCAGsWasNVd0Set+6i4znxbWy6/j16YDPJDWxhsgZiKAstMEP8wCdSpjA==", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "yargs": { - "version": "12.0.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.2.tgz", - "integrity": "sha512-e7SkEx6N6SIZ5c5H22RTZae61qtn3PYUE8JYbBFlK9sYmh3DMQ6E5ygtaG/2BW0JZi4WGgTR2IV5ChqlqrDGVQ==", - "dev": true, - "requires": { - "cliui": "^4.0.0", - "decamelize": "^2.0.0", - "find-up": "^3.0.0", - "get-caller-file": "^1.0.1", - "os-locale": "^3.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 || ^4.0.0", - "yargs-parser": "^10.1.0" - } - }, - "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" - } - } - } - }, - "webpack-log": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/webpack-log/-/webpack-log-2.0.0.tgz", - "integrity": "sha512-cX8G2vR/85UYG59FgkoMamwHUIkSSlV3bBMRsbxVXVUk2j6NleCKjQ/WE9eYg9WY4w25O9w8wKP4rzNZFmUcUg==", - "dev": true, - "requires": { - "ansi-colors": "^3.0.0", - "uuid": "^3.3.2" - } - }, - "webpack-merge": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-4.2.1.tgz", - "integrity": "sha512-4p8WQyS98bUJcCvFMbdGZyZmsKuWjWVnVHnAS3FFg0HDaRVrPbkivx2RYCre8UiemD67RsiFFLfn4JhLAin8Vw==", - "dev": true, - "requires": { - "lodash": "^4.17.5" - } - }, - "webpack-notifier": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/webpack-notifier/-/webpack-notifier-1.7.0.tgz", - "integrity": "sha512-L3UKrl500xk0VDYKkwQxy5/BPhBWsZ2xHsAx2Qe3dVKYUEk9+y690RcNTMIUcVOK2fRgK7KK3PA4ccOq1h+fTg==", - "dev": true, - "requires": { - "node-notifier": "^5.1.2", - "object-assign": "^4.1.0", - "strip-ansi": "^3.0.1" - } - }, - "webpack-sources": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.3.0.tgz", - "integrity": "sha512-OiVgSrbGu7NEnEvQJJgdSFPl2qWKkWq5lHMhgiToIiN9w34EBnjYzSYs+VbL5KoYiLNtFFa7BZIKxRED3I32pA==", - "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-visualizer-plugin": { - "version": "0.1.11", - "resolved": "https://registry.npmjs.org/webpack-visualizer-plugin/-/webpack-visualizer-plugin-0.1.11.tgz", - "integrity": "sha1-uHcK2GtPZSYSxosbeCJT+vn4o04=", - "dev": true, - "requires": { - "d3": "^3.5.6", - "mkdirp": "^0.5.1", - "react": "^0.14.0", - "react-dom": "^0.14.0" - } - }, - "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 - }, - "whatwg-encoding": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz", - "integrity": "sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==", - "dev": true, - "requires": { - "iconv-lite": "0.4.24" - } - }, - "whatwg-fetch": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-0.9.0.tgz", - "integrity": "sha1-DjaExsuZlbQ+/J3wPkw2XZX9nMA=", - "dev": true - }, - "whatwg-mimetype": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz", - "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", - "dev": true - }, - "whatwg-url": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-6.5.0.tgz", - "integrity": "sha512-rhRZRqx/TLJQWUpQ6bmrt2UV4f0HCQ463yQuONJqC6fO2VoEb1pTYddbe59SkYq87aoM5A3bdhMZiUiVws+fzQ==", - "dev": true, - "requires": { - "lodash.sortby": "^4.7.0", - "tr46": "^1.0.1", - "webidl-conversions": "^4.0.2" - } - }, - "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": "2.0.0", - "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", - "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", - "dev": true - }, - "win-release": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/win-release/-/win-release-1.1.1.tgz", - "integrity": "sha1-X6VeAr58qTTt/BJmVjLoSbcuUgk=", - "dev": true, - "requires": { - "semver": "^5.0.1" - } - }, - "window-size": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.2.0.tgz", - "integrity": "sha1-tDFbtCFKPXBY6+7okuE/ok2YsHU=", - "dev": true - }, - "winston": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/winston/-/winston-3.2.1.tgz", - "integrity": "sha512-zU6vgnS9dAWCEKg/QYigd6cgMVVNwyTzKs81XZtTFuRwJOcDdBg7AU0mXVyNbs7O5RH2zdv+BdNZUlx7mXPuOw==", - "dev": true, - "requires": { - "async": "^2.6.1", - "diagnostics": "^1.1.1", - "is-stream": "^1.1.0", - "logform": "^2.1.1", - "one-time": "0.0.4", - "readable-stream": "^3.1.1", - "stack-trace": "0.0.x", - "triple-beam": "^1.3.0", - "winston-transport": "^4.3.0" - }, - "dependencies": { - "async": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", - "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", - "dev": true, - "requires": { - "lodash": "^4.17.11" - } - }, - "readable-stream": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.2.0.tgz", - "integrity": "sha512-RV20kLjdmpZuTF1INEb9IA3L68Nmi+Ri7ppZqo78wj//Pn62fCoJyV9zalccNzDD/OuJpMG4f+pfMl8+L6QdGw==", - "dev": true, - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - } - } - }, - "winston-transport": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.3.0.tgz", - "integrity": "sha512-B2wPuwUi3vhzn/51Uukcao4dIduEiPOcOt9HJ3QeaXgkJ5Z7UwpBzxS4ZGNHtrxrUvTwemsQiSys0ihOf8Mp1A==", - "dev": true, - "requires": { - "readable-stream": "^2.3.6", - "triple-beam": "^1.2.0" - } - }, - "wordwrap": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz", - "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=", - "dev": true - }, - "workbox-background-sync": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-background-sync/-/workbox-background-sync-3.6.3.tgz", - "integrity": "sha512-ypLo0B6dces4gSpaslmDg5wuoUWrHHVJfFWwl1udvSylLdXvnrfhFfriCS42SNEe5lsZtcNZF27W/SMzBlva7Q==", - "dev": true, - "requires": { - "workbox-core": "^3.6.3" - } - }, - "workbox-broadcast-cache-update": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-broadcast-cache-update/-/workbox-broadcast-cache-update-3.6.3.tgz", - "integrity": "sha512-pJl4lbClQcvp0SyTiEw0zLSsVYE1RDlCPtpKnpMjxFtu8lCFTAEuVyzxp9w7GF4/b3P4h5nyQ+q7V9mIR7YzGg==", - "dev": true, - "requires": { - "workbox-core": "^3.6.3" - } - }, - "workbox-build": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-build/-/workbox-build-3.6.3.tgz", - "integrity": "sha512-w0clZ/pVjL8VXy6GfthefxpEXs0T8uiRuopZSFVQ8ovfbH6c6kUpEh6DcYwm/Y6dyWPiCucdyAZotgjz+nRz8g==", - "dev": true, - "requires": { - "babel-runtime": "^6.26.0", - "common-tags": "^1.4.0", - "fs-extra": "^4.0.2", - "glob": "^7.1.2", - "joi": "^11.1.1", - "lodash.template": "^4.4.0", - "pretty-bytes": "^4.0.2", - "stringify-object": "^3.2.2", - "strip-comments": "^1.0.2", - "workbox-background-sync": "^3.6.3", - "workbox-broadcast-cache-update": "^3.6.3", - "workbox-cache-expiration": "^3.6.3", - "workbox-cacheable-response": "^3.6.3", - "workbox-core": "^3.6.3", - "workbox-google-analytics": "^3.6.3", - "workbox-navigation-preload": "^3.6.3", - "workbox-precaching": "^3.6.3", - "workbox-range-requests": "^3.6.3", - "workbox-routing": "^3.6.3", - "workbox-strategies": "^3.6.3", - "workbox-streams": "^3.6.3", - "workbox-sw": "^3.6.3" - }, - "dependencies": { - "fs-extra": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-4.0.3.tgz", - "integrity": "sha512-q6rbdDd1o2mAnQreO7YADIxf/Whx4AHBiRf6d+/cVT8h44ss+lHgxf1FemcqDnQt9X3ct4McHr+JMGlYSsK7Cg==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "jsonfile": "^4.0.0", - "universalify": "^0.1.0" - } - }, - "jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.6" - } - }, - "pretty-bytes": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-4.0.2.tgz", - "integrity": "sha1-sr+C5zUNZcbDOqlaqlpPYyf2HNk=", - "dev": true - } - } - }, - "workbox-cache-expiration": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-cache-expiration/-/workbox-cache-expiration-3.6.3.tgz", - "integrity": "sha512-+ECNph/6doYx89oopO/UolYdDmQtGUgo8KCgluwBF/RieyA1ZOFKfrSiNjztxOrGJoyBB7raTIOlEEwZ1LaHoA==", - "dev": true, - "requires": { - "workbox-core": "^3.6.3" - } - }, - "workbox-cacheable-response": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-cacheable-response/-/workbox-cacheable-response-3.6.3.tgz", - "integrity": "sha512-QpmbGA9SLcA7fklBLm06C4zFg577Dt8u3QgLM0eMnnbaVv3rhm4vbmDpBkyTqvgK/Ly8MBDQzlXDtUCswQwqqg==", - "dev": true, - "requires": { - "workbox-core": "^3.6.3" - } - }, - "workbox-core": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-core/-/workbox-core-3.6.3.tgz", - "integrity": "sha512-cx9cx0nscPkIWs8Pt98HGrS9/aORuUcSkWjG25GqNWdvD/pSe7/5Oh3BKs0fC+rUshCiyLbxW54q0hA+GqZeSQ==", - "dev": true - }, - "workbox-google-analytics": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-google-analytics/-/workbox-google-analytics-3.6.3.tgz", - "integrity": "sha512-RQBUo/6SXtIaQTRFj4RQZ9e1gAl7D8oS5S+Hi173Kk70/BgJjzPwXpC5A249Jv5YfkCOLMQCeF9A27BiD0b0ig==", - "dev": true, - "requires": { - "workbox-background-sync": "^3.6.3", - "workbox-core": "^3.6.3", - "workbox-routing": "^3.6.3", - "workbox-strategies": "^3.6.3" - } - }, - "workbox-navigation-preload": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-navigation-preload/-/workbox-navigation-preload-3.6.3.tgz", - "integrity": "sha512-dd26xTX16DUu0i+MhqZK/jQXgfIitu0yATM4jhRXEmpMqQ4MxEeNvl2CgjDMOHBnCVMax+CFZQWwxMx/X/PqCw==", - "dev": true, - "requires": { - "workbox-core": "^3.6.3" - } - }, - "workbox-precaching": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-precaching/-/workbox-precaching-3.6.3.tgz", - "integrity": "sha512-aBqT66BuMFviPTW6IpccZZHzpA8xzvZU2OM1AdhmSlYDXOJyb1+Z6blVD7z2Q8VNtV1UVwQIdImIX+hH3C3PIw==", - "dev": true, - "requires": { - "workbox-core": "^3.6.3" - } - }, - "workbox-range-requests": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-range-requests/-/workbox-range-requests-3.6.3.tgz", - "integrity": "sha512-R+yLWQy7D9aRF9yJ3QzwYnGFnGDhMUij4jVBUVtkl67oaVoP1ymZ81AfCmfZro2kpPRI+vmNMfxxW531cqdx8A==", - "dev": true, - "requires": { - "workbox-core": "^3.6.3" - } - }, - "workbox-routing": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-routing/-/workbox-routing-3.6.3.tgz", - "integrity": "sha512-bX20i95OKXXQovXhFOViOK63HYmXvsIwZXKWbSpVeKToxMrp0G/6LZXnhg82ijj/S5yhKNRf9LeGDzaqxzAwMQ==", - "dev": true, - "requires": { - "workbox-core": "^3.6.3" - } - }, - "workbox-strategies": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-strategies/-/workbox-strategies-3.6.3.tgz", - "integrity": "sha512-Pg5eulqeKet2y8j73Yw6xTgLdElktcWExGkzDVCGqfV9JCvnGuEpz5eVsCIK70+k4oJcBCin9qEg3g3CwEIH3g==", - "dev": true, - "requires": { - "workbox-core": "^3.6.3" - } - }, - "workbox-streams": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-streams/-/workbox-streams-3.6.3.tgz", - "integrity": "sha512-rqDuS4duj+3aZUYI1LsrD2t9hHOjwPqnUIfrXSOxSVjVn83W2MisDF2Bj+dFUZv4GalL9xqErcFW++9gH+Z27w==", - "dev": true, - "requires": { - "workbox-core": "^3.6.3" - } - }, - "workbox-sw": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-sw/-/workbox-sw-3.6.3.tgz", - "integrity": "sha512-IQOUi+RLhvYCiv80RP23KBW/NTtIvzvjex28B8NW1jOm+iV4VIu3VXKXTA6er5/wjjuhmtB28qEAUqADLAyOSg==", - "dev": true - }, - "workbox-webpack-plugin": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/workbox-webpack-plugin/-/workbox-webpack-plugin-3.6.3.tgz", - "integrity": "sha512-RwmKjc7HFHUFHoOlKoZUq9349u0QN3F8W5tZZU0vc1qsBZDINWXRiIBCAKvo/Njgay5sWz7z4I2adnyTo97qIQ==", - "dev": true, - "requires": { - "babel-runtime": "^6.26.0", - "json-stable-stringify": "^1.0.1", - "workbox-build": "^3.6.3" - } - }, - "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" - }, - "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=", - "dev": true, - "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=", - "dev": true, - "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=", - "dev": true - }, - "write-file-atomic": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.2.tgz", - "integrity": "sha512-s0b6vB3xIVRLWywa6X9TOMA7k9zio0TMOsl9ZnDkliA/cfJlpHXAscj0gbHVJiTdIuAYpIyqS5GW91fqm6gG5g==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.11", - "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.2" - } - }, - "write-file-webpack-plugin": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/write-file-webpack-plugin/-/write-file-webpack-plugin-4.5.0.tgz", - "integrity": "sha512-k46VeERtaezbmjpDcMWATjKUWBrVe/ZEEm0cyvUm8FFP8A/r+dw5x3psRvkUOhqh9bqBLUlGYYbtr6luI+HeAg==", - "dev": true, - "requires": { - "chalk": "^2.4.0", - "debug": "^3.1.0", - "filesize": "^3.6.1", - "lodash": "^4.17.5", - "mkdirp": "^0.5.1", - "moment": "^2.22.1", - "write-file-atomic": "^2.3.0" - }, - "dependencies": { - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "debug": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "ws": { - "version": "6.1.4", - "resolved": "https://registry.npmjs.org/ws/-/ws-6.1.4.tgz", - "integrity": "sha512-eqZfL+NE/YQc1/ZynhojeV8q+H050oR8AZ2uIev7RU10svA9ZnJUddHcOUZTJLinZ9yEfdA2kSATS2qZK5fhJA==", - "dev": true, - "requires": { - "async-limiter": "~1.0.0" - } - }, - "xml": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/xml/-/xml-1.0.1.tgz", - "integrity": "sha1-eLpyAgApxbyHuKgaPPzXS0ovweU=", - "dev": true - }, - "xml-name-validator": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz", - "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", - "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" - } - }, - "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.5", - "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-1.5.5.tgz", - "integrity": "sha1-wodrBhaKrcQOV9l+gRkayPQ5iz4=", - "dev": true - }, - "xregexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/xregexp/-/xregexp-4.0.0.tgz", - "integrity": "sha512-PHyM+sQouu7xspQQwELlGwwd05mXUFqwFYfqPO0cC7x4fxyHnnuetmQr6CjJiafIDoH4MogHb9dOoJzR/Y4rFg==", - "dev": true - }, - "xtend": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", - "dev": true - }, - "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": "3.0.3", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.0.3.tgz", - "integrity": "sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==", - "dev": true - }, - "yargs": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-9.0.1.tgz", - "integrity": "sha1-UqzCP+7Kw0BCB47njAwAf1CF20w=", - "dev": true, - "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" - }, - "dependencies": { - "y18n": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz", - "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=", - "dev": true - } - } - }, - "yargs-parser": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-7.0.0.tgz", - "integrity": "sha1-jQrELxbqVd69MyyvTEA4s+P139k=", - "dev": true, - "requires": { - "camelcase": "^4.1.0" - } - }, - "yeast": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/yeast/-/yeast-0.1.2.tgz", - "integrity": "sha1-AI4G2AlDIMNy28L47XagymyKxBk=", - "dev": true - }, - "yeoman-environment": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/yeoman-environment/-/yeoman-environment-2.3.0.tgz", - "integrity": "sha512-PHSAkVOqYdcR+C+Uht1SGC4eVD/9OhygYFkYaI66xF8vKIeS1RNYay+umj2ZrQeJ50tF5Q/RSO6qGDz9y3Ifug==", - "dev": true, - "requires": { - "chalk": "^2.1.0", - "cross-spawn": "^6.0.5", - "debug": "^3.1.0", - "diff": "^3.3.1", - "escape-string-regexp": "^1.0.2", - "globby": "^8.0.1", - "grouped-queue": "^0.3.3", - "inquirer": "^5.2.0", - "is-scoped": "^1.0.0", - "lodash": "^4.17.10", - "log-symbols": "^2.1.0", - "mem-fs": "^1.1.0", - "strip-ansi": "^4.0.0", - "text-table": "^0.2.0", - "untildify": "^3.0.2" - }, - "dependencies": { - "ansi-escapes": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", - "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==", - "dev": true - }, - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", - "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" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "debug": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "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" - } - }, - "globby": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/globby/-/globby-8.0.2.tgz", - "integrity": "sha512-yTzMmKygLp8RUpG1Ymu2VXPSJQZjNAZPD4ywgYEaG7e4tBJeUQBO8OpXrf1RCNcEs5alsoJYPAMiIHP0cmeC7w==", - "dev": true, - "requires": { - "array-union": "^1.0.1", - "dir-glob": "2.0.0", - "fast-glob": "^2.0.2", - "glob": "^7.1.2", - "ignore": "^3.3.5", - "pify": "^3.0.0", - "slash": "^1.0.0" - } - }, - "inquirer": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-5.2.0.tgz", - "integrity": "sha512-E9BmnJbAKLPGonz0HeWHtbKf+EeSP93paWO3ZYoUpq/aowXvYGjjCSuashhXPpzbArIjBbji39THkxTz9ZeEUQ==", - "dev": true, - "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", - "cli-cursor": "^2.1.0", - "cli-width": "^2.0.0", - "external-editor": "^2.1.0", - "figures": "^2.0.0", - "lodash": "^4.3.0", - "mute-stream": "0.0.7", - "run-async": "^2.2.0", - "rxjs": "^5.5.2", - "string-width": "^2.1.0", - "strip-ansi": "^4.0.0", - "through": "^2.3.6" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "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" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - }, - "rxjs": { - "version": "5.5.12", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-5.5.12.tgz", - "integrity": "sha512-xx2itnL5sBbqeeiVgNPVuQQ1nC8Jp2WfNJhXWHmElW9YmrpS9UVnNzhP3EH3HFqexO5Tlp8GhYY+WEcqcVMvGw==", - "dev": true, - "requires": { - "symbol-observable": "1.0.1" - } - }, - "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" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "symbol-observable": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.0.1.tgz", - "integrity": "sha1-g0D8RwLDEi310iKI+IKD9RPT/dQ=", - "dev": true - } - } - }, - "yeoman-generator": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/yeoman-generator/-/yeoman-generator-3.0.0.tgz", - "integrity": "sha512-aHsNXzkdgAoakZTZsDX7T56wYWYd1O5E/GBIFAVMJLH7TKRr+1MiEJszZQbbCSA+J+lpT743/8L88j35yNdTLQ==", - "dev": true, - "requires": { - "async": "^2.6.0", - "chalk": "^2.3.0", - "cli-table": "^0.3.1", - "cross-spawn": "^6.0.5", - "dargs": "^6.0.0", - "dateformat": "^3.0.3", - "debug": "^3.1.0", - "detect-conflict": "^1.0.0", - "error": "^7.0.2", - "find-up": "^3.0.0", - "github-username": "^4.0.0", - "istextorbinary": "^2.2.1", - "lodash": "^4.17.10", - "make-dir": "^1.1.0", - "mem-fs-editor": "^5.0.0", - "minimist": "^1.2.0", - "pretty-bytes": "^5.1.0", - "read-chunk": "^2.1.0", - "read-pkg-up": "^4.0.0", - "rimraf": "^2.6.2", - "run-async": "^2.0.0", - "shelljs": "^0.8.0", - "text-table": "^0.2.0", - "through2": "^2.0.0", - "yeoman-environment": "^2.0.5" - }, - "dependencies": { - "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" - } - }, - "async": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", - "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", - "dev": true, - "requires": { - "lodash": "^4.17.11" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "debug": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "load-json-file": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", - "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "parse-json": "^4.0.0", - "pify": "^3.0.0", - "strip-bom": "^3.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - }, - "p-limit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", - "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.1.0.tgz", - "integrity": "sha512-H2RyIJ7+A3rjkwKC2l5GGtU4H1vkxKCAGsWasNVd0Set+6i4znxbWy6/j16YDPJDWxhsgZiKAstMEP8wCdSpjA==", - "dev": true - }, - "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" - } - }, - "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" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - }, - "read-pkg": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", - "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", - "dev": true, - "requires": { - "load-json-file": "^4.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^3.0.0" - } - }, - "read-pkg-up": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-4.0.0.tgz", - "integrity": "sha512-6etQSH7nJGsK0RbG/2TeDzZFa8shjQ1um+SwQQ5cwKy0dhSXdOncEhb1CPpvQG4h7FyOV6EB6YlV0yJvZQNAkA==", - "dev": true, - "requires": { - "find-up": "^3.0.0", - "read-pkg": "^3.0.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "yup": { - "version": "0.26.10", - "resolved": "https://registry.npmjs.org/yup/-/yup-0.26.10.tgz", - "integrity": "sha512-keuNEbNSnsOTOuGCt3UJW69jDE3O4P+UHAakO7vSeFMnjaitcmlbij/a3oNb9g1Y1KvSKH/7O1R2PQ4m4TRylw==", - "dev": true, - "requires": { - "@babel/runtime": "7.0.0", - "fn-name": "~2.0.1", - "lodash": "^4.17.10", - "property-expr": "^1.5.0", - "synchronous-promise": "^2.0.5", - "toposort": "^2.0.2" - }, - "dependencies": { - "toposort": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/toposort/-/toposort-2.0.2.tgz", - "integrity": "sha1-riF2gXXRVZ1IvvNUILL0li8JwzA=", - "dev": true - } - } - }, - "zone.js": { - "version": "0.8.29", - "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.8.29.tgz", - "integrity": "sha512-mla2acNCMkWXBD+c+yeUrBUrzOxYMNFdQ6FGfigGGtEVBPJx07BQeJekjt9DmH1FtZek4E9rE1eRR9qQpxACOQ==" - } - } -} diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml index 60fc1acf92..233765e0f3 100644 --- a/jhipster-5/bookstore-monolith/pom.xml +++ b/jhipster-5/bookstore-monolith/pom.xml @@ -8,6 +8,12 @@ war Bookstore + + jhipster-5 + com.baeldung.jhipster + 1.0.0-SNAPSHOT + + @@ -976,7 +982,7 @@ com.github.eirslett - frontend-maven-plugin + frontend-maven-plugin ${frontend-maven-plugin.version} install-node-and-npm diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTest.java deleted file mode 100644 index 670042d2df..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTest.java +++ /dev/null @@ -1,189 +0,0 @@ -package com.baeldung.jhipster5.config; - -import io.github.jhipster.config.JHipsterConstants; -import io.github.jhipster.config.JHipsterProperties; -import io.github.jhipster.web.filter.CachingHttpHeadersFilter; -import io.undertow.Undertow; -import io.undertow.Undertow.Builder; -import io.undertow.UndertowOptions; -import org.apache.commons.io.FilenameUtils; - -import org.h2.server.web.WebServlet; -import org.junit.Before; -import org.junit.Test; -import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.mock.env.MockEnvironment; -import org.springframework.mock.web.MockServletContext; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.xnio.OptionMap; - -import javax.servlet.*; -import java.util.*; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * Unit tests for the WebConfigurer class. - * - * @see WebConfigurer - */ -public class WebConfigurerTest { - - private WebConfigurer webConfigurer; - - private MockServletContext servletContext; - - private MockEnvironment env; - - private JHipsterProperties props; - - @Before - public void setup() { - servletContext = spy(new MockServletContext()); - doReturn(mock(FilterRegistration.Dynamic.class)) - .when(servletContext).addFilter(anyString(), any(Filter.class)); - doReturn(mock(ServletRegistration.Dynamic.class)) - .when(servletContext).addServlet(anyString(), any(Servlet.class)); - - env = new MockEnvironment(); - props = new JHipsterProperties(); - - webConfigurer = new WebConfigurer(env, props); - } - - @Test - public void testStartUpProdServletContext() throws ServletException { - env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); - webConfigurer.onStartup(servletContext); - - verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class)); - verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); - } - - @Test - public void testStartUpDevServletContext() throws ServletException { - env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); - webConfigurer.onStartup(servletContext); - - verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class)); - verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); - } - - @Test - public void testCustomizeServletContainer() { - env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); - UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); - webConfigurer.customize(container); - assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); - assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); - assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); - if (container.getDocumentRoot() != null) { - assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www")); - } - - Builder builder = Undertow.builder(); - container.getBuilderCustomizers().forEach(c -> c.customize(builder)); - OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); - assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); - } - - @Test - public void testUndertowHttp2Enabled() { - props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0); - UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); - webConfigurer.customize(container); - Builder builder = Undertow.builder(); - container.getBuilderCustomizers().forEach(c -> c.customize(builder)); - OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); - assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue(); - } - - @Test - public void testCorsFilterOnApiPath() throws Exception { - props.getCors().setAllowedOrigins(Collections.singletonList("*")); - props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); - props.getCors().setAllowedHeaders(Collections.singletonList("*")); - props.getCors().setMaxAge(1800L); - props.getCors().setAllowCredentials(true); - - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); - - mockMvc.perform( - options("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) - .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) - .andExpect(header().string(HttpHeaders.VARY, "Origin")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); - - mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); - } - - @Test - public void testCorsFilterOnOtherPath() throws Exception { - props.getCors().setAllowedOrigins(Collections.singletonList("*")); - props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); - props.getCors().setAllowedHeaders(Collections.singletonList("*")); - props.getCors().setMaxAge(1800L); - props.getCors().setAllowCredentials(true); - - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); - - mockMvc.perform( - get("/test/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - } - - @Test - public void testCorsFilterDeactivated() throws Exception { - props.getCors().setAllowedOrigins(null); - - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); - - mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - } - - @Test - public void testCorsFilterDeactivated2() throws Exception { - props.getCors().setAllowedOrigins(new ArrayList<>()); - - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); - - mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - } -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTestController.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTestController.java deleted file mode 100644 index c19b28ea16..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerTestController.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.jhipster5.config; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class WebConfigurerTestController { - - @GetMapping("/api/test-cors") - public void testCorsOnApiPath() { - } - - @GetMapping("/test/test-cors") - public void testCorsOnOtherPath() { - } -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTest.java new file mode 100644 index 0000000000..764d6b3587 --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTest.java @@ -0,0 +1,189 @@ +package com.baeldung.jhipster5.config; + +import io.github.jhipster.config.JHipsterConstants; +import io.github.jhipster.config.JHipsterProperties; +import io.github.jhipster.web.filter.CachingHttpHeadersFilter; +import io.undertow.Undertow; +import io.undertow.Undertow.Builder; +import io.undertow.UndertowOptions; +import org.apache.commons.io.FilenameUtils; + +import org.h2.server.web.WebServlet; +import org.junit.Before; +import org.junit.Test; +import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.mock.web.MockServletContext; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.xnio.OptionMap; + +import javax.servlet.*; +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Unit tests for the WebConfigurer class. + * + * @see WebConfigurer + */ +public class WebConfigurerUnitTest { + + private WebConfigurer webConfigurer; + + private MockServletContext servletContext; + + private MockEnvironment env; + + private JHipsterProperties props; + + @Before + public void setup() { + servletContext = spy(new MockServletContext()); + doReturn(mock(FilterRegistration.Dynamic.class)) + .when(servletContext).addFilter(anyString(), any(Filter.class)); + doReturn(mock(ServletRegistration.Dynamic.class)) + .when(servletContext).addServlet(anyString(), any(Servlet.class)); + + env = new MockEnvironment(); + props = new JHipsterProperties(); + + webConfigurer = new WebConfigurer(env, props); + } + + @Test + public void testStartUpProdServletContext() throws ServletException { + env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); + webConfigurer.onStartup(servletContext); + + verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class)); + verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); + } + + @Test + public void testStartUpDevServletContext() throws ServletException { + env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); + webConfigurer.onStartup(servletContext); + + verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class)); + verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); + } + + @Test + public void testCustomizeServletContainer() { + env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); + UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); + webConfigurer.customize(container); + assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); + assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); + assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); + if (container.getDocumentRoot() != null) { + assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www")); + } + + Builder builder = Undertow.builder(); + container.getBuilderCustomizers().forEach(c -> c.customize(builder)); + OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); + assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); + } + + @Test + public void testUndertowHttp2Enabled() { + props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0); + UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); + webConfigurer.customize(container); + Builder builder = Undertow.builder(); + container.getBuilderCustomizers().forEach(c -> c.customize(builder)); + OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); + assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue(); + } + + @Test + public void testCorsFilterOnApiPath() throws Exception { + props.getCors().setAllowedOrigins(Collections.singletonList("*")); + props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); + props.getCors().setAllowedHeaders(Collections.singletonList("*")); + props.getCors().setMaxAge(1800L); + props.getCors().setAllowCredentials(true); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerUnitTestController()) + .addFilters(webConfigurer.corsFilter()) + .build(); + + mockMvc.perform( + options("/api/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) + .andExpect(header().string(HttpHeaders.VARY, "Origin")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); + + mockMvc.perform( + get("/api/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); + } + + @Test + public void testCorsFilterOnOtherPath() throws Exception { + props.getCors().setAllowedOrigins(Collections.singletonList("*")); + props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); + props.getCors().setAllowedHeaders(Collections.singletonList("*")); + props.getCors().setMaxAge(1800L); + props.getCors().setAllowCredentials(true); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerUnitTestController()) + .addFilters(webConfigurer.corsFilter()) + .build(); + + mockMvc.perform( + get("/test/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + } + + @Test + public void testCorsFilterDeactivated() throws Exception { + props.getCors().setAllowedOrigins(null); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerUnitTestController()) + .addFilters(webConfigurer.corsFilter()) + .build(); + + mockMvc.perform( + get("/api/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + } + + @Test + public void testCorsFilterDeactivated2() throws Exception { + props.getCors().setAllowedOrigins(new ArrayList<>()); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerUnitTestController()) + .addFilters(webConfigurer.corsFilter()) + .build(); + + mockMvc.perform( + get("/api/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTestController.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTestController.java new file mode 100644 index 0000000000..ee72e1c80e --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTestController.java @@ -0,0 +1,16 @@ +package com.baeldung.jhipster5.config; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class WebConfigurerUnitTestController { + + @GetMapping("/api/test-cors") + public void testCorsOnApiPath() { + } + + @GetMapping("/test/test-cors") + public void testCorsOnOtherPath() { + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/timezone/HibernateTimeZoneIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/timezone/HibernateTimeZoneIntegrationTest.java new file mode 100644 index 0000000000..fba77e037e --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/timezone/HibernateTimeZoneIntegrationTest.java @@ -0,0 +1,176 @@ +package com.baeldung.jhipster5.config.timezone; + +import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster5.repository.timezone.DateTimeWrapper; +import com.baeldung.jhipster5.repository.timezone.DateTimeWrapperRepository; +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.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.support.rowset.SqlRowSet; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import java.time.*; +import java.time.format.DateTimeFormatter; + +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests for the UTC Hibernate configuration. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +public class HibernateTimeZoneIntegrationTest { + + @Autowired + private DateTimeWrapperRepository dateTimeWrapperRepository; + @Autowired + private JdbcTemplate jdbcTemplate; + + private DateTimeWrapper dateTimeWrapper; + private DateTimeFormatter dateTimeFormatter; + private DateTimeFormatter timeFormatter; + private DateTimeFormatter dateFormatter; + + @Before + public void setup() { + dateTimeWrapper = new DateTimeWrapper(); + dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:50:00.0Z")); + dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:50:00.0")); + dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z")); + dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:30:00.0Z")); + dateTimeWrapper.setLocalTime(LocalTime.parse("14:30:00")); + dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:30:00+02:00")); + dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10")); + + dateTimeFormatter = DateTimeFormatter + .ofPattern("yyyy-MM-dd HH:mm:ss.S") + .withZone(ZoneId.of("UTC")); + + timeFormatter = DateTimeFormatter + .ofPattern("HH:mm:ss") + .withZone(ZoneId.of("UTC")); + + dateFormatter = DateTimeFormatter + .ofPattern("yyyy-MM-dd"); + } + + @Test + @Transactional + public void storeInstantWithUtcConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("instant", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant()); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeLocalDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getLocalDateTime() + .atZone(ZoneId.systemDefault()) + .format(dateTimeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeOffsetDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getOffsetDateTime() + .format(dateTimeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeZoneDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getZonedDateTime() + .format(dateTimeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeLocalTimeWithUtcConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getLocalTime() + .atDate(LocalDate.of(1970, Month.JANUARY, 1)) + .atZone(ZoneId.systemDefault()) + .format(timeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeOffsetTimeWithUtcConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("offset_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getOffsetTime() + .toLocalTime() + .atDate(LocalDate.of(1970, Month.JANUARY, 1)) + .atZone(ZoneId.systemDefault()) + .format(timeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeLocalDateWithUtcConfigShouldBeStoredWithoutTransformation() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_date", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getLocalDate() + .format(dateFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + private String generateSqlRequest(String fieldName, long id) { + return format("SELECT %s FROM jhi_date_time_wrapper where id=%d", fieldName, id); + } + + private void assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(SqlRowSet sqlRowSet, String expectedValue) { + while (sqlRowSet.next()) { + String dbValue = sqlRowSet.getString(1); + + assertThat(dbValue).isNotNull(); + assertThat(dbValue).isEqualTo(expectedValue); + } + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/timezone/HibernateTimeZoneTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/timezone/HibernateTimeZoneTest.java deleted file mode 100644 index 9027606e67..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/timezone/HibernateTimeZoneTest.java +++ /dev/null @@ -1,176 +0,0 @@ -package com.baeldung.jhipster5.config.timezone; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.repository.timezone.DateTimeWrapper; -import com.baeldung.jhipster5.repository.timezone.DateTimeWrapperRepository; -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.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.support.rowset.SqlRowSet; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import java.time.*; -import java.time.format.DateTimeFormatter; - -import static java.lang.String.format; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for the UTC Hibernate configuration. - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -public class HibernateTimeZoneTest { - - @Autowired - private DateTimeWrapperRepository dateTimeWrapperRepository; - @Autowired - private JdbcTemplate jdbcTemplate; - - private DateTimeWrapper dateTimeWrapper; - private DateTimeFormatter dateTimeFormatter; - private DateTimeFormatter timeFormatter; - private DateTimeFormatter dateFormatter; - - @Before - public void setup() { - dateTimeWrapper = new DateTimeWrapper(); - dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:50:00.0Z")); - dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:50:00.0")); - dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z")); - dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:30:00.0Z")); - dateTimeWrapper.setLocalTime(LocalTime.parse("14:30:00")); - dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:30:00+02:00")); - dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10")); - - dateTimeFormatter = DateTimeFormatter - .ofPattern("yyyy-MM-dd HH:mm:ss.S") - .withZone(ZoneId.of("UTC")); - - timeFormatter = DateTimeFormatter - .ofPattern("HH:mm:ss") - .withZone(ZoneId.of("UTC")); - - dateFormatter = DateTimeFormatter - .ofPattern("yyyy-MM-dd"); - } - - @Test - @Transactional - public void storeInstantWithUtcConfigShouldBeStoredOnGMTTimeZone() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("instant", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant()); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeLocalDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getLocalDateTime() - .atZone(ZoneId.systemDefault()) - .format(dateTimeFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeOffsetDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getOffsetDateTime() - .format(dateTimeFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeZoneDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getZonedDateTime() - .format(dateTimeFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeLocalTimeWithUtcConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("local_time", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getLocalTime() - .atDate(LocalDate.of(1970, Month.JANUARY, 1)) - .atZone(ZoneId.systemDefault()) - .format(timeFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeOffsetTimeWithUtcConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("offset_time", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getOffsetTime() - .toLocalTime() - .atDate(LocalDate.of(1970, Month.JANUARY, 1)) - .atZone(ZoneId.systemDefault()) - .format(timeFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - @Test - @Transactional - public void storeLocalDateWithUtcConfigShouldBeStoredWithoutTransformation() { - dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); - - String request = generateSqlRequest("local_date", dateTimeWrapper.getId()); - SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); - String expectedValue = dateTimeWrapper - .getLocalDate() - .format(dateFormatter); - - assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); - } - - private String generateSqlRequest(String fieldName, long id) { - return format("SELECT %s FROM jhi_date_time_wrapper where id=%d", fieldName, id); - } - - private void assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(SqlRowSet sqlRowSet, String expectedValue) { - while (sqlRowSet.next()) { - String dbValue = sqlRowSet.getString(1); - - assertThat(dbValue).isNotNull(); - assertThat(dbValue).isEqualTo(expectedValue); - } - } -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntTest.java deleted file mode 100644 index eaf5c07504..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntTest.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.baeldung.jhipster5.repository; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.config.Constants; -import com.baeldung.jhipster5.config.audit.AuditEventConverter; -import com.baeldung.jhipster5.domain.PersistentAuditEvent; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.audit.AuditEvent; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpSession; -import org.springframework.security.web.authentication.WebAuthenticationDetails; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import javax.servlet.http.HttpSession; -import java.time.Instant; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; -import static com.baeldung.jhipster5.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; - -/** - * Test class for the CustomAuditEventRepository class. - * - * @see CustomAuditEventRepository - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -@Transactional -public class CustomAuditEventRepositoryIntTest { - - @Autowired - private PersistenceAuditEventRepository persistenceAuditEventRepository; - - @Autowired - private AuditEventConverter auditEventConverter; - - private CustomAuditEventRepository customAuditEventRepository; - - private PersistentAuditEvent testUserEvent; - - private PersistentAuditEvent testOtherUserEvent; - - private PersistentAuditEvent testOldUserEvent; - - @Before - public void setup() { - customAuditEventRepository = new CustomAuditEventRepository(persistenceAuditEventRepository, auditEventConverter); - persistenceAuditEventRepository.deleteAll(); - Instant oneHourAgo = Instant.now().minusSeconds(3600); - - testUserEvent = new PersistentAuditEvent(); - testUserEvent.setPrincipal("test-user"); - testUserEvent.setAuditEventType("test-type"); - testUserEvent.setAuditEventDate(oneHourAgo); - Map data = new HashMap<>(); - data.put("test-key", "test-value"); - testUserEvent.setData(data); - - testOldUserEvent = new PersistentAuditEvent(); - testOldUserEvent.setPrincipal("test-user"); - testOldUserEvent.setAuditEventType("test-type"); - testOldUserEvent.setAuditEventDate(oneHourAgo.minusSeconds(10000)); - - testOtherUserEvent = new PersistentAuditEvent(); - testOtherUserEvent.setPrincipal("other-test-user"); - testOtherUserEvent.setAuditEventType("test-type"); - testOtherUserEvent.setAuditEventDate(oneHourAgo); - } - - @Test - public void addAuditEvent() { - Map data = new HashMap<>(); - data.put("test-key", "test-value"); - AuditEvent event = new AuditEvent("test-user", "test-type", data); - customAuditEventRepository.add(event); - List persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(1); - PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); - assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); - assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); - assertThat(persistentAuditEvent.getData()).containsKey("test-key"); - assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("test-value"); - assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp()); - } - - @Test - public void addAuditEventTruncateLargeData() { - Map data = new HashMap<>(); - StringBuilder largeData = new StringBuilder(); - for (int i = 0; i < EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) { - largeData.append("a"); - } - data.put("test-key", largeData); - AuditEvent event = new AuditEvent("test-user", "test-type", data); - customAuditEventRepository.add(event); - List persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(1); - PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); - assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); - assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); - assertThat(persistentAuditEvent.getData()).containsKey("test-key"); - String actualData = persistentAuditEvent.getData().get("test-key"); - assertThat(actualData.length()).isEqualTo(EVENT_DATA_COLUMN_MAX_LENGTH); - assertThat(actualData).isSubstringOf(largeData); - assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp()); - } - - @Test - public void testAddEventWithWebAuthenticationDetails() { - HttpSession session = new MockHttpSession(null, "test-session-id"); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setSession(session); - request.setRemoteAddr("1.2.3.4"); - WebAuthenticationDetails details = new WebAuthenticationDetails(request); - Map data = new HashMap<>(); - data.put("test-key", details); - AuditEvent event = new AuditEvent("test-user", "test-type", data); - customAuditEventRepository.add(event); - List persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(1); - PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); - assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); - assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); - } - - @Test - public void testAddEventWithNullData() { - Map data = new HashMap<>(); - data.put("test-key", null); - AuditEvent event = new AuditEvent("test-user", "test-type", data); - customAuditEventRepository.add(event); - List persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(1); - PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); - assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("null"); - } - - @Test - public void addAuditEventWithAnonymousUser() { - Map data = new HashMap<>(); - data.put("test-key", "test-value"); - AuditEvent event = new AuditEvent(Constants.ANONYMOUS_USER, "test-type", data); - customAuditEventRepository.add(event); - List persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(0); - } - - @Test - public void addAuditEventWithAuthorizationFailureType() { - Map data = new HashMap<>(); - data.put("test-key", "test-value"); - AuditEvent event = new AuditEvent("test-user", "AUTHORIZATION_FAILURE", data); - customAuditEventRepository.add(event); - List persistentAuditEvents = persistenceAuditEventRepository.findAll(); - assertThat(persistentAuditEvents).hasSize(0); - } - -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntegrationTest.java new file mode 100644 index 0000000000..948bf43f87 --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntegrationTest.java @@ -0,0 +1,165 @@ +package com.baeldung.jhipster5.repository; + +import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster5.config.Constants; +import com.baeldung.jhipster5.config.audit.AuditEventConverter; +import com.baeldung.jhipster5.domain.PersistentAuditEvent; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.actuate.audit.AuditEvent; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.web.authentication.WebAuthenticationDetails; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import javax.servlet.http.HttpSession; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static com.baeldung.jhipster5.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; + +/** + * Test class for the CustomAuditEventRepository class. + * + * @see CustomAuditEventRepository + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +@Transactional +public class CustomAuditEventRepositoryIntegrationTest { + + @Autowired + private PersistenceAuditEventRepository persistenceAuditEventRepository; + + @Autowired + private AuditEventConverter auditEventConverter; + + private CustomAuditEventRepository customAuditEventRepository; + + private PersistentAuditEvent testUserEvent; + + private PersistentAuditEvent testOtherUserEvent; + + private PersistentAuditEvent testOldUserEvent; + + @Before + public void setup() { + customAuditEventRepository = new CustomAuditEventRepository(persistenceAuditEventRepository, auditEventConverter); + persistenceAuditEventRepository.deleteAll(); + Instant oneHourAgo = Instant.now().minusSeconds(3600); + + testUserEvent = new PersistentAuditEvent(); + testUserEvent.setPrincipal("test-user"); + testUserEvent.setAuditEventType("test-type"); + testUserEvent.setAuditEventDate(oneHourAgo); + Map data = new HashMap<>(); + data.put("test-key", "test-value"); + testUserEvent.setData(data); + + testOldUserEvent = new PersistentAuditEvent(); + testOldUserEvent.setPrincipal("test-user"); + testOldUserEvent.setAuditEventType("test-type"); + testOldUserEvent.setAuditEventDate(oneHourAgo.minusSeconds(10000)); + + testOtherUserEvent = new PersistentAuditEvent(); + testOtherUserEvent.setPrincipal("other-test-user"); + testOtherUserEvent.setAuditEventType("test-type"); + testOtherUserEvent.setAuditEventDate(oneHourAgo); + } + + @Test + public void addAuditEvent() { + Map data = new HashMap<>(); + data.put("test-key", "test-value"); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); + assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); + assertThat(persistentAuditEvent.getData()).containsKey("test-key"); + assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("test-value"); + assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp()); + } + + @Test + public void addAuditEventTruncateLargeData() { + Map data = new HashMap<>(); + StringBuilder largeData = new StringBuilder(); + for (int i = 0; i < EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) { + largeData.append("a"); + } + data.put("test-key", largeData); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); + assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); + assertThat(persistentAuditEvent.getData()).containsKey("test-key"); + String actualData = persistentAuditEvent.getData().get("test-key"); + assertThat(actualData.length()).isEqualTo(EVENT_DATA_COLUMN_MAX_LENGTH); + assertThat(actualData).isSubstringOf(largeData); + assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp()); + } + + @Test + public void testAddEventWithWebAuthenticationDetails() { + HttpSession session = new MockHttpSession(null, "test-session-id"); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setSession(session); + request.setRemoteAddr("1.2.3.4"); + WebAuthenticationDetails details = new WebAuthenticationDetails(request); + Map data = new HashMap<>(); + data.put("test-key", details); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); + assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); + } + + @Test + public void testAddEventWithNullData() { + Map data = new HashMap<>(); + data.put("test-key", null); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("null"); + } + + @Test + public void addAuditEventWithAnonymousUser() { + Map data = new HashMap<>(); + data.put("test-key", "test-value"); + AuditEvent event = new AuditEvent(Constants.ANONYMOUS_USER, "test-type", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(0); + } + + @Test + public void addAuditEventWithAuthorizationFailureType() { + Map data = new HashMap<>(); + data.put("test-key", "test-value"); + AuditEvent event = new AuditEvent("test-user", "AUTHORIZATION_FAILURE", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(0); + } + +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntTest.java deleted file mode 100644 index f11252de2b..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.baeldung.jhipster5.security; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.UserRepository; - -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.boot.test.context.SpringBootTest; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import java.util.Locale; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Test class for DomainUserDetailsService. - * - * @see DomainUserDetailsService - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -@Transactional -public class DomainUserDetailsServiceIntTest { - - private static final String USER_ONE_LOGIN = "test-user-one"; - private static final String USER_ONE_EMAIL = "test-user-one@localhost"; - private static final String USER_TWO_LOGIN = "test-user-two"; - private static final String USER_TWO_EMAIL = "test-user-two@localhost"; - private static final String USER_THREE_LOGIN = "test-user-three"; - private static final String USER_THREE_EMAIL = "test-user-three@localhost"; - - @Autowired - private UserRepository userRepository; - - @Autowired - private UserDetailsService domainUserDetailsService; - - private User userOne; - private User userTwo; - private User userThree; - - @Before - public void init() { - userOne = new User(); - userOne.setLogin(USER_ONE_LOGIN); - userOne.setPassword(RandomStringUtils.random(60)); - userOne.setActivated(true); - userOne.setEmail(USER_ONE_EMAIL); - userOne.setFirstName("userOne"); - userOne.setLastName("doe"); - userOne.setLangKey("en"); - userRepository.save(userOne); - - userTwo = new User(); - userTwo.setLogin(USER_TWO_LOGIN); - userTwo.setPassword(RandomStringUtils.random(60)); - userTwo.setActivated(true); - userTwo.setEmail(USER_TWO_EMAIL); - userTwo.setFirstName("userTwo"); - userTwo.setLastName("doe"); - userTwo.setLangKey("en"); - userRepository.save(userTwo); - - userThree = new User(); - userThree.setLogin(USER_THREE_LOGIN); - userThree.setPassword(RandomStringUtils.random(60)); - userThree.setActivated(false); - userThree.setEmail(USER_THREE_EMAIL); - userThree.setFirstName("userThree"); - userThree.setLastName("doe"); - userThree.setLangKey("en"); - userRepository.save(userThree); - } - - @Test - @Transactional - public void assertThatUserCanBeFoundByLogin() { - UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN); - assertThat(userDetails).isNotNull(); - assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); - } - - @Test - @Transactional - public void assertThatUserCanBeFoundByLoginIgnoreCase() { - UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH)); - assertThat(userDetails).isNotNull(); - assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); - } - - @Test - @Transactional - public void assertThatUserCanBeFoundByEmail() { - UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL); - assertThat(userDetails).isNotNull(); - assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN); - } - - @Test(expected = UsernameNotFoundException.class) - @Transactional - public void assertThatUserCanNotBeFoundByEmailIgnoreCase() { - domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH)); - } - - @Test - @Transactional - public void assertThatEmailIsPrioritizedOverLogin() { - UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_EMAIL); - assertThat(userDetails).isNotNull(); - assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); - } - - @Test(expected = UserNotActivatedException.class) - @Transactional - public void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() { - domainUserDetailsService.loadUserByUsername(USER_THREE_LOGIN); - } - -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntegrationTest.java new file mode 100644 index 0000000000..11757f6516 --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntegrationTest.java @@ -0,0 +1,127 @@ +package com.baeldung.jhipster5.security; + +import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster5.domain.User; +import com.baeldung.jhipster5.repository.UserRepository; + +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.boot.test.context.SpringBootTest; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Locale; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test class for DomainUserDetailsService. + * + * @see DomainUserDetailsService + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +@Transactional +public class DomainUserDetailsServiceIntegrationTest { + + private static final String USER_ONE_LOGIN = "test-user-one"; + private static final String USER_ONE_EMAIL = "test-user-one@localhost"; + private static final String USER_TWO_LOGIN = "test-user-two"; + private static final String USER_TWO_EMAIL = "test-user-two@localhost"; + private static final String USER_THREE_LOGIN = "test-user-three"; + private static final String USER_THREE_EMAIL = "test-user-three@localhost"; + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserDetailsService domainUserDetailsService; + + private User userOne; + private User userTwo; + private User userThree; + + @Before + public void init() { + userOne = new User(); + userOne.setLogin(USER_ONE_LOGIN); + userOne.setPassword(RandomStringUtils.random(60)); + userOne.setActivated(true); + userOne.setEmail(USER_ONE_EMAIL); + userOne.setFirstName("userOne"); + userOne.setLastName("doe"); + userOne.setLangKey("en"); + userRepository.save(userOne); + + userTwo = new User(); + userTwo.setLogin(USER_TWO_LOGIN); + userTwo.setPassword(RandomStringUtils.random(60)); + userTwo.setActivated(true); + userTwo.setEmail(USER_TWO_EMAIL); + userTwo.setFirstName("userTwo"); + userTwo.setLastName("doe"); + userTwo.setLangKey("en"); + userRepository.save(userTwo); + + userThree = new User(); + userThree.setLogin(USER_THREE_LOGIN); + userThree.setPassword(RandomStringUtils.random(60)); + userThree.setActivated(false); + userThree.setEmail(USER_THREE_EMAIL); + userThree.setFirstName("userThree"); + userThree.setLastName("doe"); + userThree.setLangKey("en"); + userRepository.save(userThree); + } + + @Test + @Transactional + public void assertThatUserCanBeFoundByLogin() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test + @Transactional + public void assertThatUserCanBeFoundByLoginIgnoreCase() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH)); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test + @Transactional + public void assertThatUserCanBeFoundByEmail() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN); + } + + @Test(expected = UsernameNotFoundException.class) + @Transactional + public void assertThatUserCanNotBeFoundByEmailIgnoreCase() { + domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH)); + } + + @Test + @Transactional + public void assertThatEmailIsPrioritizedOverLogin() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_EMAIL); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test(expected = UserNotActivatedException.class) + @Transactional + public void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() { + domainUserDetailsService.loadUserByUsername(USER_THREE_LOGIN); + } + +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterTest.java deleted file mode 100644 index b3de21819b..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterTest.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.baeldung.jhipster5.security.jwt; - -import com.baeldung.jhipster5.security.AuthoritiesConstants; -import io.github.jhipster.config.JHipsterProperties; -import io.jsonwebtoken.io.Decoders; -import io.jsonwebtoken.security.Keys; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.http.HttpStatus; -import org.springframework.mock.web.MockFilterChain; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.test.util.ReflectionTestUtils; - -import java.util.Collections; - -import static org.assertj.core.api.Assertions.assertThat; - -public class JWTFilterTest { - - private TokenProvider tokenProvider; - - private JWTFilter jwtFilter; - - @Before - public void setup() { - JHipsterProperties jHipsterProperties = new JHipsterProperties(); - tokenProvider = new TokenProvider(jHipsterProperties); - ReflectionTestUtils.setField(tokenProvider, "key", - Keys.hmacShaKeyFor(Decoders.BASE64 - .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"))); - - ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000); - jwtFilter = new JWTFilter(tokenProvider); - SecurityContextHolder.getContext().setAuthentication(null); - } - - @Test - public void testJWTFilter() throws Exception { - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - "test-user", - "test-password", - Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) - ); - String jwt = tokenProvider.createToken(authentication, false); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user"); - assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt); - } - - @Test - public void testJWTFilterInvalidToken() throws Exception { - String jwt = "wrong_jwt"; - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); - } - - @Test - public void testJWTFilterMissingAuthorization() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); - } - - @Test - public void testJWTFilterMissingToken() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer "); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); - } - - @Test - public void testJWTFilterWrongScheme() throws Exception { - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - "test-user", - "test-password", - Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) - ); - String jwt = tokenProvider.createToken(authentication, false); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); - } - -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterUnitTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterUnitTest.java new file mode 100644 index 0000000000..2be8e6809a --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterUnitTest.java @@ -0,0 +1,115 @@ +package com.baeldung.jhipster5.security.jwt; + +import com.baeldung.jhipster5.security.AuthoritiesConstants; +import io.github.jhipster.config.JHipsterProperties; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.HttpStatus; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JWTFilterUnitTest { + + private TokenProvider tokenProvider; + + private JWTFilter jwtFilter; + + @Before + public void setup() { + JHipsterProperties jHipsterProperties = new JHipsterProperties(); + tokenProvider = new TokenProvider(jHipsterProperties); + ReflectionTestUtils.setField(tokenProvider, "key", + Keys.hmacShaKeyFor(Decoders.BASE64 + .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"))); + + ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000); + jwtFilter = new JWTFilter(tokenProvider); + SecurityContextHolder.getContext().setAuthentication(null); + } + + @Test + public void testJWTFilter() throws Exception { + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( + "test-user", + "test-password", + Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) + ); + String jwt = tokenProvider.createToken(authentication, false); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user"); + assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt); + } + + @Test + public void testJWTFilterInvalidToken() throws Exception { + String jwt = "wrong_jwt"; + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + + @Test + public void testJWTFilterMissingAuthorization() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + + @Test + public void testJWTFilterMissingToken() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer "); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + + @Test + public void testJWTFilterWrongScheme() throws Exception { + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( + "test-user", + "test-password", + Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) + ); + String jwt = tokenProvider.createToken(authentication, false); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderTest.java deleted file mode 100644 index 11fcfddbf9..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.baeldung.jhipster5.security.jwt; - -import com.baeldung.jhipster5.security.AuthoritiesConstants; - -import java.security.Key; -import java.util.*; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.test.util.ReflectionTestUtils; - -import io.github.jhipster.config.JHipsterProperties; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import io.jsonwebtoken.io.Decoders; -import io.jsonwebtoken.security.Keys; - -import static org.assertj.core.api.Assertions.assertThat; - -public class TokenProviderTest { - - private final long ONE_MINUTE = 60000; - private Key key; - private JHipsterProperties jHipsterProperties; - private TokenProvider tokenProvider; - - @Before - public void setup() { - jHipsterProperties = Mockito.mock(JHipsterProperties.class); - tokenProvider = new TokenProvider(jHipsterProperties); - key = Keys.hmacShaKeyFor(Decoders.BASE64 - .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); - - ReflectionTestUtils.setField(tokenProvider, "key", key); - ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE); - } - - @Test - public void testReturnFalseWhenJWThasInvalidSignature() { - boolean isTokenValid = tokenProvider.validateToken(createTokenWithDifferentSignature()); - - assertThat(isTokenValid).isEqualTo(false); - } - - @Test - public void testReturnFalseWhenJWTisMalformed() { - Authentication authentication = createAuthentication(); - String token = tokenProvider.createToken(authentication, false); - String invalidToken = token.substring(1); - boolean isTokenValid = tokenProvider.validateToken(invalidToken); - - assertThat(isTokenValid).isEqualTo(false); - } - - @Test - public void testReturnFalseWhenJWTisExpired() { - ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", -ONE_MINUTE); - - Authentication authentication = createAuthentication(); - String token = tokenProvider.createToken(authentication, false); - - boolean isTokenValid = tokenProvider.validateToken(token); - - assertThat(isTokenValid).isEqualTo(false); - } - - @Test - public void testReturnFalseWhenJWTisUnsupported() { - String unsupportedToken = createUnsupportedToken(); - - boolean isTokenValid = tokenProvider.validateToken(unsupportedToken); - - assertThat(isTokenValid).isEqualTo(false); - } - - @Test - public void testReturnFalseWhenJWTisInvalid() { - boolean isTokenValid = tokenProvider.validateToken(""); - - assertThat(isTokenValid).isEqualTo(false); - } - - private Authentication createAuthentication() { - Collection authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); - return new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities); - } - - private String createUnsupportedToken() { - return Jwts.builder() - .setPayload("payload") - .signWith(key, SignatureAlgorithm.HS512) - .compact(); - } - - private String createTokenWithDifferentSignature() { - Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64 - .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); - - return Jwts.builder() - .setSubject("anonymous") - .signWith(otherKey, SignatureAlgorithm.HS512) - .setExpiration(new Date(new Date().getTime() + ONE_MINUTE)) - .compact(); - } -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderUnitTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderUnitTest.java new file mode 100644 index 0000000000..18da2eb875 --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderUnitTest.java @@ -0,0 +1,111 @@ +package com.baeldung.jhipster5.security.jwt; + +import com.baeldung.jhipster5.security.AuthoritiesConstants; + +import java.security.Key; +import java.util.*; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.test.util.ReflectionTestUtils; + +import io.github.jhipster.config.JHipsterProperties; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; + +import static org.assertj.core.api.Assertions.assertThat; + +public class TokenProviderUnitTest { + + private final long ONE_MINUTE = 60000; + private Key key; + private JHipsterProperties jHipsterProperties; + private TokenProvider tokenProvider; + + @Before + public void setup() { + jHipsterProperties = Mockito.mock(JHipsterProperties.class); + tokenProvider = new TokenProvider(jHipsterProperties); + key = Keys.hmacShaKeyFor(Decoders.BASE64 + .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); + + ReflectionTestUtils.setField(tokenProvider, "key", key); + ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE); + } + + @Test + public void testReturnFalseWhenJWThasInvalidSignature() { + boolean isTokenValid = tokenProvider.validateToken(createTokenWithDifferentSignature()); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisMalformed() { + Authentication authentication = createAuthentication(); + String token = tokenProvider.createToken(authentication, false); + String invalidToken = token.substring(1); + boolean isTokenValid = tokenProvider.validateToken(invalidToken); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisExpired() { + ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", -ONE_MINUTE); + + Authentication authentication = createAuthentication(); + String token = tokenProvider.createToken(authentication, false); + + boolean isTokenValid = tokenProvider.validateToken(token); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisUnsupported() { + String unsupportedToken = createUnsupportedToken(); + + boolean isTokenValid = tokenProvider.validateToken(unsupportedToken); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisInvalid() { + boolean isTokenValid = tokenProvider.validateToken(""); + + assertThat(isTokenValid).isEqualTo(false); + } + + private Authentication createAuthentication() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); + return new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities); + } + + private String createUnsupportedToken() { + return Jwts.builder() + .setPayload("payload") + .signWith(key, SignatureAlgorithm.HS512) + .compact(); + } + + private String createTokenWithDifferentSignature() { + Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64 + .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); + + return Jwts.builder() + .setSubject("anonymous") + .signWith(otherKey, SignatureAlgorithm.HS512) + .setExpiration(new Date(new Date().getTime() + ONE_MINUTE)) + .compact(); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntTest.java deleted file mode 100644 index 4bde3276f5..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntTest.java +++ /dev/null @@ -1,187 +0,0 @@ -package com.baeldung.jhipster5.service; -import com.baeldung.jhipster5.config.Constants; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.domain.User; -import io.github.jhipster.config.JHipsterProperties; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.MessageSource; -import org.springframework.mail.MailSendException; -import org.springframework.mail.javamail.JavaMailSenderImpl; -import org.springframework.test.context.junit4.SpringRunner; -import org.thymeleaf.spring5.SpringTemplateEngine; - -import javax.mail.Multipart; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; -import java.io.ByteArrayOutputStream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -public class MailServiceIntTest { - - @Autowired - private JHipsterProperties jHipsterProperties; - - @Autowired - private MessageSource messageSource; - - @Autowired - private SpringTemplateEngine templateEngine; - - @Spy - private JavaMailSenderImpl javaMailSender; - - @Captor - private ArgumentCaptor messageCaptor; - - private MailService mailService; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - doNothing().when(javaMailSender).send(any(MimeMessage.class)); - mailService = new MailService(jHipsterProperties, javaMailSender, messageSource, templateEngine); - } - - @Test - public void testSendEmail() throws Exception { - mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getSubject()).isEqualTo("testSubject"); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); - assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); - assertThat(message.getContent()).isInstanceOf(String.class); - assertThat(message.getContent().toString()).isEqualTo("testContent"); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); - } - - @Test - public void testSendHtmlEmail() throws Exception { - mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, true); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getSubject()).isEqualTo("testSubject"); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); - assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); - assertThat(message.getContent()).isInstanceOf(String.class); - assertThat(message.getContent().toString()).isEqualTo("testContent"); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); - } - - @Test - public void testSendMultipartEmail() throws Exception { - mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, false); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - MimeMultipart mp = (MimeMultipart) message.getContent(); - MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - part.writeTo(aos); - assertThat(message.getSubject()).isEqualTo("testSubject"); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); - assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); - assertThat(message.getContent()).isInstanceOf(Multipart.class); - assertThat(aos.toString()).isEqualTo("\r\ntestContent"); - assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); - } - - @Test - public void testSendMultipartHtmlEmail() throws Exception { - mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, true); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - MimeMultipart mp = (MimeMultipart) message.getContent(); - MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - part.writeTo(aos); - assertThat(message.getSubject()).isEqualTo("testSubject"); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); - assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); - assertThat(message.getContent()).isInstanceOf(Multipart.class); - assertThat(aos.toString()).isEqualTo("\r\ntestContent"); - assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); - } - - @Test - public void testSendEmailFromTemplate() throws Exception { - User user = new User(); - user.setLogin("john"); - user.setEmail("john.doe@example.com"); - user.setLangKey("en"); - mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title"); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getSubject()).isEqualTo("test title"); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); - assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); - assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("test title, http://127.0.0.1:8080, john\n"); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); - } - - @Test - public void testSendActivationEmail() throws Exception { - User user = new User(); - user.setLangKey(Constants.DEFAULT_LANGUAGE); - user.setLogin("john"); - user.setEmail("john.doe@example.com"); - mailService.sendActivationEmail(user); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); - assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); - assertThat(message.getContent().toString()).isNotEmpty(); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); - } - - @Test - public void testCreationEmail() throws Exception { - User user = new User(); - user.setLangKey(Constants.DEFAULT_LANGUAGE); - user.setLogin("john"); - user.setEmail("john.doe@example.com"); - mailService.sendCreationEmail(user); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); - assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); - assertThat(message.getContent().toString()).isNotEmpty(); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); - } - - @Test - public void testSendPasswordResetMail() throws Exception { - User user = new User(); - user.setLangKey(Constants.DEFAULT_LANGUAGE); - user.setLogin("john"); - user.setEmail("john.doe@example.com"); - mailService.sendPasswordResetMail(user); - verify(javaMailSender).send(messageCaptor.capture()); - MimeMessage message = messageCaptor.getValue(); - assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); - assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); - assertThat(message.getContent().toString()).isNotEmpty(); - assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); - } - - @Test - public void testSendEmailWithException() throws Exception { - doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class)); - mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); - } - -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntegrationTest.java new file mode 100644 index 0000000000..72592e1239 --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntegrationTest.java @@ -0,0 +1,187 @@ +package com.baeldung.jhipster5.service; +import com.baeldung.jhipster5.config.Constants; + +import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster5.domain.User; +import io.github.jhipster.config.JHipsterProperties; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.MessageSource; +import org.springframework.mail.MailSendException; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import org.springframework.test.context.junit4.SpringRunner; +import org.thymeleaf.spring5.SpringTemplateEngine; + +import javax.mail.Multipart; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; +import java.io.ByteArrayOutputStream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +public class MailServiceIntegrationTest { + + @Autowired + private JHipsterProperties jHipsterProperties; + + @Autowired + private MessageSource messageSource; + + @Autowired + private SpringTemplateEngine templateEngine; + + @Spy + private JavaMailSenderImpl javaMailSender; + + @Captor + private ArgumentCaptor messageCaptor; + + private MailService mailService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + doNothing().when(javaMailSender).send(any(MimeMessage.class)); + mailService = new MailService(jHipsterProperties, javaMailSender, messageSource, templateEngine); + } + + @Test + public void testSendEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent()).isInstanceOf(String.class); + assertThat(message.getContent().toString()).isEqualTo("testContent"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); + } + + @Test + public void testSendHtmlEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, true); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent()).isInstanceOf(String.class); + assertThat(message.getContent().toString()).isEqualTo("testContent"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendMultipartEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, false); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + MimeMultipart mp = (MimeMultipart) message.getContent(); + MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + part.writeTo(aos); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent()).isInstanceOf(Multipart.class); + assertThat(aos.toString()).isEqualTo("\r\ntestContent"); + assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); + } + + @Test + public void testSendMultipartHtmlEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, true); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + MimeMultipart mp = (MimeMultipart) message.getContent(); + MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + part.writeTo(aos); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent()).isInstanceOf(Multipart.class); + assertThat(aos.toString()).isEqualTo("\r\ntestContent"); + assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendEmailFromTemplate() throws Exception { + User user = new User(); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + user.setLangKey("en"); + mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title"); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("test title"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("test title, http://127.0.0.1:8080, john\n"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendActivationEmail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendActivationEmail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testCreationEmail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendCreationEmail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendPasswordResetMail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendPasswordResetMail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendEmailWithException() throws Exception { + doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class)); + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); + } + +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntTest.java deleted file mode 100644 index 81034c2793..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntTest.java +++ /dev/null @@ -1,192 +0,0 @@ -package com.baeldung.jhipster5.service; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.config.Constants; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.UserRepository; -import com.baeldung.jhipster5.service.dto.UserDTO; -import com.baeldung.jhipster5.service.util.RandomUtil; - -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.auditing.AuditingHandler; -import org.springframework.data.auditing.DateTimeProvider; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.time.LocalDateTime; -import java.util.Optional; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -/** - * Test class for the UserResource REST controller. - * - * @see UserService - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -@Transactional -public class UserServiceIntTest { - - @Autowired - private UserRepository userRepository; - - @Autowired - private UserService userService; - - @Autowired - private AuditingHandler auditingHandler; - - @Mock - DateTimeProvider dateTimeProvider; - - private User user; - - @Before - public void init() { - user = new User(); - user.setLogin("johndoe"); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - user.setEmail("johndoe@localhost"); - user.setFirstName("john"); - user.setLastName("doe"); - user.setImageUrl("http://placehold.it/50x50"); - user.setLangKey("en"); - - when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now())); - auditingHandler.setDateTimeProvider(dateTimeProvider); - } - - @Test - @Transactional - public void assertThatUserMustExistToResetPassword() { - userRepository.saveAndFlush(user); - Optional maybeUser = userService.requestPasswordReset("invalid.login@localhost"); - assertThat(maybeUser).isNotPresent(); - - maybeUser = userService.requestPasswordReset(user.getEmail()); - assertThat(maybeUser).isPresent(); - assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail()); - assertThat(maybeUser.orElse(null).getResetDate()).isNotNull(); - assertThat(maybeUser.orElse(null).getResetKey()).isNotNull(); - } - - @Test - @Transactional - public void assertThatOnlyActivatedUserCanRequestPasswordReset() { - user.setActivated(false); - userRepository.saveAndFlush(user); - - Optional maybeUser = userService.requestPasswordReset(user.getLogin()); - assertThat(maybeUser).isNotPresent(); - userRepository.delete(user); - } - - @Test - @Transactional - public void assertThatResetKeyMustNotBeOlderThan24Hours() { - Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); - String resetKey = RandomUtil.generateResetKey(); - user.setActivated(true); - user.setResetDate(daysAgo); - user.setResetKey(resetKey); - userRepository.saveAndFlush(user); - - Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); - assertThat(maybeUser).isNotPresent(); - userRepository.delete(user); - } - - @Test - @Transactional - public void assertThatResetKeyMustBeValid() { - Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); - user.setActivated(true); - user.setResetDate(daysAgo); - user.setResetKey("1234"); - userRepository.saveAndFlush(user); - - Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); - assertThat(maybeUser).isNotPresent(); - userRepository.delete(user); - } - - @Test - @Transactional - public void assertThatUserCanResetPassword() { - String oldPassword = user.getPassword(); - Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS); - String resetKey = RandomUtil.generateResetKey(); - user.setActivated(true); - user.setResetDate(daysAgo); - user.setResetKey(resetKey); - userRepository.saveAndFlush(user); - - Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); - assertThat(maybeUser).isPresent(); - assertThat(maybeUser.orElse(null).getResetDate()).isNull(); - assertThat(maybeUser.orElse(null).getResetKey()).isNull(); - assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword); - - userRepository.delete(user); - } - - @Test - @Transactional - public void testFindNotActivatedUsersByCreationDateBefore() { - Instant now = Instant.now(); - when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS))); - user.setActivated(false); - User dbUser = userRepository.saveAndFlush(user); - dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS)); - userRepository.saveAndFlush(user); - List users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS)); - assertThat(users).isNotEmpty(); - userService.removeNotActivatedUsers(); - users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS)); - assertThat(users).isEmpty(); - } - - @Test - @Transactional - public void assertThatAnonymousUserIsNotGet() { - user.setLogin(Constants.ANONYMOUS_USER); - if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) { - userRepository.saveAndFlush(user); - } - final PageRequest pageable = PageRequest.of(0, (int) userRepository.count()); - final Page allManagedUsers = userService.getAllManagedUsers(pageable); - assertThat(allManagedUsers.getContent().stream() - .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))) - .isTrue(); - } - - - @Test - @Transactional - public void testRemoveNotActivatedUsers() { - // custom "now" for audit to use as creation date - when(dateTimeProvider.getNow()).thenReturn(Optional.of(Instant.now().minus(30, ChronoUnit.DAYS))); - - user.setActivated(false); - userRepository.saveAndFlush(user); - - assertThat(userRepository.findOneByLogin("johndoe")).isPresent(); - userService.removeNotActivatedUsers(); - assertThat(userRepository.findOneByLogin("johndoe")).isNotPresent(); - } - -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntegrationTest.java new file mode 100644 index 0000000000..ca3608462d --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntegrationTest.java @@ -0,0 +1,192 @@ +package com.baeldung.jhipster5.service; + +import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster5.config.Constants; +import com.baeldung.jhipster5.domain.User; +import com.baeldung.jhipster5.repository.UserRepository; +import com.baeldung.jhipster5.service.dto.UserDTO; +import com.baeldung.jhipster5.service.util.RandomUtil; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.auditing.AuditingHandler; +import org.springframework.data.auditing.DateTimeProvider; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.time.LocalDateTime; +import java.util.Optional; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +/** + * Test class for the UserResource REST controller. + * + * @see UserService + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +@Transactional +public class UserServiceIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserService userService; + + @Autowired + private AuditingHandler auditingHandler; + + @Mock + DateTimeProvider dateTimeProvider; + + private User user; + + @Before + public void init() { + user = new User(); + user.setLogin("johndoe"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setEmail("johndoe@localhost"); + user.setFirstName("john"); + user.setLastName("doe"); + user.setImageUrl("http://placehold.it/50x50"); + user.setLangKey("en"); + + when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now())); + auditingHandler.setDateTimeProvider(dateTimeProvider); + } + + @Test + @Transactional + public void assertThatUserMustExistToResetPassword() { + userRepository.saveAndFlush(user); + Optional maybeUser = userService.requestPasswordReset("invalid.login@localhost"); + assertThat(maybeUser).isNotPresent(); + + maybeUser = userService.requestPasswordReset(user.getEmail()); + assertThat(maybeUser).isPresent(); + assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail()); + assertThat(maybeUser.orElse(null).getResetDate()).isNotNull(); + assertThat(maybeUser.orElse(null).getResetKey()).isNotNull(); + } + + @Test + @Transactional + public void assertThatOnlyActivatedUserCanRequestPasswordReset() { + user.setActivated(false); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.requestPasswordReset(user.getLogin()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + public void assertThatResetKeyMustNotBeOlderThan24Hours() { + Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); + String resetKey = RandomUtil.generateResetKey(); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey(resetKey); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + public void assertThatResetKeyMustBeValid() { + Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey("1234"); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + public void assertThatUserCanResetPassword() { + String oldPassword = user.getPassword(); + Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS); + String resetKey = RandomUtil.generateResetKey(); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey(resetKey); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isPresent(); + assertThat(maybeUser.orElse(null).getResetDate()).isNull(); + assertThat(maybeUser.orElse(null).getResetKey()).isNull(); + assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword); + + userRepository.delete(user); + } + + @Test + @Transactional + public void testFindNotActivatedUsersByCreationDateBefore() { + Instant now = Instant.now(); + when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS))); + user.setActivated(false); + User dbUser = userRepository.saveAndFlush(user); + dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS)); + userRepository.saveAndFlush(user); + List users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS)); + assertThat(users).isNotEmpty(); + userService.removeNotActivatedUsers(); + users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS)); + assertThat(users).isEmpty(); + } + + @Test + @Transactional + public void assertThatAnonymousUserIsNotGet() { + user.setLogin(Constants.ANONYMOUS_USER); + if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) { + userRepository.saveAndFlush(user); + } + final PageRequest pageable = PageRequest.of(0, (int) userRepository.count()); + final Page allManagedUsers = userService.getAllManagedUsers(pageable); + assertThat(allManagedUsers.getContent().stream() + .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))) + .isTrue(); + } + + + @Test + @Transactional + public void testRemoveNotActivatedUsers() { + // custom "now" for audit to use as creation date + when(dateTimeProvider.getNow()).thenReturn(Optional.of(Instant.now().minus(30, ChronoUnit.DAYS))); + + user.setActivated(false); + userRepository.saveAndFlush(user); + + assertThat(userRepository.findOneByLogin("johndoe")).isPresent(); + userService.removeNotActivatedUsers(); + assertThat(userRepository.findOneByLogin("johndoe")).isNotPresent(); + } + +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java new file mode 100644 index 0000000000..cd49135d63 --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java @@ -0,0 +1,150 @@ +package com.baeldung.jhipster5.service.mapper; + + +import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster5.domain.User; +import com.baeldung.jhipster5.service.dto.UserDTO; +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.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test class for the UserMapper. + * + * @see UserMapper + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +public class UserMapperIntegrationTest { + + private static final String DEFAULT_LOGIN = "johndoe"; + + @Autowired + private UserMapper userMapper; + + private User user; + private UserDTO userDto; + + private static final Long DEFAULT_ID = 1L; + + @Before + public void init() { + user = new User(); + user.setLogin(DEFAULT_LOGIN); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setEmail("johndoe@localhost"); + user.setFirstName("john"); + user.setLastName("doe"); + user.setImageUrl("image_url"); + user.setLangKey("en"); + + userDto = new UserDTO(user); + } + + @Test + public void usersToUserDTOsShouldMapOnlyNonNullUsers(){ + List users = new ArrayList<>(); + users.add(user); + users.add(null); + + List userDTOS = userMapper.usersToUserDTOs(users); + + assertThat(userDTOS).isNotEmpty(); + assertThat(userDTOS).size().isEqualTo(1); + } + + @Test + public void userDTOsToUsersShouldMapOnlyNonNullUsers(){ + List usersDto = new ArrayList<>(); + usersDto.add(userDto); + usersDto.add(null); + + List users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty(); + assertThat(users).size().isEqualTo(1); + } + + @Test + public void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain(){ + Set authoritiesAsString = new HashSet<>(); + authoritiesAsString.add("ADMIN"); + userDto.setAuthorities(authoritiesAsString); + + List usersDto = new ArrayList<>(); + usersDto.add(userDto); + + List users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty(); + assertThat(users).size().isEqualTo(1); + assertThat(users.get(0).getAuthorities()).isNotNull(); + assertThat(users.get(0).getAuthorities()).isNotEmpty(); + assertThat(users.get(0).getAuthorities().iterator().next().getName()).isEqualTo("ADMIN"); + } + + @Test + public void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities(){ + userDto.setAuthorities(null); + + List usersDto = new ArrayList<>(); + usersDto.add(userDto); + + List users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty(); + assertThat(users).size().isEqualTo(1); + assertThat(users.get(0).getAuthorities()).isNotNull(); + assertThat(users.get(0).getAuthorities()).isEmpty(); + } + + @Test + public void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities(){ + Set authoritiesAsString = new HashSet<>(); + authoritiesAsString.add("ADMIN"); + userDto.setAuthorities(authoritiesAsString); + + userDto.setAuthorities(authoritiesAsString); + + User user = userMapper.userDTOToUser(userDto); + + assertThat(user).isNotNull(); + assertThat(user.getAuthorities()).isNotNull(); + assertThat(user.getAuthorities()).isNotEmpty(); + assertThat(user.getAuthorities().iterator().next().getName()).isEqualTo("ADMIN"); + } + + @Test + public void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities(){ + userDto.setAuthorities(null); + + User user = userMapper.userDTOToUser(userDto); + + assertThat(user).isNotNull(); + assertThat(user.getAuthorities()).isNotNull(); + assertThat(user.getAuthorities()).isEmpty(); + } + + @Test + public void userDTOToUserMapWithNullUserShouldReturnNull(){ + assertThat(userMapper.userDTOToUser(null)).isNull(); + } + + @Test + public void testUserFromId() { + assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID); + assertThat(userMapper.userFromId(null)).isNull(); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperTest.java deleted file mode 100644 index 3d66fa5813..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperTest.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.baeldung.jhipster5.service.mapper; - - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.service.dto.UserDTO; -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.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Test class for the UserMapper. - * - * @see UserMapper - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -public class UserMapperTest { - - private static final String DEFAULT_LOGIN = "johndoe"; - - @Autowired - private UserMapper userMapper; - - private User user; - private UserDTO userDto; - - private static final Long DEFAULT_ID = 1L; - - @Before - public void init() { - user = new User(); - user.setLogin(DEFAULT_LOGIN); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - user.setEmail("johndoe@localhost"); - user.setFirstName("john"); - user.setLastName("doe"); - user.setImageUrl("image_url"); - user.setLangKey("en"); - - userDto = new UserDTO(user); - } - - @Test - public void usersToUserDTOsShouldMapOnlyNonNullUsers(){ - List users = new ArrayList<>(); - users.add(user); - users.add(null); - - List userDTOS = userMapper.usersToUserDTOs(users); - - assertThat(userDTOS).isNotEmpty(); - assertThat(userDTOS).size().isEqualTo(1); - } - - @Test - public void userDTOsToUsersShouldMapOnlyNonNullUsers(){ - List usersDto = new ArrayList<>(); - usersDto.add(userDto); - usersDto.add(null); - - List users = userMapper.userDTOsToUsers(usersDto); - - assertThat(users).isNotEmpty(); - assertThat(users).size().isEqualTo(1); - } - - @Test - public void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain(){ - Set authoritiesAsString = new HashSet<>(); - authoritiesAsString.add("ADMIN"); - userDto.setAuthorities(authoritiesAsString); - - List usersDto = new ArrayList<>(); - usersDto.add(userDto); - - List users = userMapper.userDTOsToUsers(usersDto); - - assertThat(users).isNotEmpty(); - assertThat(users).size().isEqualTo(1); - assertThat(users.get(0).getAuthorities()).isNotNull(); - assertThat(users.get(0).getAuthorities()).isNotEmpty(); - assertThat(users.get(0).getAuthorities().iterator().next().getName()).isEqualTo("ADMIN"); - } - - @Test - public void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities(){ - userDto.setAuthorities(null); - - List usersDto = new ArrayList<>(); - usersDto.add(userDto); - - List users = userMapper.userDTOsToUsers(usersDto); - - assertThat(users).isNotEmpty(); - assertThat(users).size().isEqualTo(1); - assertThat(users.get(0).getAuthorities()).isNotNull(); - assertThat(users.get(0).getAuthorities()).isEmpty(); - } - - @Test - public void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities(){ - Set authoritiesAsString = new HashSet<>(); - authoritiesAsString.add("ADMIN"); - userDto.setAuthorities(authoritiesAsString); - - userDto.setAuthorities(authoritiesAsString); - - User user = userMapper.userDTOToUser(userDto); - - assertThat(user).isNotNull(); - assertThat(user.getAuthorities()).isNotNull(); - assertThat(user.getAuthorities()).isNotEmpty(); - assertThat(user.getAuthorities().iterator().next().getName()).isEqualTo("ADMIN"); - } - - @Test - public void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities(){ - userDto.setAuthorities(null); - - User user = userMapper.userDTOToUser(userDto); - - assertThat(user).isNotNull(); - assertThat(user.getAuthorities()).isNotNull(); - assertThat(user.getAuthorities()).isEmpty(); - } - - @Test - public void userDTOToUserMapWithNullUserShouldReturnNull(){ - assertThat(userMapper.userDTOToUser(null)).isNull(); - } - - @Test - public void testUserFromId() { - assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID); - assertThat(userMapper.userFromId(null)).isNull(); - } -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntTest.java deleted file mode 100644 index 6db284a87f..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntTest.java +++ /dev/null @@ -1,818 +0,0 @@ -package com.baeldung.jhipster5.web.rest; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.config.Constants; -import com.baeldung.jhipster5.domain.Authority; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.AuthorityRepository; -import com.baeldung.jhipster5.repository.UserRepository; -import com.baeldung.jhipster5.security.AuthoritiesConstants; -import com.baeldung.jhipster5.service.MailService; -import com.baeldung.jhipster5.service.UserService; -import com.baeldung.jhipster5.service.dto.PasswordChangeDTO; -import com.baeldung.jhipster5.service.dto.UserDTO; -import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; -import com.baeldung.jhipster5.web.rest.vm.KeyAndPasswordVM; -import com.baeldung.jhipster5.web.rest.vm.ManagedUserVM; -import org.apache.commons.lang3.RandomStringUtils; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.security.crypto.password.PasswordEncoder; -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.transaction.annotation.Transactional; - -import java.time.Instant; -import java.util.*; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -/** - * Test class for the AccountResource REST controller. - * - * @see AccountResource - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -public class AccountResourceIntTest { - - @Autowired - private UserRepository userRepository; - - @Autowired - private AuthorityRepository authorityRepository; - - @Autowired - private UserService userService; - - @Autowired - private PasswordEncoder passwordEncoder; - - @Autowired - private HttpMessageConverter[] httpMessageConverters; - - @Autowired - private ExceptionTranslator exceptionTranslator; - - @Mock - private UserService mockUserService; - - @Mock - private MailService mockMailService; - - private MockMvc restMvc; - - private MockMvc restUserMockMvc; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - doNothing().when(mockMailService).sendActivationEmail(any()); - AccountResource accountResource = - new AccountResource(userRepository, userService, mockMailService); - - AccountResource accountUserMockResource = - new AccountResource(userRepository, mockUserService, mockMailService); - this.restMvc = MockMvcBuilders.standaloneSetup(accountResource) - .setMessageConverters(httpMessageConverters) - .setControllerAdvice(exceptionTranslator) - .build(); - this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource) - .setControllerAdvice(exceptionTranslator) - .build(); - } - - @Test - public void testNonAuthenticatedUser() throws Exception { - restUserMockMvc.perform(get("/api/authenticate") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string("")); - } - - @Test - public void testAuthenticatedUser() throws Exception { - restUserMockMvc.perform(get("/api/authenticate") - .with(request -> { - request.setRemoteUser("test"); - return request; - }) - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string("test")); - } - - @Test - public void testGetExistingAccount() throws Exception { - Set authorities = new HashSet<>(); - Authority authority = new Authority(); - authority.setName(AuthoritiesConstants.ADMIN); - authorities.add(authority); - - User user = new User(); - user.setLogin("test"); - user.setFirstName("john"); - user.setLastName("doe"); - user.setEmail("john.doe@jhipster.com"); - user.setImageUrl("http://placehold.it/50x50"); - user.setLangKey("en"); - user.setAuthorities(authorities); - when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user)); - - restUserMockMvc.perform(get("/api/account") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.login").value("test")) - .andExpect(jsonPath("$.firstName").value("john")) - .andExpect(jsonPath("$.lastName").value("doe")) - .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) - .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) - .andExpect(jsonPath("$.langKey").value("en")) - .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); - } - - @Test - public void testGetUnknownAccount() throws Exception { - when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty()); - - restUserMockMvc.perform(get("/api/account") - .accept(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(status().isInternalServerError()); - } - - @Test - @Transactional - public void testRegisterValid() throws Exception { - ManagedUserVM validUser = new ManagedUserVM(); - validUser.setLogin("test-register-valid"); - validUser.setPassword("password"); - validUser.setFirstName("Alice"); - validUser.setLastName("Test"); - validUser.setEmail("test-register-valid@example.com"); - validUser.setImageUrl("http://placehold.it/50x50"); - validUser.setLangKey(Constants.DEFAULT_LANGUAGE); - validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse(); - - restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(validUser))) - .andExpect(status().isCreated()); - - assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue(); - } - - @Test - @Transactional - public void testRegisterInvalidLogin() throws Exception { - ManagedUserVM invalidUser = new ManagedUserVM(); - invalidUser.setLogin("funky-log!n");// <-- invalid - invalidUser.setPassword("password"); - invalidUser.setFirstName("Funky"); - invalidUser.setLastName("One"); - invalidUser.setEmail("funky@example.com"); - invalidUser.setActivated(true); - invalidUser.setImageUrl("http://placehold.it/50x50"); - invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); - invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); - - Optional user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); - assertThat(user.isPresent()).isFalse(); - } - - @Test - @Transactional - public void testRegisterInvalidEmail() throws Exception { - ManagedUserVM invalidUser = new ManagedUserVM(); - invalidUser.setLogin("bob"); - invalidUser.setPassword("password"); - invalidUser.setFirstName("Bob"); - invalidUser.setLastName("Green"); - invalidUser.setEmail("invalid");// <-- invalid - invalidUser.setActivated(true); - invalidUser.setImageUrl("http://placehold.it/50x50"); - invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); - invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); - - Optional user = userRepository.findOneByLogin("bob"); - assertThat(user.isPresent()).isFalse(); - } - - @Test - @Transactional - public void testRegisterInvalidPassword() throws Exception { - ManagedUserVM invalidUser = new ManagedUserVM(); - invalidUser.setLogin("bob"); - invalidUser.setPassword("123");// password with only 3 digits - invalidUser.setFirstName("Bob"); - invalidUser.setLastName("Green"); - invalidUser.setEmail("bob@example.com"); - invalidUser.setActivated(true); - invalidUser.setImageUrl("http://placehold.it/50x50"); - invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); - invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); - - Optional user = userRepository.findOneByLogin("bob"); - assertThat(user.isPresent()).isFalse(); - } - - @Test - @Transactional - public void testRegisterNullPassword() throws Exception { - ManagedUserVM invalidUser = new ManagedUserVM(); - invalidUser.setLogin("bob"); - invalidUser.setPassword(null);// invalid null password - invalidUser.setFirstName("Bob"); - invalidUser.setLastName("Green"); - invalidUser.setEmail("bob@example.com"); - invalidUser.setActivated(true); - invalidUser.setImageUrl("http://placehold.it/50x50"); - invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); - invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); - - Optional user = userRepository.findOneByLogin("bob"); - assertThat(user.isPresent()).isFalse(); - } - - @Test - @Transactional - public void testRegisterDuplicateLogin() throws Exception { - // First registration - ManagedUserVM firstUser = new ManagedUserVM(); - firstUser.setLogin("alice"); - firstUser.setPassword("password"); - firstUser.setFirstName("Alice"); - firstUser.setLastName("Something"); - firstUser.setEmail("alice@example.com"); - firstUser.setImageUrl("http://placehold.it/50x50"); - firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); - firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - // Duplicate login, different email - ManagedUserVM secondUser = new ManagedUserVM(); - secondUser.setLogin(firstUser.getLogin()); - secondUser.setPassword(firstUser.getPassword()); - secondUser.setFirstName(firstUser.getFirstName()); - secondUser.setLastName(firstUser.getLastName()); - secondUser.setEmail("alice2@example.com"); - secondUser.setImageUrl(firstUser.getImageUrl()); - secondUser.setLangKey(firstUser.getLangKey()); - secondUser.setCreatedBy(firstUser.getCreatedBy()); - secondUser.setCreatedDate(firstUser.getCreatedDate()); - secondUser.setLastModifiedBy(firstUser.getLastModifiedBy()); - secondUser.setLastModifiedDate(firstUser.getLastModifiedDate()); - secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); - - // First user - restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(firstUser))) - .andExpect(status().isCreated()); - - // Second (non activated) user - restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().isCreated()); - - Optional testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); - assertThat(testUser.isPresent()).isTrue(); - testUser.get().setActivated(true); - userRepository.save(testUser.get()); - - // Second (already activated) user - restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().is4xxClientError()); - } - - @Test - @Transactional - public void testRegisterDuplicateEmail() throws Exception { - // First user - ManagedUserVM firstUser = new ManagedUserVM(); - firstUser.setLogin("test-register-duplicate-email"); - firstUser.setPassword("password"); - firstUser.setFirstName("Alice"); - firstUser.setLastName("Test"); - firstUser.setEmail("test-register-duplicate-email@example.com"); - firstUser.setImageUrl("http://placehold.it/50x50"); - firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); - firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - // Register first user - restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(firstUser))) - .andExpect(status().isCreated()); - - Optional testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); - assertThat(testUser1.isPresent()).isTrue(); - - // Duplicate email, different login - ManagedUserVM secondUser = new ManagedUserVM(); - secondUser.setLogin("test-register-duplicate-email-2"); - secondUser.setPassword(firstUser.getPassword()); - secondUser.setFirstName(firstUser.getFirstName()); - secondUser.setLastName(firstUser.getLastName()); - secondUser.setEmail(firstUser.getEmail()); - secondUser.setImageUrl(firstUser.getImageUrl()); - secondUser.setLangKey(firstUser.getLangKey()); - secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); - - // Register second (non activated) user - restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().isCreated()); - - Optional testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); - assertThat(testUser2.isPresent()).isFalse(); - - Optional testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2"); - assertThat(testUser3.isPresent()).isTrue(); - - // Duplicate email - with uppercase email address - ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM(); - userWithUpperCaseEmail.setId(firstUser.getId()); - userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3"); - userWithUpperCaseEmail.setPassword(firstUser.getPassword()); - userWithUpperCaseEmail.setFirstName(firstUser.getFirstName()); - userWithUpperCaseEmail.setLastName(firstUser.getLastName()); - userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com"); - userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl()); - userWithUpperCaseEmail.setLangKey(firstUser.getLangKey()); - userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); - - // Register third (not activated) user - restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) - .andExpect(status().isCreated()); - - Optional testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); - assertThat(testUser4.isPresent()).isTrue(); - assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com"); - - testUser4.get().setActivated(true); - userService.updateUser((new UserDTO(testUser4.get()))); - - // Register 4th (already activated) user - restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().is4xxClientError()); - } - - @Test - @Transactional - public void testRegisterAdminIsIgnored() throws Exception { - ManagedUserVM validUser = new ManagedUserVM(); - validUser.setLogin("badguy"); - validUser.setPassword("password"); - validUser.setFirstName("Bad"); - validUser.setLastName("Guy"); - validUser.setEmail("badguy@example.com"); - validUser.setActivated(true); - validUser.setImageUrl("http://placehold.it/50x50"); - validUser.setLangKey(Constants.DEFAULT_LANGUAGE); - validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - - restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(validUser))) - .andExpect(status().isCreated()); - - Optional userDup = userRepository.findOneByLogin("badguy"); - assertThat(userDup.isPresent()).isTrue(); - assertThat(userDup.get().getAuthorities()).hasSize(1) - .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); - } - - @Test - @Transactional - public void testActivateAccount() throws Exception { - final String activationKey = "some activation key"; - User user = new User(); - user.setLogin("activate-account"); - user.setEmail("activate-account@example.com"); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(false); - user.setActivationKey(activationKey); - - userRepository.saveAndFlush(user); - - restMvc.perform(get("/api/activate?key={activationKey}", activationKey)) - .andExpect(status().isOk()); - - user = userRepository.findOneByLogin(user.getLogin()).orElse(null); - assertThat(user.getActivated()).isTrue(); - } - - @Test - @Transactional - public void testActivateAccountWithWrongKey() throws Exception { - restMvc.perform(get("/api/activate?key=wrongActivationKey")) - .andExpect(status().isInternalServerError()); - } - - @Test - @Transactional - @WithMockUser("save-account") - public void testSaveAccount() throws Exception { - User user = new User(); - user.setLogin("save-account"); - user.setEmail("save-account@example.com"); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - - userRepository.saveAndFlush(user); - - UserDTO userDTO = new UserDTO(); - userDTO.setLogin("not-used"); - userDTO.setFirstName("firstname"); - userDTO.setLastName("lastname"); - userDTO.setEmail("save-account@example.com"); - userDTO.setActivated(false); - userDTO.setImageUrl("http://placehold.it/50x50"); - userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); - userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - - restMvc.perform( - post("/api/account") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isOk()); - - User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); - assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); - assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName()); - assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail()); - assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey()); - assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); - assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl()); - assertThat(updatedUser.getActivated()).isEqualTo(true); - assertThat(updatedUser.getAuthorities()).isEmpty(); - } - - @Test - @Transactional - @WithMockUser("save-invalid-email") - public void testSaveInvalidEmail() throws Exception { - User user = new User(); - user.setLogin("save-invalid-email"); - user.setEmail("save-invalid-email@example.com"); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - - userRepository.saveAndFlush(user); - - UserDTO userDTO = new UserDTO(); - userDTO.setLogin("not-used"); - userDTO.setFirstName("firstname"); - userDTO.setLastName("lastname"); - userDTO.setEmail("invalid email"); - userDTO.setActivated(false); - userDTO.setImageUrl("http://placehold.it/50x50"); - userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); - userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - - restMvc.perform( - post("/api/account") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isBadRequest()); - - assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); - } - - @Test - @Transactional - @WithMockUser("save-existing-email") - public void testSaveExistingEmail() throws Exception { - User user = new User(); - user.setLogin("save-existing-email"); - user.setEmail("save-existing-email@example.com"); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - - userRepository.saveAndFlush(user); - - User anotherUser = new User(); - anotherUser.setLogin("save-existing-email2"); - anotherUser.setEmail("save-existing-email2@example.com"); - anotherUser.setPassword(RandomStringUtils.random(60)); - anotherUser.setActivated(true); - - userRepository.saveAndFlush(anotherUser); - - UserDTO userDTO = new UserDTO(); - userDTO.setLogin("not-used"); - userDTO.setFirstName("firstname"); - userDTO.setLastName("lastname"); - userDTO.setEmail("save-existing-email2@example.com"); - userDTO.setActivated(false); - userDTO.setImageUrl("http://placehold.it/50x50"); - userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); - userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - - restMvc.perform( - post("/api/account") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null); - assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com"); - } - - @Test - @Transactional - @WithMockUser("save-existing-email-and-login") - public void testSaveExistingEmailAndLogin() throws Exception { - User user = new User(); - user.setLogin("save-existing-email-and-login"); - user.setEmail("save-existing-email-and-login@example.com"); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - - userRepository.saveAndFlush(user); - - UserDTO userDTO = new UserDTO(); - userDTO.setLogin("not-used"); - userDTO.setFirstName("firstname"); - userDTO.setLastName("lastname"); - userDTO.setEmail("save-existing-email-and-login@example.com"); - userDTO.setActivated(false); - userDTO.setImageUrl("http://placehold.it/50x50"); - userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); - userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - - restMvc.perform( - post("/api/account") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isOk()); - - User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); - assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com"); - } - - @Test - @Transactional - @WithMockUser("change-password-wrong-existing-password") - public void testChangePasswordWrongExistingPassword() throws Exception { - User user = new User(); - String currentPassword = RandomStringUtils.random(60); - user.setPassword(passwordEncoder.encode(currentPassword)); - user.setLogin("change-password-wrong-existing-password"); - user.setEmail("change-password-wrong-existing-password@example.com"); - userRepository.saveAndFlush(user); - - restMvc.perform(post("/api/account/change-password") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password")))) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); - assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse(); - assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue(); - } - - @Test - @Transactional - @WithMockUser("change-password") - public void testChangePassword() throws Exception { - User user = new User(); - String currentPassword = RandomStringUtils.random(60); - user.setPassword(passwordEncoder.encode(currentPassword)); - user.setLogin("change-password"); - user.setEmail("change-password@example.com"); - userRepository.saveAndFlush(user); - - restMvc.perform(post("/api/account/change-password") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password")))) - .andExpect(status().isOk()); - - User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); - assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); - } - - @Test - @Transactional - @WithMockUser("change-password-too-small") - public void testChangePasswordTooSmall() throws Exception { - User user = new User(); - String currentPassword = RandomStringUtils.random(60); - user.setPassword(passwordEncoder.encode(currentPassword)); - user.setLogin("change-password-too-small"); - user.setEmail("change-password-too-small@example.com"); - userRepository.saveAndFlush(user); - - String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); - - restMvc.perform(post("/api/account/change-password") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); - assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); - } - - @Test - @Transactional - @WithMockUser("change-password-too-long") - public void testChangePasswordTooLong() throws Exception { - User user = new User(); - String currentPassword = RandomStringUtils.random(60); - user.setPassword(passwordEncoder.encode(currentPassword)); - user.setLogin("change-password-too-long"); - user.setEmail("change-password-too-long@example.com"); - userRepository.saveAndFlush(user); - - String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); - - restMvc.perform(post("/api/account/change-password") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); - assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); - } - - @Test - @Transactional - @WithMockUser("change-password-empty") - public void testChangePasswordEmpty() throws Exception { - User user = new User(); - String currentPassword = RandomStringUtils.random(60); - user.setPassword(passwordEncoder.encode(currentPassword)); - user.setLogin("change-password-empty"); - user.setEmail("change-password-empty@example.com"); - userRepository.saveAndFlush(user); - - restMvc.perform(post("/api/account/change-password") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); - assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); - } - - @Test - @Transactional - public void testRequestPasswordReset() throws Exception { - User user = new User(); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - user.setLogin("password-reset"); - user.setEmail("password-reset@example.com"); - userRepository.saveAndFlush(user); - - restMvc.perform(post("/api/account/reset-password/init") - .content("password-reset@example.com")) - .andExpect(status().isOk()); - } - - @Test - @Transactional - public void testRequestPasswordResetUpperCaseEmail() throws Exception { - User user = new User(); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - user.setLogin("password-reset"); - user.setEmail("password-reset@example.com"); - userRepository.saveAndFlush(user); - - restMvc.perform(post("/api/account/reset-password/init") - .content("password-reset@EXAMPLE.COM")) - .andExpect(status().isOk()); - } - - @Test - public void testRequestPasswordResetWrongEmail() throws Exception { - restMvc.perform( - post("/api/account/reset-password/init") - .content("password-reset-wrong-email@example.com")) - .andExpect(status().isBadRequest()); - } - - @Test - @Transactional - public void testFinishPasswordReset() throws Exception { - User user = new User(); - user.setPassword(RandomStringUtils.random(60)); - user.setLogin("finish-password-reset"); - user.setEmail("finish-password-reset@example.com"); - user.setResetDate(Instant.now().plusSeconds(60)); - user.setResetKey("reset key"); - userRepository.saveAndFlush(user); - - KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); - keyAndPassword.setKey(user.getResetKey()); - keyAndPassword.setNewPassword("new password"); - - restMvc.perform( - post("/api/account/reset-password/finish") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) - .andExpect(status().isOk()); - - User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); - assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); - } - - @Test - @Transactional - public void testFinishPasswordResetTooSmall() throws Exception { - User user = new User(); - user.setPassword(RandomStringUtils.random(60)); - user.setLogin("finish-password-reset-too-small"); - user.setEmail("finish-password-reset-too-small@example.com"); - user.setResetDate(Instant.now().plusSeconds(60)); - user.setResetKey("reset key too small"); - userRepository.saveAndFlush(user); - - KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); - keyAndPassword.setKey(user.getResetKey()); - keyAndPassword.setNewPassword("foo"); - - restMvc.perform( - post("/api/account/reset-password/finish") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) - .andExpect(status().isBadRequest()); - - User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); - assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse(); - } - - - @Test - @Transactional - public void testFinishPasswordResetWrongKey() throws Exception { - KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); - keyAndPassword.setKey("wrong reset key"); - keyAndPassword.setNewPassword("new password"); - - restMvc.perform( - post("/api/account/reset-password/finish") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) - .andExpect(status().isInternalServerError()); - } -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntegrationTest.java new file mode 100644 index 0000000000..f591b7ecbf --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntegrationTest.java @@ -0,0 +1,818 @@ +package com.baeldung.jhipster5.web.rest; + +import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster5.config.Constants; +import com.baeldung.jhipster5.domain.Authority; +import com.baeldung.jhipster5.domain.User; +import com.baeldung.jhipster5.repository.AuthorityRepository; +import com.baeldung.jhipster5.repository.UserRepository; +import com.baeldung.jhipster5.security.AuthoritiesConstants; +import com.baeldung.jhipster5.service.MailService; +import com.baeldung.jhipster5.service.UserService; +import com.baeldung.jhipster5.service.dto.PasswordChangeDTO; +import com.baeldung.jhipster5.service.dto.UserDTO; +import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; +import com.baeldung.jhipster5.web.rest.vm.KeyAndPasswordVM; +import com.baeldung.jhipster5.web.rest.vm.ManagedUserVM; +import org.apache.commons.lang3.RandomStringUtils; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.security.crypto.password.PasswordEncoder; +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.transaction.annotation.Transactional; + +import java.time.Instant; +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** + * Test class for the AccountResource REST controller. + * + * @see AccountResource + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +public class AccountResourceIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Autowired + private AuthorityRepository authorityRepository; + + @Autowired + private UserService userService; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private HttpMessageConverter[] httpMessageConverters; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Mock + private UserService mockUserService; + + @Mock + private MailService mockMailService; + + private MockMvc restMvc; + + private MockMvc restUserMockMvc; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + doNothing().when(mockMailService).sendActivationEmail(any()); + AccountResource accountResource = + new AccountResource(userRepository, userService, mockMailService); + + AccountResource accountUserMockResource = + new AccountResource(userRepository, mockUserService, mockMailService); + this.restMvc = MockMvcBuilders.standaloneSetup(accountResource) + .setMessageConverters(httpMessageConverters) + .setControllerAdvice(exceptionTranslator) + .build(); + this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource) + .setControllerAdvice(exceptionTranslator) + .build(); + } + + @Test + public void testNonAuthenticatedUser() throws Exception { + restUserMockMvc.perform(get("/api/authenticate") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("")); + } + + @Test + public void testAuthenticatedUser() throws Exception { + restUserMockMvc.perform(get("/api/authenticate") + .with(request -> { + request.setRemoteUser("test"); + return request; + }) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("test")); + } + + @Test + public void testGetExistingAccount() throws Exception { + Set authorities = new HashSet<>(); + Authority authority = new Authority(); + authority.setName(AuthoritiesConstants.ADMIN); + authorities.add(authority); + + User user = new User(); + user.setLogin("test"); + user.setFirstName("john"); + user.setLastName("doe"); + user.setEmail("john.doe@jhipster.com"); + user.setImageUrl("http://placehold.it/50x50"); + user.setLangKey("en"); + user.setAuthorities(authorities); + when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user)); + + restUserMockMvc.perform(get("/api/account") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.login").value("test")) + .andExpect(jsonPath("$.firstName").value("john")) + .andExpect(jsonPath("$.lastName").value("doe")) + .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) + .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) + .andExpect(jsonPath("$.langKey").value("en")) + .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); + } + + @Test + public void testGetUnknownAccount() throws Exception { + when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty()); + + restUserMockMvc.perform(get("/api/account") + .accept(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(status().isInternalServerError()); + } + + @Test + @Transactional + public void testRegisterValid() throws Exception { + ManagedUserVM validUser = new ManagedUserVM(); + validUser.setLogin("test-register-valid"); + validUser.setPassword("password"); + validUser.setFirstName("Alice"); + validUser.setLastName("Test"); + validUser.setEmail("test-register-valid@example.com"); + validUser.setImageUrl("http://placehold.it/50x50"); + validUser.setLangKey(Constants.DEFAULT_LANGUAGE); + validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse(); + + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(validUser))) + .andExpect(status().isCreated()); + + assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue(); + } + + @Test + @Transactional + public void testRegisterInvalidLogin() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("funky-log!n");// <-- invalid + invalidUser.setPassword("password"); + invalidUser.setFirstName("Funky"); + invalidUser.setLastName("One"); + invalidUser.setEmail("funky@example.com"); + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterInvalidEmail() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("bob"); + invalidUser.setPassword("password"); + invalidUser.setFirstName("Bob"); + invalidUser.setLastName("Green"); + invalidUser.setEmail("invalid");// <-- invalid + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional user = userRepository.findOneByLogin("bob"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterInvalidPassword() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("bob"); + invalidUser.setPassword("123");// password with only 3 digits + invalidUser.setFirstName("Bob"); + invalidUser.setLastName("Green"); + invalidUser.setEmail("bob@example.com"); + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional user = userRepository.findOneByLogin("bob"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterNullPassword() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("bob"); + invalidUser.setPassword(null);// invalid null password + invalidUser.setFirstName("Bob"); + invalidUser.setLastName("Green"); + invalidUser.setEmail("bob@example.com"); + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional user = userRepository.findOneByLogin("bob"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterDuplicateLogin() throws Exception { + // First registration + ManagedUserVM firstUser = new ManagedUserVM(); + firstUser.setLogin("alice"); + firstUser.setPassword("password"); + firstUser.setFirstName("Alice"); + firstUser.setLastName("Something"); + firstUser.setEmail("alice@example.com"); + firstUser.setImageUrl("http://placehold.it/50x50"); + firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); + firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Duplicate login, different email + ManagedUserVM secondUser = new ManagedUserVM(); + secondUser.setLogin(firstUser.getLogin()); + secondUser.setPassword(firstUser.getPassword()); + secondUser.setFirstName(firstUser.getFirstName()); + secondUser.setLastName(firstUser.getLastName()); + secondUser.setEmail("alice2@example.com"); + secondUser.setImageUrl(firstUser.getImageUrl()); + secondUser.setLangKey(firstUser.getLangKey()); + secondUser.setCreatedBy(firstUser.getCreatedBy()); + secondUser.setCreatedDate(firstUser.getCreatedDate()); + secondUser.setLastModifiedBy(firstUser.getLastModifiedBy()); + secondUser.setLastModifiedDate(firstUser.getLastModifiedDate()); + secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // First user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(firstUser))) + .andExpect(status().isCreated()); + + // Second (non activated) user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().isCreated()); + + Optional testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); + assertThat(testUser.isPresent()).isTrue(); + testUser.get().setActivated(true); + userRepository.save(testUser.get()); + + // Second (already activated) user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().is4xxClientError()); + } + + @Test + @Transactional + public void testRegisterDuplicateEmail() throws Exception { + // First user + ManagedUserVM firstUser = new ManagedUserVM(); + firstUser.setLogin("test-register-duplicate-email"); + firstUser.setPassword("password"); + firstUser.setFirstName("Alice"); + firstUser.setLastName("Test"); + firstUser.setEmail("test-register-duplicate-email@example.com"); + firstUser.setImageUrl("http://placehold.it/50x50"); + firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); + firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Register first user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(firstUser))) + .andExpect(status().isCreated()); + + Optional testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); + assertThat(testUser1.isPresent()).isTrue(); + + // Duplicate email, different login + ManagedUserVM secondUser = new ManagedUserVM(); + secondUser.setLogin("test-register-duplicate-email-2"); + secondUser.setPassword(firstUser.getPassword()); + secondUser.setFirstName(firstUser.getFirstName()); + secondUser.setLastName(firstUser.getLastName()); + secondUser.setEmail(firstUser.getEmail()); + secondUser.setImageUrl(firstUser.getImageUrl()); + secondUser.setLangKey(firstUser.getLangKey()); + secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // Register second (non activated) user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().isCreated()); + + Optional testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); + assertThat(testUser2.isPresent()).isFalse(); + + Optional testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2"); + assertThat(testUser3.isPresent()).isTrue(); + + // Duplicate email - with uppercase email address + ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM(); + userWithUpperCaseEmail.setId(firstUser.getId()); + userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3"); + userWithUpperCaseEmail.setPassword(firstUser.getPassword()); + userWithUpperCaseEmail.setFirstName(firstUser.getFirstName()); + userWithUpperCaseEmail.setLastName(firstUser.getLastName()); + userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com"); + userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl()); + userWithUpperCaseEmail.setLangKey(firstUser.getLangKey()); + userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // Register third (not activated) user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) + .andExpect(status().isCreated()); + + Optional testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); + assertThat(testUser4.isPresent()).isTrue(); + assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com"); + + testUser4.get().setActivated(true); + userService.updateUser((new UserDTO(testUser4.get()))); + + // Register 4th (already activated) user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().is4xxClientError()); + } + + @Test + @Transactional + public void testRegisterAdminIsIgnored() throws Exception { + ManagedUserVM validUser = new ManagedUserVM(); + validUser.setLogin("badguy"); + validUser.setPassword("password"); + validUser.setFirstName("Bad"); + validUser.setLastName("Guy"); + validUser.setEmail("badguy@example.com"); + validUser.setActivated(true); + validUser.setImageUrl("http://placehold.it/50x50"); + validUser.setLangKey(Constants.DEFAULT_LANGUAGE); + validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(validUser))) + .andExpect(status().isCreated()); + + Optional userDup = userRepository.findOneByLogin("badguy"); + assertThat(userDup.isPresent()).isTrue(); + assertThat(userDup.get().getAuthorities()).hasSize(1) + .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); + } + + @Test + @Transactional + public void testActivateAccount() throws Exception { + final String activationKey = "some activation key"; + User user = new User(); + user.setLogin("activate-account"); + user.setEmail("activate-account@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(false); + user.setActivationKey(activationKey); + + userRepository.saveAndFlush(user); + + restMvc.perform(get("/api/activate?key={activationKey}", activationKey)) + .andExpect(status().isOk()); + + user = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(user.getActivated()).isTrue(); + } + + @Test + @Transactional + public void testActivateAccountWithWrongKey() throws Exception { + restMvc.perform(get("/api/activate?key=wrongActivationKey")) + .andExpect(status().isInternalServerError()); + } + + @Test + @Transactional + @WithMockUser("save-account") + public void testSaveAccount() throws Exception { + User user = new User(); + user.setLogin("save-account"); + user.setEmail("save-account@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + + userRepository.saveAndFlush(user); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-account@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restMvc.perform( + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); + assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName()); + assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail()); + assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey()); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl()); + assertThat(updatedUser.getActivated()).isEqualTo(true); + assertThat(updatedUser.getAuthorities()).isEmpty(); + } + + @Test + @Transactional + @WithMockUser("save-invalid-email") + public void testSaveInvalidEmail() throws Exception { + User user = new User(); + user.setLogin("save-invalid-email"); + user.setEmail("save-invalid-email@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + + userRepository.saveAndFlush(user); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("invalid email"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restMvc.perform( + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isBadRequest()); + + assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); + } + + @Test + @Transactional + @WithMockUser("save-existing-email") + public void testSaveExistingEmail() throws Exception { + User user = new User(); + user.setLogin("save-existing-email"); + user.setEmail("save-existing-email@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("save-existing-email2"); + anotherUser.setEmail("save-existing-email2@example.com"); + anotherUser.setPassword(RandomStringUtils.random(60)); + anotherUser.setActivated(true); + + userRepository.saveAndFlush(anotherUser); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-existing-email2@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restMvc.perform( + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null); + assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com"); + } + + @Test + @Transactional + @WithMockUser("save-existing-email-and-login") + public void testSaveExistingEmailAndLogin() throws Exception { + User user = new User(); + user.setLogin("save-existing-email-and-login"); + user.setEmail("save-existing-email-and-login@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + + userRepository.saveAndFlush(user); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-existing-email-and-login@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restMvc.perform( + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); + assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com"); + } + + @Test + @Transactional + @WithMockUser("change-password-wrong-existing-password") + public void testChangePasswordWrongExistingPassword() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-wrong-existing-password"); + user.setEmail("change-password-wrong-existing-password@example.com"); + userRepository.saveAndFlush(user); + + restMvc.perform(post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password")))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); + assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse(); + assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue(); + } + + @Test + @Transactional + @WithMockUser("change-password") + public void testChangePassword() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password"); + user.setEmail("change-password@example.com"); + userRepository.saveAndFlush(user); + + restMvc.perform(post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password")))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); + assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); + } + + @Test + @Transactional + @WithMockUser("change-password-too-small") + public void testChangePasswordTooSmall() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-too-small"); + user.setEmail("change-password-too-small@example.com"); + userRepository.saveAndFlush(user); + + String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); + + restMvc.perform(post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + } + + @Test + @Transactional + @WithMockUser("change-password-too-long") + public void testChangePasswordTooLong() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-too-long"); + user.setEmail("change-password-too-long@example.com"); + userRepository.saveAndFlush(user); + + String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); + + restMvc.perform(post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + } + + @Test + @Transactional + @WithMockUser("change-password-empty") + public void testChangePasswordEmpty() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-empty"); + user.setEmail("change-password-empty@example.com"); + userRepository.saveAndFlush(user); + + restMvc.perform(post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + } + + @Test + @Transactional + public void testRequestPasswordReset() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setLogin("password-reset"); + user.setEmail("password-reset@example.com"); + userRepository.saveAndFlush(user); + + restMvc.perform(post("/api/account/reset-password/init") + .content("password-reset@example.com")) + .andExpect(status().isOk()); + } + + @Test + @Transactional + public void testRequestPasswordResetUpperCaseEmail() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setLogin("password-reset"); + user.setEmail("password-reset@example.com"); + userRepository.saveAndFlush(user); + + restMvc.perform(post("/api/account/reset-password/init") + .content("password-reset@EXAMPLE.COM")) + .andExpect(status().isOk()); + } + + @Test + public void testRequestPasswordResetWrongEmail() throws Exception { + restMvc.perform( + post("/api/account/reset-password/init") + .content("password-reset-wrong-email@example.com")) + .andExpect(status().isBadRequest()); + } + + @Test + @Transactional + public void testFinishPasswordReset() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setLogin("finish-password-reset"); + user.setEmail("finish-password-reset@example.com"); + user.setResetDate(Instant.now().plusSeconds(60)); + user.setResetKey("reset key"); + userRepository.saveAndFlush(user); + + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey(user.getResetKey()); + keyAndPassword.setNewPassword("new password"); + + restMvc.perform( + post("/api/account/reset-password/finish") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); + } + + @Test + @Transactional + public void testFinishPasswordResetTooSmall() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setLogin("finish-password-reset-too-small"); + user.setEmail("finish-password-reset-too-small@example.com"); + user.setResetDate(Instant.now().plusSeconds(60)); + user.setResetKey("reset key too small"); + userRepository.saveAndFlush(user); + + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey(user.getResetKey()); + keyAndPassword.setNewPassword("foo"); + + restMvc.perform( + post("/api/account/reset-password/finish") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse(); + } + + + @Test + @Transactional + public void testFinishPasswordResetWrongKey() throws Exception { + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey("wrong reset key"); + keyAndPassword.setNewPassword("new password"); + + restMvc.perform( + post("/api/account/reset-password/finish") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + .andExpect(status().isInternalServerError()); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntTest.java deleted file mode 100644 index c3b91ab390..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.baeldung.jhipster5.web.rest; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.config.audit.AuditEventConverter; -import com.baeldung.jhipster5.domain.PersistentAuditEvent; -import com.baeldung.jhipster5.repository.PersistenceAuditEventRepository; -import com.baeldung.jhipster5.service.AuditEventService; -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.boot.test.context.SpringBootTest; -import org.springframework.data.web.PageableHandlerMethodArgumentResolver; -import org.springframework.format.support.FormattingConversionService; -import org.springframework.http.MediaType; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -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.transaction.annotation.Transactional; - -import java.time.Instant; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -/** - * Test class for the AuditResource REST controller. - * - * @see AuditResource - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -@Transactional -public class AuditResourceIntTest { - - private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL"; - private static final String SAMPLE_TYPE = "SAMPLE_TYPE"; - private static final Instant SAMPLE_TIMESTAMP = Instant.parse("2015-08-04T10:11:30Z"); - private static final long SECONDS_PER_DAY = 60 * 60 * 24; - - @Autowired - private PersistenceAuditEventRepository auditEventRepository; - - @Autowired - private AuditEventConverter auditEventConverter; - - @Autowired - private MappingJackson2HttpMessageConverter jacksonMessageConverter; - - @Autowired - private FormattingConversionService formattingConversionService; - - @Autowired - private PageableHandlerMethodArgumentResolver pageableArgumentResolver; - - private PersistentAuditEvent auditEvent; - - private MockMvc restAuditMockMvc; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - AuditEventService auditEventService = - new AuditEventService(auditEventRepository, auditEventConverter); - AuditResource auditResource = new AuditResource(auditEventService); - this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setConversionService(formattingConversionService) - .setMessageConverters(jacksonMessageConverter).build(); - } - - @Before - public void initTest() { - auditEventRepository.deleteAll(); - auditEvent = new PersistentAuditEvent(); - auditEvent.setAuditEventType(SAMPLE_TYPE); - auditEvent.setPrincipal(SAMPLE_PRINCIPAL); - auditEvent.setAuditEventDate(SAMPLE_TIMESTAMP); - } - - @Test - public void getAllAudits() throws Exception { - // Initialize the database - auditEventRepository.save(auditEvent); - - // Get all the audits - restAuditMockMvc.perform(get("/management/audits")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); - } - - @Test - public void getAudit() throws Exception { - // Initialize the database - auditEventRepository.save(auditEvent); - - // Get the audit - restAuditMockMvc.perform(get("/management/audits/{id}", auditEvent.getId())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL)); - } - - @Test - public void getAuditsByDate() throws Exception { - // Initialize the database - auditEventRepository.save(auditEvent); - - // Generate dates for selecting audits by date, making sure the period will contain the audit - String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); - String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); - - // Get the audit - restAuditMockMvc.perform(get("/management/audits?fromDate="+fromDate+"&toDate="+toDate)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); - } - - @Test - public void getNonExistingAuditsByDate() throws Exception { - // Initialize the database - auditEventRepository.save(auditEvent); - - // Generate dates for selecting audits by date, making sure the period will not contain the sample audit - String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0, 10); - String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); - - // Query audits but expect no results - restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(header().string("X-Total-Count", "0")); - } - - @Test - public void getNonExistingAudit() throws Exception { - // Get the audit - restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); - } - - @Test - @Transactional - public void testPersistentAuditEventEquals() throws Exception { - TestUtil.equalsVerifier(PersistentAuditEvent.class); - PersistentAuditEvent auditEvent1 = new PersistentAuditEvent(); - auditEvent1.setId(1L); - PersistentAuditEvent auditEvent2 = new PersistentAuditEvent(); - auditEvent2.setId(auditEvent1.getId()); - assertThat(auditEvent1).isEqualTo(auditEvent2); - auditEvent2.setId(2L); - assertThat(auditEvent1).isNotEqualTo(auditEvent2); - auditEvent1.setId(null); - assertThat(auditEvent1).isNotEqualTo(auditEvent2); - } -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntegrationTest.java new file mode 100644 index 0000000000..05d8f9d503 --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntegrationTest.java @@ -0,0 +1,162 @@ +package com.baeldung.jhipster5.web.rest; + +import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster5.config.audit.AuditEventConverter; +import com.baeldung.jhipster5.domain.PersistentAuditEvent; +import com.baeldung.jhipster5.repository.PersistenceAuditEventRepository; +import com.baeldung.jhipster5.service.AuditEventService; +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.boot.test.context.SpringBootTest; +import org.springframework.data.web.PageableHandlerMethodArgumentResolver; +import org.springframework.format.support.FormattingConversionService; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +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.transaction.annotation.Transactional; + +import java.time.Instant; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** + * Test class for the AuditResource REST controller. + * + * @see AuditResource + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +@Transactional +public class AuditResourceIntegrationTest { + + private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL"; + private static final String SAMPLE_TYPE = "SAMPLE_TYPE"; + private static final Instant SAMPLE_TIMESTAMP = Instant.parse("2015-08-04T10:11:30Z"); + private static final long SECONDS_PER_DAY = 60 * 60 * 24; + + @Autowired + private PersistenceAuditEventRepository auditEventRepository; + + @Autowired + private AuditEventConverter auditEventConverter; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private FormattingConversionService formattingConversionService; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + private PersistentAuditEvent auditEvent; + + private MockMvc restAuditMockMvc; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + AuditEventService auditEventService = + new AuditEventService(auditEventRepository, auditEventConverter); + AuditResource auditResource = new AuditResource(auditEventService); + this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setConversionService(formattingConversionService) + .setMessageConverters(jacksonMessageConverter).build(); + } + + @Before + public void initTest() { + auditEventRepository.deleteAll(); + auditEvent = new PersistentAuditEvent(); + auditEvent.setAuditEventType(SAMPLE_TYPE); + auditEvent.setPrincipal(SAMPLE_PRINCIPAL); + auditEvent.setAuditEventDate(SAMPLE_TIMESTAMP); + } + + @Test + public void getAllAudits() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Get all the audits + restAuditMockMvc.perform(get("/management/audits")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); + } + + @Test + public void getAudit() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Get the audit + restAuditMockMvc.perform(get("/management/audits/{id}", auditEvent.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL)); + } + + @Test + public void getAuditsByDate() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Generate dates for selecting audits by date, making sure the period will contain the audit + String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); + String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); + + // Get the audit + restAuditMockMvc.perform(get("/management/audits?fromDate="+fromDate+"&toDate="+toDate)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); + } + + @Test + public void getNonExistingAuditsByDate() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Generate dates for selecting audits by date, making sure the period will not contain the sample audit + String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0, 10); + String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); + + // Query audits but expect no results + restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(header().string("X-Total-Count", "0")); + } + + @Test + public void getNonExistingAudit() throws Exception { + // Get the audit + restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void testPersistentAuditEventEquals() throws Exception { + TestUtil.equalsVerifier(PersistentAuditEvent.class); + PersistentAuditEvent auditEvent1 = new PersistentAuditEvent(); + auditEvent1.setId(1L); + PersistentAuditEvent auditEvent2 = new PersistentAuditEvent(); + auditEvent2.setId(auditEvent1.getId()); + assertThat(auditEvent1).isEqualTo(auditEvent2); + auditEvent2.setId(2L); + assertThat(auditEvent1).isNotEqualTo(auditEvent2); + auditEvent1.setId(null); + assertThat(auditEvent1).isNotEqualTo(auditEvent2); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntTest.java deleted file mode 100644 index ef8f27ceea..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntTest.java +++ /dev/null @@ -1,416 +0,0 @@ -package com.baeldung.jhipster5.web.rest; - -import com.baeldung.jhipster5.BookstoreApp; - -import com.baeldung.jhipster5.domain.Book; -import com.baeldung.jhipster5.repository.BookRepository; -import com.baeldung.jhipster5.service.BookService; -import com.baeldung.jhipster5.service.dto.BookDTO; -import com.baeldung.jhipster5.service.mapper.BookMapper; -import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; - -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.boot.test.context.SpringBootTest; -import org.springframework.data.web.PageableHandlerMethodArgumentResolver; -import org.springframework.http.MediaType; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -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.transaction.annotation.Transactional; -import org.springframework.validation.Validator; - -import javax.persistence.EntityManager; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.List; - - -import static com.baeldung.jhipster5.web.rest.TestUtil.createFormattingConversionService; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -/** - * Test class for the BookResource REST controller. - * - * @see BookResource - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -public class BookResourceIntTest { - - private static final String DEFAULT_TITLE = "AAAAAAAAAA"; - private static final String UPDATED_TITLE = "BBBBBBBBBB"; - - private static final String DEFAULT_AUTHOR = "AAAAAAAAAA"; - private static final String UPDATED_AUTHOR = "BBBBBBBBBB"; - - private static final LocalDate DEFAULT_PUBLISHED = LocalDate.ofEpochDay(0L); - private static final LocalDate UPDATED_PUBLISHED = LocalDate.now(ZoneId.systemDefault()); - - private static final Integer DEFAULT_QUANTITY = 0; - private static final Integer UPDATED_QUANTITY = 1; - - private static final Double DEFAULT_PRICE = 0D; - private static final Double UPDATED_PRICE = 1D; - - @Autowired - private BookRepository bookRepository; - - @Autowired - private BookMapper bookMapper; - - @Autowired - private BookService bookService; - - @Autowired - private MappingJackson2HttpMessageConverter jacksonMessageConverter; - - @Autowired - private PageableHandlerMethodArgumentResolver pageableArgumentResolver; - - @Autowired - private ExceptionTranslator exceptionTranslator; - - @Autowired - private EntityManager em; - - @Autowired - private Validator validator; - - private MockMvc restBookMockMvc; - - private Book book; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - final BookResource bookResource = new BookResource(bookService); - this.restBookMockMvc = MockMvcBuilders.standaloneSetup(bookResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setConversionService(createFormattingConversionService()) - .setMessageConverters(jacksonMessageConverter) - .setValidator(validator).build(); - } - - /** - * Create an entity for this test. - * - * This is a static method, as tests for other entities might also need it, - * if they test an entity which requires the current entity. - */ - public static Book createEntity(EntityManager em) { - Book book = new Book() - .title(DEFAULT_TITLE) - .author(DEFAULT_AUTHOR) - .published(DEFAULT_PUBLISHED) - .quantity(DEFAULT_QUANTITY) - .price(DEFAULT_PRICE); - return book; - } - - @Before - public void initTest() { - book = createEntity(em); - } - - @Test - @Transactional - public void createBook() throws Exception { - int databaseSizeBeforeCreate = bookRepository.findAll().size(); - - // Create the Book - BookDTO bookDTO = bookMapper.toDto(book); - restBookMockMvc.perform(post("/api/books") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(bookDTO))) - .andExpect(status().isCreated()); - - // Validate the Book in the database - List bookList = bookRepository.findAll(); - assertThat(bookList).hasSize(databaseSizeBeforeCreate + 1); - Book testBook = bookList.get(bookList.size() - 1); - assertThat(testBook.getTitle()).isEqualTo(DEFAULT_TITLE); - assertThat(testBook.getAuthor()).isEqualTo(DEFAULT_AUTHOR); - assertThat(testBook.getPublished()).isEqualTo(DEFAULT_PUBLISHED); - assertThat(testBook.getQuantity()).isEqualTo(DEFAULT_QUANTITY); - assertThat(testBook.getPrice()).isEqualTo(DEFAULT_PRICE); - } - - @Test - @Transactional - public void createBookWithExistingId() throws Exception { - int databaseSizeBeforeCreate = bookRepository.findAll().size(); - - // Create the Book with an existing ID - book.setId(1L); - BookDTO bookDTO = bookMapper.toDto(book); - - // An entity with an existing ID cannot be created, so this API call must fail - restBookMockMvc.perform(post("/api/books") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(bookDTO))) - .andExpect(status().isBadRequest()); - - // Validate the Book in the database - List bookList = bookRepository.findAll(); - assertThat(bookList).hasSize(databaseSizeBeforeCreate); - } - - @Test - @Transactional - public void checkTitleIsRequired() throws Exception { - int databaseSizeBeforeTest = bookRepository.findAll().size(); - // set the field null - book.setTitle(null); - - // Create the Book, which fails. - BookDTO bookDTO = bookMapper.toDto(book); - - restBookMockMvc.perform(post("/api/books") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(bookDTO))) - .andExpect(status().isBadRequest()); - - List bookList = bookRepository.findAll(); - assertThat(bookList).hasSize(databaseSizeBeforeTest); - } - - @Test - @Transactional - public void checkAuthorIsRequired() throws Exception { - int databaseSizeBeforeTest = bookRepository.findAll().size(); - // set the field null - book.setAuthor(null); - - // Create the Book, which fails. - BookDTO bookDTO = bookMapper.toDto(book); - - restBookMockMvc.perform(post("/api/books") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(bookDTO))) - .andExpect(status().isBadRequest()); - - List bookList = bookRepository.findAll(); - assertThat(bookList).hasSize(databaseSizeBeforeTest); - } - - @Test - @Transactional - public void checkPublishedIsRequired() throws Exception { - int databaseSizeBeforeTest = bookRepository.findAll().size(); - // set the field null - book.setPublished(null); - - // Create the Book, which fails. - BookDTO bookDTO = bookMapper.toDto(book); - - restBookMockMvc.perform(post("/api/books") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(bookDTO))) - .andExpect(status().isBadRequest()); - - List bookList = bookRepository.findAll(); - assertThat(bookList).hasSize(databaseSizeBeforeTest); - } - - @Test - @Transactional - public void checkQuantityIsRequired() throws Exception { - int databaseSizeBeforeTest = bookRepository.findAll().size(); - // set the field null - book.setQuantity(null); - - // Create the Book, which fails. - BookDTO bookDTO = bookMapper.toDto(book); - - restBookMockMvc.perform(post("/api/books") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(bookDTO))) - .andExpect(status().isBadRequest()); - - List bookList = bookRepository.findAll(); - assertThat(bookList).hasSize(databaseSizeBeforeTest); - } - - @Test - @Transactional - public void checkPriceIsRequired() throws Exception { - int databaseSizeBeforeTest = bookRepository.findAll().size(); - // set the field null - book.setPrice(null); - - // Create the Book, which fails. - BookDTO bookDTO = bookMapper.toDto(book); - - restBookMockMvc.perform(post("/api/books") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(bookDTO))) - .andExpect(status().isBadRequest()); - - List bookList = bookRepository.findAll(); - assertThat(bookList).hasSize(databaseSizeBeforeTest); - } - - @Test - @Transactional - public void getAllBooks() throws Exception { - // Initialize the database - bookRepository.saveAndFlush(book); - - // Get all the bookList - restBookMockMvc.perform(get("/api/books?sort=id,desc")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].id").value(hasItem(book.getId().intValue()))) - .andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE.toString()))) - .andExpect(jsonPath("$.[*].author").value(hasItem(DEFAULT_AUTHOR.toString()))) - .andExpect(jsonPath("$.[*].published").value(hasItem(DEFAULT_PUBLISHED.toString()))) - .andExpect(jsonPath("$.[*].quantity").value(hasItem(DEFAULT_QUANTITY))) - .andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.doubleValue()))); - } - - @Test - @Transactional - public void getBook() throws Exception { - // Initialize the database - bookRepository.saveAndFlush(book); - - // Get the book - restBookMockMvc.perform(get("/api/books/{id}", book.getId())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.id").value(book.getId().intValue())) - .andExpect(jsonPath("$.title").value(DEFAULT_TITLE.toString())) - .andExpect(jsonPath("$.author").value(DEFAULT_AUTHOR.toString())) - .andExpect(jsonPath("$.published").value(DEFAULT_PUBLISHED.toString())) - .andExpect(jsonPath("$.quantity").value(DEFAULT_QUANTITY)) - .andExpect(jsonPath("$.price").value(DEFAULT_PRICE.doubleValue())); - } - - @Test - @Transactional - public void getNonExistingBook() throws Exception { - // Get the book - restBookMockMvc.perform(get("/api/books/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); - } - - @Test - @Transactional - public void updateBook() throws Exception { - // Initialize the database - bookRepository.saveAndFlush(book); - - int databaseSizeBeforeUpdate = bookRepository.findAll().size(); - - // Update the book - Book updatedBook = bookRepository.findById(book.getId()).get(); - // Disconnect from session so that the updates on updatedBook are not directly saved in db - em.detach(updatedBook); - updatedBook - .title(UPDATED_TITLE) - .author(UPDATED_AUTHOR) - .published(UPDATED_PUBLISHED) - .quantity(UPDATED_QUANTITY) - .price(UPDATED_PRICE); - BookDTO bookDTO = bookMapper.toDto(updatedBook); - - restBookMockMvc.perform(put("/api/books") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(bookDTO))) - .andExpect(status().isOk()); - - // Validate the Book in the database - List bookList = bookRepository.findAll(); - assertThat(bookList).hasSize(databaseSizeBeforeUpdate); - Book testBook = bookList.get(bookList.size() - 1); - assertThat(testBook.getTitle()).isEqualTo(UPDATED_TITLE); - assertThat(testBook.getAuthor()).isEqualTo(UPDATED_AUTHOR); - assertThat(testBook.getPublished()).isEqualTo(UPDATED_PUBLISHED); - assertThat(testBook.getQuantity()).isEqualTo(UPDATED_QUANTITY); - assertThat(testBook.getPrice()).isEqualTo(UPDATED_PRICE); - } - - @Test - @Transactional - public void updateNonExistingBook() throws Exception { - int databaseSizeBeforeUpdate = bookRepository.findAll().size(); - - // Create the Book - BookDTO bookDTO = bookMapper.toDto(book); - - // If the entity doesn't have an ID, it will throw BadRequestAlertException - restBookMockMvc.perform(put("/api/books") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(bookDTO))) - .andExpect(status().isBadRequest()); - - // Validate the Book in the database - List bookList = bookRepository.findAll(); - assertThat(bookList).hasSize(databaseSizeBeforeUpdate); - } - - @Test - @Transactional - public void deleteBook() throws Exception { - // Initialize the database - bookRepository.saveAndFlush(book); - - int databaseSizeBeforeDelete = bookRepository.findAll().size(); - - // Delete the book - restBookMockMvc.perform(delete("/api/books/{id}", book.getId()) - .accept(TestUtil.APPLICATION_JSON_UTF8)) - .andExpect(status().isOk()); - - // Validate the database is empty - List bookList = bookRepository.findAll(); - assertThat(bookList).hasSize(databaseSizeBeforeDelete - 1); - } - - @Test - @Transactional - public void equalsVerifier() throws Exception { - TestUtil.equalsVerifier(Book.class); - Book book1 = new Book(); - book1.setId(1L); - Book book2 = new Book(); - book2.setId(book1.getId()); - assertThat(book1).isEqualTo(book2); - book2.setId(2L); - assertThat(book1).isNotEqualTo(book2); - book1.setId(null); - assertThat(book1).isNotEqualTo(book2); - } - - @Test - @Transactional - public void dtoEqualsVerifier() throws Exception { - TestUtil.equalsVerifier(BookDTO.class); - BookDTO bookDTO1 = new BookDTO(); - bookDTO1.setId(1L); - BookDTO bookDTO2 = new BookDTO(); - assertThat(bookDTO1).isNotEqualTo(bookDTO2); - bookDTO2.setId(bookDTO1.getId()); - assertThat(bookDTO1).isEqualTo(bookDTO2); - bookDTO2.setId(2L); - assertThat(bookDTO1).isNotEqualTo(bookDTO2); - bookDTO1.setId(null); - assertThat(bookDTO1).isNotEqualTo(bookDTO2); - } - - @Test - @Transactional - public void testEntityFromId() { - assertThat(bookMapper.fromId(42L).getId()).isEqualTo(42); - assertThat(bookMapper.fromId(null)).isNull(); - } -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntegrationTest.java new file mode 100644 index 0000000000..4f5cb25cdb --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntegrationTest.java @@ -0,0 +1,416 @@ +package com.baeldung.jhipster5.web.rest; + +import com.baeldung.jhipster5.BookstoreApp; + +import com.baeldung.jhipster5.domain.Book; +import com.baeldung.jhipster5.repository.BookRepository; +import com.baeldung.jhipster5.service.BookService; +import com.baeldung.jhipster5.service.dto.BookDTO; +import com.baeldung.jhipster5.service.mapper.BookMapper; +import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; + +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.boot.test.context.SpringBootTest; +import org.springframework.data.web.PageableHandlerMethodArgumentResolver; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +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.transaction.annotation.Transactional; +import org.springframework.validation.Validator; + +import javax.persistence.EntityManager; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.List; + + +import static com.baeldung.jhipster5.web.rest.TestUtil.createFormattingConversionService; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** + * Test class for the BookResource REST controller. + * + * @see BookResource + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +public class BookResourceIntegrationTest { + + private static final String DEFAULT_TITLE = "AAAAAAAAAA"; + private static final String UPDATED_TITLE = "BBBBBBBBBB"; + + private static final String DEFAULT_AUTHOR = "AAAAAAAAAA"; + private static final String UPDATED_AUTHOR = "BBBBBBBBBB"; + + private static final LocalDate DEFAULT_PUBLISHED = LocalDate.ofEpochDay(0L); + private static final LocalDate UPDATED_PUBLISHED = LocalDate.now(ZoneId.systemDefault()); + + private static final Integer DEFAULT_QUANTITY = 0; + private static final Integer UPDATED_QUANTITY = 1; + + private static final Double DEFAULT_PRICE = 0D; + private static final Double UPDATED_PRICE = 1D; + + @Autowired + private BookRepository bookRepository; + + @Autowired + private BookMapper bookMapper; + + @Autowired + private BookService bookService; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restBookMockMvc; + + private Book book; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + final BookResource bookResource = new BookResource(bookService); + this.restBookMockMvc = MockMvcBuilders.standaloneSetup(bookResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .setValidator(validator).build(); + } + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Book createEntity(EntityManager em) { + Book book = new Book() + .title(DEFAULT_TITLE) + .author(DEFAULT_AUTHOR) + .published(DEFAULT_PUBLISHED) + .quantity(DEFAULT_QUANTITY) + .price(DEFAULT_PRICE); + return book; + } + + @Before + public void initTest() { + book = createEntity(em); + } + + @Test + @Transactional + public void createBook() throws Exception { + int databaseSizeBeforeCreate = bookRepository.findAll().size(); + + // Create the Book + BookDTO bookDTO = bookMapper.toDto(book); + restBookMockMvc.perform(post("/api/books") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(bookDTO))) + .andExpect(status().isCreated()); + + // Validate the Book in the database + List bookList = bookRepository.findAll(); + assertThat(bookList).hasSize(databaseSizeBeforeCreate + 1); + Book testBook = bookList.get(bookList.size() - 1); + assertThat(testBook.getTitle()).isEqualTo(DEFAULT_TITLE); + assertThat(testBook.getAuthor()).isEqualTo(DEFAULT_AUTHOR); + assertThat(testBook.getPublished()).isEqualTo(DEFAULT_PUBLISHED); + assertThat(testBook.getQuantity()).isEqualTo(DEFAULT_QUANTITY); + assertThat(testBook.getPrice()).isEqualTo(DEFAULT_PRICE); + } + + @Test + @Transactional + public void createBookWithExistingId() throws Exception { + int databaseSizeBeforeCreate = bookRepository.findAll().size(); + + // Create the Book with an existing ID + book.setId(1L); + BookDTO bookDTO = bookMapper.toDto(book); + + // An entity with an existing ID cannot be created, so this API call must fail + restBookMockMvc.perform(post("/api/books") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(bookDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Book in the database + List bookList = bookRepository.findAll(); + assertThat(bookList).hasSize(databaseSizeBeforeCreate); + } + + @Test + @Transactional + public void checkTitleIsRequired() throws Exception { + int databaseSizeBeforeTest = bookRepository.findAll().size(); + // set the field null + book.setTitle(null); + + // Create the Book, which fails. + BookDTO bookDTO = bookMapper.toDto(book); + + restBookMockMvc.perform(post("/api/books") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(bookDTO))) + .andExpect(status().isBadRequest()); + + List bookList = bookRepository.findAll(); + assertThat(bookList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void checkAuthorIsRequired() throws Exception { + int databaseSizeBeforeTest = bookRepository.findAll().size(); + // set the field null + book.setAuthor(null); + + // Create the Book, which fails. + BookDTO bookDTO = bookMapper.toDto(book); + + restBookMockMvc.perform(post("/api/books") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(bookDTO))) + .andExpect(status().isBadRequest()); + + List bookList = bookRepository.findAll(); + assertThat(bookList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void checkPublishedIsRequired() throws Exception { + int databaseSizeBeforeTest = bookRepository.findAll().size(); + // set the field null + book.setPublished(null); + + // Create the Book, which fails. + BookDTO bookDTO = bookMapper.toDto(book); + + restBookMockMvc.perform(post("/api/books") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(bookDTO))) + .andExpect(status().isBadRequest()); + + List bookList = bookRepository.findAll(); + assertThat(bookList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void checkQuantityIsRequired() throws Exception { + int databaseSizeBeforeTest = bookRepository.findAll().size(); + // set the field null + book.setQuantity(null); + + // Create the Book, which fails. + BookDTO bookDTO = bookMapper.toDto(book); + + restBookMockMvc.perform(post("/api/books") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(bookDTO))) + .andExpect(status().isBadRequest()); + + List bookList = bookRepository.findAll(); + assertThat(bookList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void checkPriceIsRequired() throws Exception { + int databaseSizeBeforeTest = bookRepository.findAll().size(); + // set the field null + book.setPrice(null); + + // Create the Book, which fails. + BookDTO bookDTO = bookMapper.toDto(book); + + restBookMockMvc.perform(post("/api/books") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(bookDTO))) + .andExpect(status().isBadRequest()); + + List bookList = bookRepository.findAll(); + assertThat(bookList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void getAllBooks() throws Exception { + // Initialize the database + bookRepository.saveAndFlush(book); + + // Get all the bookList + restBookMockMvc.perform(get("/api/books?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(book.getId().intValue()))) + .andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE.toString()))) + .andExpect(jsonPath("$.[*].author").value(hasItem(DEFAULT_AUTHOR.toString()))) + .andExpect(jsonPath("$.[*].published").value(hasItem(DEFAULT_PUBLISHED.toString()))) + .andExpect(jsonPath("$.[*].quantity").value(hasItem(DEFAULT_QUANTITY))) + .andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.doubleValue()))); + } + + @Test + @Transactional + public void getBook() throws Exception { + // Initialize the database + bookRepository.saveAndFlush(book); + + // Get the book + restBookMockMvc.perform(get("/api/books/{id}", book.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(book.getId().intValue())) + .andExpect(jsonPath("$.title").value(DEFAULT_TITLE.toString())) + .andExpect(jsonPath("$.author").value(DEFAULT_AUTHOR.toString())) + .andExpect(jsonPath("$.published").value(DEFAULT_PUBLISHED.toString())) + .andExpect(jsonPath("$.quantity").value(DEFAULT_QUANTITY)) + .andExpect(jsonPath("$.price").value(DEFAULT_PRICE.doubleValue())); + } + + @Test + @Transactional + public void getNonExistingBook() throws Exception { + // Get the book + restBookMockMvc.perform(get("/api/books/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateBook() throws Exception { + // Initialize the database + bookRepository.saveAndFlush(book); + + int databaseSizeBeforeUpdate = bookRepository.findAll().size(); + + // Update the book + Book updatedBook = bookRepository.findById(book.getId()).get(); + // Disconnect from session so that the updates on updatedBook are not directly saved in db + em.detach(updatedBook); + updatedBook + .title(UPDATED_TITLE) + .author(UPDATED_AUTHOR) + .published(UPDATED_PUBLISHED) + .quantity(UPDATED_QUANTITY) + .price(UPDATED_PRICE); + BookDTO bookDTO = bookMapper.toDto(updatedBook); + + restBookMockMvc.perform(put("/api/books") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(bookDTO))) + .andExpect(status().isOk()); + + // Validate the Book in the database + List bookList = bookRepository.findAll(); + assertThat(bookList).hasSize(databaseSizeBeforeUpdate); + Book testBook = bookList.get(bookList.size() - 1); + assertThat(testBook.getTitle()).isEqualTo(UPDATED_TITLE); + assertThat(testBook.getAuthor()).isEqualTo(UPDATED_AUTHOR); + assertThat(testBook.getPublished()).isEqualTo(UPDATED_PUBLISHED); + assertThat(testBook.getQuantity()).isEqualTo(UPDATED_QUANTITY); + assertThat(testBook.getPrice()).isEqualTo(UPDATED_PRICE); + } + + @Test + @Transactional + public void updateNonExistingBook() throws Exception { + int databaseSizeBeforeUpdate = bookRepository.findAll().size(); + + // Create the Book + BookDTO bookDTO = bookMapper.toDto(book); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restBookMockMvc.perform(put("/api/books") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(bookDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Book in the database + List bookList = bookRepository.findAll(); + assertThat(bookList).hasSize(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + public void deleteBook() throws Exception { + // Initialize the database + bookRepository.saveAndFlush(book); + + int databaseSizeBeforeDelete = bookRepository.findAll().size(); + + // Delete the book + restBookMockMvc.perform(delete("/api/books/{id}", book.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isOk()); + + // Validate the database is empty + List bookList = bookRepository.findAll(); + assertThat(bookList).hasSize(databaseSizeBeforeDelete - 1); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Book.class); + Book book1 = new Book(); + book1.setId(1L); + Book book2 = new Book(); + book2.setId(book1.getId()); + assertThat(book1).isEqualTo(book2); + book2.setId(2L); + assertThat(book1).isNotEqualTo(book2); + book1.setId(null); + assertThat(book1).isNotEqualTo(book2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(BookDTO.class); + BookDTO bookDTO1 = new BookDTO(); + bookDTO1.setId(1L); + BookDTO bookDTO2 = new BookDTO(); + assertThat(bookDTO1).isNotEqualTo(bookDTO2); + bookDTO2.setId(bookDTO1.getId()); + assertThat(bookDTO1).isEqualTo(bookDTO2); + bookDTO2.setId(2L); + assertThat(bookDTO1).isNotEqualTo(bookDTO2); + bookDTO1.setId(null); + assertThat(bookDTO1).isNotEqualTo(bookDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(bookMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(bookMapper.fromId(null)).isNull(); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntTest.java deleted file mode 100644 index 62f7f3f17c..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.baeldung.jhipster5.web.rest; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.web.rest.vm.LoggerVM; -import ch.qos.logback.classic.AsyncAppender; -import ch.qos.logback.classic.LoggerContext; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.LoggerFactory; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * Test class for the LogsResource REST controller. - * - * @see LogsResource - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -public class LogsResourceIntTest { - - private MockMvc restLogsMockMvc; - - @Before - public void setup() { - LogsResource logsResource = new LogsResource(); - this.restLogsMockMvc = MockMvcBuilders - .standaloneSetup(logsResource) - .build(); - } - - @Test - public void getAllLogs() throws Exception { - restLogsMockMvc.perform(get("/management/logs")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)); - } - - @Test - public void changeLogs() throws Exception { - LoggerVM logger = new LoggerVM(); - logger.setLevel("INFO"); - logger.setName("ROOT"); - - restLogsMockMvc.perform(put("/management/logs") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(logger))) - .andExpect(status().isNoContent()); - } - - @Test - public void testLogstashAppender() { - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - assertThat(context.getLogger("ROOT").getAppender("ASYNC_LOGSTASH")).isInstanceOf(AsyncAppender.class); - } -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntegrationTest.java new file mode 100644 index 0000000000..b045f52f87 --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntegrationTest.java @@ -0,0 +1,66 @@ +package com.baeldung.jhipster5.web.rest; + +import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster5.web.rest.vm.LoggerVM; +import ch.qos.logback.classic.AsyncAppender; +import ch.qos.logback.classic.LoggerContext; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.LoggerFactory; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Test class for the LogsResource REST controller. + * + * @see LogsResource + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +public class LogsResourceIntegrationTest { + + private MockMvc restLogsMockMvc; + + @Before + public void setup() { + LogsResource logsResource = new LogsResource(); + this.restLogsMockMvc = MockMvcBuilders + .standaloneSetup(logsResource) + .build(); + } + + @Test + public void getAllLogs() throws Exception { + restLogsMockMvc.perform(get("/management/logs")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void changeLogs() throws Exception { + LoggerVM logger = new LoggerVM(); + logger.setLevel("INFO"); + logger.setName("ROOT"); + + restLogsMockMvc.perform(put("/management/logs") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(logger))) + .andExpect(status().isNoContent()); + } + + @Test + public void testLogstashAppender() { + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + assertThat(context.getLogger("ROOT").getAppender("ASYNC_LOGSTASH")).isInstanceOf(AsyncAppender.class); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntTest.java deleted file mode 100644 index 3886710438..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.baeldung.jhipster5.web.rest; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.UserRepository; -import com.baeldung.jhipster5.security.jwt.TokenProvider; -import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; -import com.baeldung.jhipster5.web.rest.vm.LoginVM; -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.security.authentication.AuthenticationManager; -import org.springframework.security.crypto.password.PasswordEncoder; -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.transaction.annotation.Transactional; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.isEmptyString; -import static org.hamcrest.Matchers.not; - -/** - * Test class for the UserJWTController REST controller. - * - * @see UserJWTController - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -public class UserJWTControllerIntTest { - - @Autowired - private TokenProvider tokenProvider; - - @Autowired - private AuthenticationManager authenticationManager; - - @Autowired - private UserRepository userRepository; - - @Autowired - private PasswordEncoder passwordEncoder; - - @Autowired - private ExceptionTranslator exceptionTranslator; - - private MockMvc mockMvc; - - @Before - public void setup() { - UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager); - this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController) - .setControllerAdvice(exceptionTranslator) - .build(); - } - - @Test - @Transactional - public void testAuthorize() throws Exception { - User user = new User(); - user.setLogin("user-jwt-controller"); - user.setEmail("user-jwt-controller@example.com"); - user.setActivated(true); - user.setPassword(passwordEncoder.encode("test")); - - userRepository.saveAndFlush(user); - - LoginVM login = new LoginVM(); - login.setUsername("user-jwt-controller"); - login.setPassword("test"); - mockMvc.perform(post("/api/authenticate") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(login))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.id_token").isString()) - .andExpect(jsonPath("$.id_token").isNotEmpty()) - .andExpect(header().string("Authorization", not(nullValue()))) - .andExpect(header().string("Authorization", not(isEmptyString()))); - } - - @Test - @Transactional - public void testAuthorizeWithRememberMe() throws Exception { - User user = new User(); - user.setLogin("user-jwt-controller-remember-me"); - user.setEmail("user-jwt-controller-remember-me@example.com"); - user.setActivated(true); - user.setPassword(passwordEncoder.encode("test")); - - userRepository.saveAndFlush(user); - - LoginVM login = new LoginVM(); - login.setUsername("user-jwt-controller-remember-me"); - login.setPassword("test"); - login.setRememberMe(true); - mockMvc.perform(post("/api/authenticate") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(login))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.id_token").isString()) - .andExpect(jsonPath("$.id_token").isNotEmpty()) - .andExpect(header().string("Authorization", not(nullValue()))) - .andExpect(header().string("Authorization", not(isEmptyString()))); - } - - @Test - @Transactional - public void testAuthorizeFails() throws Exception { - LoginVM login = new LoginVM(); - login.setUsername("wrong-user"); - login.setPassword("wrong password"); - mockMvc.perform(post("/api/authenticate") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(login))) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.id_token").doesNotExist()) - .andExpect(header().doesNotExist("Authorization")); - } -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntegrationTest.java new file mode 100644 index 0000000000..7cfc0e19fc --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntegrationTest.java @@ -0,0 +1,125 @@ +package com.baeldung.jhipster5.web.rest; + +import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster5.domain.User; +import com.baeldung.jhipster5.repository.UserRepository; +import com.baeldung.jhipster5.security.jwt.TokenProvider; +import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; +import com.baeldung.jhipster5.web.rest.vm.LoginVM; +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.security.authentication.AuthenticationManager; +import org.springframework.security.crypto.password.PasswordEncoder; +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.transaction.annotation.Transactional; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +/** + * Test class for the UserJWTController REST controller. + * + * @see UserJWTController + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +public class UserJWTControllerIntegrationTest { + + @Autowired + private TokenProvider tokenProvider; + + @Autowired + private AuthenticationManager authenticationManager; + + @Autowired + private UserRepository userRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + private MockMvc mockMvc; + + @Before + public void setup() { + UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager); + this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController) + .setControllerAdvice(exceptionTranslator) + .build(); + } + + @Test + @Transactional + public void testAuthorize() throws Exception { + User user = new User(); + user.setLogin("user-jwt-controller"); + user.setEmail("user-jwt-controller@example.com"); + user.setActivated(true); + user.setPassword(passwordEncoder.encode("test")); + + userRepository.saveAndFlush(user); + + LoginVM login = new LoginVM(); + login.setUsername("user-jwt-controller"); + login.setPassword("test"); + mockMvc.perform(post("/api/authenticate") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id_token").isString()) + .andExpect(jsonPath("$.id_token").isNotEmpty()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(isEmptyString()))); + } + + @Test + @Transactional + public void testAuthorizeWithRememberMe() throws Exception { + User user = new User(); + user.setLogin("user-jwt-controller-remember-me"); + user.setEmail("user-jwt-controller-remember-me@example.com"); + user.setActivated(true); + user.setPassword(passwordEncoder.encode("test")); + + userRepository.saveAndFlush(user); + + LoginVM login = new LoginVM(); + login.setUsername("user-jwt-controller-remember-me"); + login.setPassword("test"); + login.setRememberMe(true); + mockMvc.perform(post("/api/authenticate") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id_token").isString()) + .andExpect(jsonPath("$.id_token").isNotEmpty()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(isEmptyString()))); + } + + @Test + @Transactional + public void testAuthorizeFails() throws Exception { + LoginVM login = new LoginVM(); + login.setUsername("wrong-user"); + login.setPassword("wrong password"); + mockMvc.perform(post("/api/authenticate") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.id_token").doesNotExist()) + .andExpect(header().doesNotExist("Authorization")); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntTest.java deleted file mode 100644 index d31df3b15c..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntTest.java +++ /dev/null @@ -1,596 +0,0 @@ -package com.baeldung.jhipster5.web.rest; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.domain.Authority; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.UserRepository; -import com.baeldung.jhipster5.security.AuthoritiesConstants; -import com.baeldung.jhipster5.service.MailService; -import com.baeldung.jhipster5.service.UserService; -import com.baeldung.jhipster5.service.dto.UserDTO; -import com.baeldung.jhipster5.service.mapper.UserMapper; -import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; -import com.baeldung.jhipster5.web.rest.vm.ManagedUserVM; -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.boot.test.context.SpringBootTest; -import org.springframework.data.web.PageableHandlerMethodArgumentResolver; -import org.springframework.http.MediaType; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -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.transaction.annotation.Transactional; - -import javax.persistence.EntityManager; -import java.time.Instant; -import java.util.*; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -/** - * Test class for the UserResource REST controller. - * - * @see UserResource - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -public class UserResourceIntTest { - - private static final String DEFAULT_LOGIN = "johndoe"; - private static final String UPDATED_LOGIN = "jhipster"; - - private static final Long DEFAULT_ID = 1L; - - private static final String DEFAULT_PASSWORD = "passjohndoe"; - private static final String UPDATED_PASSWORD = "passjhipster"; - - private static final String DEFAULT_EMAIL = "johndoe@localhost"; - private static final String UPDATED_EMAIL = "jhipster@localhost"; - - private static final String DEFAULT_FIRSTNAME = "john"; - private static final String UPDATED_FIRSTNAME = "jhipsterFirstName"; - - private static final String DEFAULT_LASTNAME = "doe"; - private static final String UPDATED_LASTNAME = "jhipsterLastName"; - - private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50"; - private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40"; - - private static final String DEFAULT_LANGKEY = "en"; - private static final String UPDATED_LANGKEY = "fr"; - - @Autowired - private UserRepository userRepository; - - @Autowired - private MailService mailService; - - @Autowired - private UserService userService; - - @Autowired - private UserMapper userMapper; - - @Autowired - private MappingJackson2HttpMessageConverter jacksonMessageConverter; - - @Autowired - private PageableHandlerMethodArgumentResolver pageableArgumentResolver; - - @Autowired - private ExceptionTranslator exceptionTranslator; - - @Autowired - private EntityManager em; - - private MockMvc restUserMockMvc; - - private User user; - - @Before - public void setup() { - UserResource userResource = new UserResource(userService, userRepository, mailService); - - this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setMessageConverters(jacksonMessageConverter) - .build(); - } - - /** - * Create a User. - * - * This is a static method, as tests for other entities might also need it, - * if they test an entity which has a required relationship to the User entity. - */ - public static User createEntity(EntityManager em) { - User user = new User(); - user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5)); - user.setPassword(RandomStringUtils.random(60)); - user.setActivated(true); - user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL); - user.setFirstName(DEFAULT_FIRSTNAME); - user.setLastName(DEFAULT_LASTNAME); - user.setImageUrl(DEFAULT_IMAGEURL); - user.setLangKey(DEFAULT_LANGKEY); - return user; - } - - @Before - public void initTest() { - user = createEntity(em); - user.setLogin(DEFAULT_LOGIN); - user.setEmail(DEFAULT_EMAIL); - } - - @Test - @Transactional - public void createUser() throws Exception { - int databaseSizeBeforeCreate = userRepository.findAll().size(); - - // Create the User - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setLogin(DEFAULT_LOGIN); - managedUserVM.setPassword(DEFAULT_PASSWORD); - managedUserVM.setFirstName(DEFAULT_FIRSTNAME); - managedUserVM.setLastName(DEFAULT_LASTNAME); - managedUserVM.setEmail(DEFAULT_EMAIL); - managedUserVM.setActivated(true); - managedUserVM.setImageUrl(DEFAULT_IMAGEURL); - managedUserVM.setLangKey(DEFAULT_LANGKEY); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform(post("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isCreated()); - - // Validate the User in the database - List userList = userRepository.findAll(); - assertThat(userList).hasSize(databaseSizeBeforeCreate + 1); - User testUser = userList.get(userList.size() - 1); - assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN); - assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); - assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME); - assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL); - assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); - assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY); - } - - @Test - @Transactional - public void createUserWithExistingId() throws Exception { - int databaseSizeBeforeCreate = userRepository.findAll().size(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setId(1L); - managedUserVM.setLogin(DEFAULT_LOGIN); - managedUserVM.setPassword(DEFAULT_PASSWORD); - managedUserVM.setFirstName(DEFAULT_FIRSTNAME); - managedUserVM.setLastName(DEFAULT_LASTNAME); - managedUserVM.setEmail(DEFAULT_EMAIL); - managedUserVM.setActivated(true); - managedUserVM.setImageUrl(DEFAULT_IMAGEURL); - managedUserVM.setLangKey(DEFAULT_LANGKEY); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - // An entity with an existing ID cannot be created, so this API call must fail - restUserMockMvc.perform(post("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); - - // Validate the User in the database - List userList = userRepository.findAll(); - assertThat(userList).hasSize(databaseSizeBeforeCreate); - } - - @Test - @Transactional - public void createUserWithExistingLogin() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - int databaseSizeBeforeCreate = userRepository.findAll().size(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setLogin(DEFAULT_LOGIN);// this login should already be used - managedUserVM.setPassword(DEFAULT_PASSWORD); - managedUserVM.setFirstName(DEFAULT_FIRSTNAME); - managedUserVM.setLastName(DEFAULT_LASTNAME); - managedUserVM.setEmail("anothermail@localhost"); - managedUserVM.setActivated(true); - managedUserVM.setImageUrl(DEFAULT_IMAGEURL); - managedUserVM.setLangKey(DEFAULT_LANGKEY); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - // Create the User - restUserMockMvc.perform(post("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); - - // Validate the User in the database - List userList = userRepository.findAll(); - assertThat(userList).hasSize(databaseSizeBeforeCreate); - } - - @Test - @Transactional - public void createUserWithExistingEmail() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - int databaseSizeBeforeCreate = userRepository.findAll().size(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setLogin("anotherlogin"); - managedUserVM.setPassword(DEFAULT_PASSWORD); - managedUserVM.setFirstName(DEFAULT_FIRSTNAME); - managedUserVM.setLastName(DEFAULT_LASTNAME); - managedUserVM.setEmail(DEFAULT_EMAIL);// this email should already be used - managedUserVM.setActivated(true); - managedUserVM.setImageUrl(DEFAULT_IMAGEURL); - managedUserVM.setLangKey(DEFAULT_LANGKEY); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - // Create the User - restUserMockMvc.perform(post("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); - - // Validate the User in the database - List userList = userRepository.findAll(); - assertThat(userList).hasSize(databaseSizeBeforeCreate); - } - - @Test - @Transactional - public void getAllUsers() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - - // Get all the users - restUserMockMvc.perform(get("/api/users?sort=id,desc") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) - .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME))) - .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME))) - .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) - .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL))) - .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY))); - } - - @Test - @Transactional - public void getUser() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - - // Get the user - restUserMockMvc.perform(get("/api/users/{login}", user.getLogin())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.login").value(user.getLogin())) - .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME)) - .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME)) - .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) - .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL)) - .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY)); - } - - @Test - @Transactional - public void getNonExistingUser() throws Exception { - restUserMockMvc.perform(get("/api/users/unknown")) - .andExpect(status().isNotFound()); - } - - @Test - @Transactional - public void updateUser() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - int databaseSizeBeforeUpdate = userRepository.findAll().size(); - - // Update the user - User updatedUser = userRepository.findById(user.getId()).get(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setId(updatedUser.getId()); - managedUserVM.setLogin(updatedUser.getLogin()); - managedUserVM.setPassword(UPDATED_PASSWORD); - managedUserVM.setFirstName(UPDATED_FIRSTNAME); - managedUserVM.setLastName(UPDATED_LASTNAME); - managedUserVM.setEmail(UPDATED_EMAIL); - managedUserVM.setActivated(updatedUser.getActivated()); - managedUserVM.setImageUrl(UPDATED_IMAGEURL); - managedUserVM.setLangKey(UPDATED_LANGKEY); - managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); - managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); - managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); - managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform(put("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isOk()); - - // Validate the User in the database - List userList = userRepository.findAll(); - assertThat(userList).hasSize(databaseSizeBeforeUpdate); - User testUser = userList.get(userList.size() - 1); - assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); - assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); - assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); - assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); - assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); - } - - @Test - @Transactional - public void updateUserLogin() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - int databaseSizeBeforeUpdate = userRepository.findAll().size(); - - // Update the user - User updatedUser = userRepository.findById(user.getId()).get(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setId(updatedUser.getId()); - managedUserVM.setLogin(UPDATED_LOGIN); - managedUserVM.setPassword(UPDATED_PASSWORD); - managedUserVM.setFirstName(UPDATED_FIRSTNAME); - managedUserVM.setLastName(UPDATED_LASTNAME); - managedUserVM.setEmail(UPDATED_EMAIL); - managedUserVM.setActivated(updatedUser.getActivated()); - managedUserVM.setImageUrl(UPDATED_IMAGEURL); - managedUserVM.setLangKey(UPDATED_LANGKEY); - managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); - managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); - managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); - managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform(put("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isOk()); - - // Validate the User in the database - List userList = userRepository.findAll(); - assertThat(userList).hasSize(databaseSizeBeforeUpdate); - User testUser = userList.get(userList.size() - 1); - assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN); - assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); - assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); - assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); - assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); - assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); - } - - @Test - @Transactional - public void updateUserExistingEmail() throws Exception { - // Initialize the database with 2 users - userRepository.saveAndFlush(user); - - User anotherUser = new User(); - anotherUser.setLogin("jhipster"); - anotherUser.setPassword(RandomStringUtils.random(60)); - anotherUser.setActivated(true); - anotherUser.setEmail("jhipster@localhost"); - anotherUser.setFirstName("java"); - anotherUser.setLastName("hipster"); - anotherUser.setImageUrl(""); - anotherUser.setLangKey("en"); - userRepository.saveAndFlush(anotherUser); - - // Update the user - User updatedUser = userRepository.findById(user.getId()).get(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setId(updatedUser.getId()); - managedUserVM.setLogin(updatedUser.getLogin()); - managedUserVM.setPassword(updatedUser.getPassword()); - managedUserVM.setFirstName(updatedUser.getFirstName()); - managedUserVM.setLastName(updatedUser.getLastName()); - managedUserVM.setEmail("jhipster@localhost");// this email should already be used by anotherUser - managedUserVM.setActivated(updatedUser.getActivated()); - managedUserVM.setImageUrl(updatedUser.getImageUrl()); - managedUserVM.setLangKey(updatedUser.getLangKey()); - managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); - managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); - managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); - managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform(put("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); - } - - @Test - @Transactional - public void updateUserExistingLogin() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - - User anotherUser = new User(); - anotherUser.setLogin("jhipster"); - anotherUser.setPassword(RandomStringUtils.random(60)); - anotherUser.setActivated(true); - anotherUser.setEmail("jhipster@localhost"); - anotherUser.setFirstName("java"); - anotherUser.setLastName("hipster"); - anotherUser.setImageUrl(""); - anotherUser.setLangKey("en"); - userRepository.saveAndFlush(anotherUser); - - // Update the user - User updatedUser = userRepository.findById(user.getId()).get(); - - ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setId(updatedUser.getId()); - managedUserVM.setLogin("jhipster");// this login should already be used by anotherUser - managedUserVM.setPassword(updatedUser.getPassword()); - managedUserVM.setFirstName(updatedUser.getFirstName()); - managedUserVM.setLastName(updatedUser.getLastName()); - managedUserVM.setEmail(updatedUser.getEmail()); - managedUserVM.setActivated(updatedUser.getActivated()); - managedUserVM.setImageUrl(updatedUser.getImageUrl()); - managedUserVM.setLangKey(updatedUser.getLangKey()); - managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); - managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); - managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); - managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); - managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - restUserMockMvc.perform(put("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); - } - - @Test - @Transactional - public void deleteUser() throws Exception { - // Initialize the database - userRepository.saveAndFlush(user); - int databaseSizeBeforeDelete = userRepository.findAll().size(); - - // Delete the user - restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin()) - .accept(TestUtil.APPLICATION_JSON_UTF8)) - .andExpect(status().isOk()); - - // Validate the database is empty - List userList = userRepository.findAll(); - assertThat(userList).hasSize(databaseSizeBeforeDelete - 1); - } - - @Test - @Transactional - public void getAllAuthorities() throws Exception { - restUserMockMvc.perform(get("/api/users/authorities") - .accept(TestUtil.APPLICATION_JSON_UTF8) - .contentType(TestUtil.APPLICATION_JSON_UTF8)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$").isArray()) - .andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN))); - } - - @Test - @Transactional - public void testUserEquals() throws Exception { - TestUtil.equalsVerifier(User.class); - User user1 = new User(); - user1.setId(1L); - User user2 = new User(); - user2.setId(user1.getId()); - assertThat(user1).isEqualTo(user2); - user2.setId(2L); - assertThat(user1).isNotEqualTo(user2); - user1.setId(null); - assertThat(user1).isNotEqualTo(user2); - } - - @Test - public void testUserDTOtoUser() { - UserDTO userDTO = new UserDTO(); - userDTO.setId(DEFAULT_ID); - userDTO.setLogin(DEFAULT_LOGIN); - userDTO.setFirstName(DEFAULT_FIRSTNAME); - userDTO.setLastName(DEFAULT_LASTNAME); - userDTO.setEmail(DEFAULT_EMAIL); - userDTO.setActivated(true); - userDTO.setImageUrl(DEFAULT_IMAGEURL); - userDTO.setLangKey(DEFAULT_LANGKEY); - userDTO.setCreatedBy(DEFAULT_LOGIN); - userDTO.setLastModifiedBy(DEFAULT_LOGIN); - userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - - User user = userMapper.userDTOToUser(userDTO); - assertThat(user.getId()).isEqualTo(DEFAULT_ID); - assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN); - assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); - assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME); - assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL); - assertThat(user.getActivated()).isEqualTo(true); - assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); - assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY); - assertThat(user.getCreatedBy()).isNull(); - assertThat(user.getCreatedDate()).isNotNull(); - assertThat(user.getLastModifiedBy()).isNull(); - assertThat(user.getLastModifiedDate()).isNotNull(); - assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER); - } - - @Test - public void testUserToUserDTO() { - user.setId(DEFAULT_ID); - user.setCreatedBy(DEFAULT_LOGIN); - user.setCreatedDate(Instant.now()); - user.setLastModifiedBy(DEFAULT_LOGIN); - user.setLastModifiedDate(Instant.now()); - Set authorities = new HashSet<>(); - Authority authority = new Authority(); - authority.setName(AuthoritiesConstants.USER); - authorities.add(authority); - user.setAuthorities(authorities); - - UserDTO userDTO = userMapper.userToUserDTO(user); - - assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID); - assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN); - assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); - assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME); - assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL); - assertThat(userDTO.isActivated()).isEqualTo(true); - assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); - assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY); - assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN); - assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate()); - assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN); - assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate()); - assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER); - assertThat(userDTO.toString()).isNotNull(); - } - - @Test - public void testAuthorityEquals() { - Authority authorityA = new Authority(); - assertThat(authorityA).isEqualTo(authorityA); - assertThat(authorityA).isNotEqualTo(null); - assertThat(authorityA).isNotEqualTo(new Object()); - assertThat(authorityA.hashCode()).isEqualTo(0); - assertThat(authorityA.toString()).isNotNull(); - - Authority authorityB = new Authority(); - assertThat(authorityA).isEqualTo(authorityB); - - authorityB.setName(AuthoritiesConstants.ADMIN); - assertThat(authorityA).isNotEqualTo(authorityB); - - authorityA.setName(AuthoritiesConstants.USER); - assertThat(authorityA).isNotEqualTo(authorityB); - - authorityB.setName(AuthoritiesConstants.USER); - assertThat(authorityA).isEqualTo(authorityB); - assertThat(authorityA.hashCode()).isEqualTo(authorityB.hashCode()); - } -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntegrationTest.java new file mode 100644 index 0000000000..c0abc042fb --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntegrationTest.java @@ -0,0 +1,596 @@ +package com.baeldung.jhipster5.web.rest; + +import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster5.domain.Authority; +import com.baeldung.jhipster5.domain.User; +import com.baeldung.jhipster5.repository.UserRepository; +import com.baeldung.jhipster5.security.AuthoritiesConstants; +import com.baeldung.jhipster5.service.MailService; +import com.baeldung.jhipster5.service.UserService; +import com.baeldung.jhipster5.service.dto.UserDTO; +import com.baeldung.jhipster5.service.mapper.UserMapper; +import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; +import com.baeldung.jhipster5.web.rest.vm.ManagedUserVM; +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.boot.test.context.SpringBootTest; +import org.springframework.data.web.PageableHandlerMethodArgumentResolver; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +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.transaction.annotation.Transactional; + +import javax.persistence.EntityManager; +import java.time.Instant; +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** + * Test class for the UserResource REST controller. + * + * @see UserResource + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +public class UserResourceIntegrationTest { + + private static final String DEFAULT_LOGIN = "johndoe"; + private static final String UPDATED_LOGIN = "jhipster"; + + private static final Long DEFAULT_ID = 1L; + + private static final String DEFAULT_PASSWORD = "passjohndoe"; + private static final String UPDATED_PASSWORD = "passjhipster"; + + private static final String DEFAULT_EMAIL = "johndoe@localhost"; + private static final String UPDATED_EMAIL = "jhipster@localhost"; + + private static final String DEFAULT_FIRSTNAME = "john"; + private static final String UPDATED_FIRSTNAME = "jhipsterFirstName"; + + private static final String DEFAULT_LASTNAME = "doe"; + private static final String UPDATED_LASTNAME = "jhipsterLastName"; + + private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50"; + private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40"; + + private static final String DEFAULT_LANGKEY = "en"; + private static final String UPDATED_LANGKEY = "fr"; + + @Autowired + private UserRepository userRepository; + + @Autowired + private MailService mailService; + + @Autowired + private UserService userService; + + @Autowired + private UserMapper userMapper; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + private MockMvc restUserMockMvc; + + private User user; + + @Before + public void setup() { + UserResource userResource = new UserResource(userService, userRepository, mailService); + + this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setMessageConverters(jacksonMessageConverter) + .build(); + } + + /** + * Create a User. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which has a required relationship to the User entity. + */ + public static User createEntity(EntityManager em) { + User user = new User(); + user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5)); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL); + user.setFirstName(DEFAULT_FIRSTNAME); + user.setLastName(DEFAULT_LASTNAME); + user.setImageUrl(DEFAULT_IMAGEURL); + user.setLangKey(DEFAULT_LANGKEY); + return user; + } + + @Before + public void initTest() { + user = createEntity(em); + user.setLogin(DEFAULT_LOGIN); + user.setEmail(DEFAULT_EMAIL); + } + + @Test + @Transactional + public void createUser() throws Exception { + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + // Create the User + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setLogin(DEFAULT_LOGIN); + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail(DEFAULT_EMAIL); + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform(post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isCreated()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeCreate + 1); + User testUser = userList.get(userList.size() - 1); + assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN); + assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY); + } + + @Test + @Transactional + public void createUserWithExistingId() throws Exception { + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(1L); + managedUserVM.setLogin(DEFAULT_LOGIN); + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail(DEFAULT_EMAIL); + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // An entity with an existing ID cannot be created, so this API call must fail + restUserMockMvc.perform(post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeCreate); + } + + @Test + @Transactional + public void createUserWithExistingLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setLogin(DEFAULT_LOGIN);// this login should already be used + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail("anothermail@localhost"); + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Create the User + restUserMockMvc.perform(post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeCreate); + } + + @Test + @Transactional + public void createUserWithExistingEmail() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setLogin("anotherlogin"); + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail(DEFAULT_EMAIL);// this email should already be used + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Create the User + restUserMockMvc.perform(post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeCreate); + } + + @Test + @Transactional + public void getAllUsers() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + // Get all the users + restUserMockMvc.perform(get("/api/users?sort=id,desc") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) + .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME))) + .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME))) + .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) + .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL))) + .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY))); + } + + @Test + @Transactional + public void getUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + // Get the user + restUserMockMvc.perform(get("/api/users/{login}", user.getLogin())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.login").value(user.getLogin())) + .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME)) + .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME)) + .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) + .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL)) + .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY)); + } + + @Test + @Transactional + public void getNonExistingUser() throws Exception { + restUserMockMvc.perform(get("/api/users/unknown")) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeUpdate = userRepository.findAll().size(); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin(updatedUser.getLogin()); + managedUserVM.setPassword(UPDATED_PASSWORD); + managedUserVM.setFirstName(UPDATED_FIRSTNAME); + managedUserVM.setLastName(UPDATED_LASTNAME); + managedUserVM.setEmail(UPDATED_EMAIL); + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(UPDATED_IMAGEURL); + managedUserVM.setLangKey(UPDATED_LANGKEY); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform(put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isOk()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeUpdate); + User testUser = userList.get(userList.size() - 1); + assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); + } + + @Test + @Transactional + public void updateUserLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeUpdate = userRepository.findAll().size(); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin(UPDATED_LOGIN); + managedUserVM.setPassword(UPDATED_PASSWORD); + managedUserVM.setFirstName(UPDATED_FIRSTNAME); + managedUserVM.setLastName(UPDATED_LASTNAME); + managedUserVM.setEmail(UPDATED_EMAIL); + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(UPDATED_IMAGEURL); + managedUserVM.setLangKey(UPDATED_LANGKEY); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform(put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isOk()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeUpdate); + User testUser = userList.get(userList.size() - 1); + assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN); + assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); + } + + @Test + @Transactional + public void updateUserExistingEmail() throws Exception { + // Initialize the database with 2 users + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("jhipster"); + anotherUser.setPassword(RandomStringUtils.random(60)); + anotherUser.setActivated(true); + anotherUser.setEmail("jhipster@localhost"); + anotherUser.setFirstName("java"); + anotherUser.setLastName("hipster"); + anotherUser.setImageUrl(""); + anotherUser.setLangKey("en"); + userRepository.saveAndFlush(anotherUser); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin(updatedUser.getLogin()); + managedUserVM.setPassword(updatedUser.getPassword()); + managedUserVM.setFirstName(updatedUser.getFirstName()); + managedUserVM.setLastName(updatedUser.getLastName()); + managedUserVM.setEmail("jhipster@localhost");// this email should already be used by anotherUser + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(updatedUser.getImageUrl()); + managedUserVM.setLangKey(updatedUser.getLangKey()); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform(put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + } + + @Test + @Transactional + public void updateUserExistingLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("jhipster"); + anotherUser.setPassword(RandomStringUtils.random(60)); + anotherUser.setActivated(true); + anotherUser.setEmail("jhipster@localhost"); + anotherUser.setFirstName("java"); + anotherUser.setLastName("hipster"); + anotherUser.setImageUrl(""); + anotherUser.setLangKey("en"); + userRepository.saveAndFlush(anotherUser); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin("jhipster");// this login should already be used by anotherUser + managedUserVM.setPassword(updatedUser.getPassword()); + managedUserVM.setFirstName(updatedUser.getFirstName()); + managedUserVM.setLastName(updatedUser.getLastName()); + managedUserVM.setEmail(updatedUser.getEmail()); + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(updatedUser.getImageUrl()); + managedUserVM.setLangKey(updatedUser.getLangKey()); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform(put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + } + + @Test + @Transactional + public void deleteUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeDelete = userRepository.findAll().size(); + + // Delete the user + restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isOk()); + + // Validate the database is empty + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeDelete - 1); + } + + @Test + @Transactional + public void getAllAuthorities() throws Exception { + restUserMockMvc.perform(get("/api/users/authorities") + .accept(TestUtil.APPLICATION_JSON_UTF8) + .contentType(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN))); + } + + @Test + @Transactional + public void testUserEquals() throws Exception { + TestUtil.equalsVerifier(User.class); + User user1 = new User(); + user1.setId(1L); + User user2 = new User(); + user2.setId(user1.getId()); + assertThat(user1).isEqualTo(user2); + user2.setId(2L); + assertThat(user1).isNotEqualTo(user2); + user1.setId(null); + assertThat(user1).isNotEqualTo(user2); + } + + @Test + public void testUserDTOtoUser() { + UserDTO userDTO = new UserDTO(); + userDTO.setId(DEFAULT_ID); + userDTO.setLogin(DEFAULT_LOGIN); + userDTO.setFirstName(DEFAULT_FIRSTNAME); + userDTO.setLastName(DEFAULT_LASTNAME); + userDTO.setEmail(DEFAULT_EMAIL); + userDTO.setActivated(true); + userDTO.setImageUrl(DEFAULT_IMAGEURL); + userDTO.setLangKey(DEFAULT_LANGKEY); + userDTO.setCreatedBy(DEFAULT_LOGIN); + userDTO.setLastModifiedBy(DEFAULT_LOGIN); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + User user = userMapper.userDTOToUser(userDTO); + assertThat(user.getId()).isEqualTo(DEFAULT_ID); + assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN); + assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); + assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME); + assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(user.getActivated()).isEqualTo(true); + assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); + assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY); + assertThat(user.getCreatedBy()).isNull(); + assertThat(user.getCreatedDate()).isNotNull(); + assertThat(user.getLastModifiedBy()).isNull(); + assertThat(user.getLastModifiedDate()).isNotNull(); + assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER); + } + + @Test + public void testUserToUserDTO() { + user.setId(DEFAULT_ID); + user.setCreatedBy(DEFAULT_LOGIN); + user.setCreatedDate(Instant.now()); + user.setLastModifiedBy(DEFAULT_LOGIN); + user.setLastModifiedDate(Instant.now()); + Set authorities = new HashSet<>(); + Authority authority = new Authority(); + authority.setName(AuthoritiesConstants.USER); + authorities.add(authority); + user.setAuthorities(authorities); + + UserDTO userDTO = userMapper.userToUserDTO(user); + + assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID); + assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN); + assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); + assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME); + assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(userDTO.isActivated()).isEqualTo(true); + assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); + assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY); + assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN); + assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate()); + assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN); + assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate()); + assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER); + assertThat(userDTO.toString()).isNotNull(); + } + + @Test + public void testAuthorityEquals() { + Authority authorityA = new Authority(); + assertThat(authorityA).isEqualTo(authorityA); + assertThat(authorityA).isNotEqualTo(null); + assertThat(authorityA).isNotEqualTo(new Object()); + assertThat(authorityA.hashCode()).isEqualTo(0); + assertThat(authorityA.toString()).isNotNull(); + + Authority authorityB = new Authority(); + assertThat(authorityA).isEqualTo(authorityB); + + authorityB.setName(AuthoritiesConstants.ADMIN); + assertThat(authorityA).isNotEqualTo(authorityB); + + authorityA.setName(AuthoritiesConstants.USER); + assertThat(authorityA).isNotEqualTo(authorityB); + + authorityB.setName(AuthoritiesConstants.USER); + assertThat(authorityA).isEqualTo(authorityB); + assertThat(authorityA.hashCode()).isEqualTo(authorityB.hashCode()); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntTest.java deleted file mode 100644 index a94d54063b..0000000000 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntTest.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.baeldung.jhipster5.web.rest.errors; - -import com.baeldung.jhipster5.BookstoreApp; -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.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import static org.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.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * Test class for the ExceptionTranslator controller advice. - * - * @see ExceptionTranslator - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookstoreApp.class) -public class ExceptionTranslatorIntTest { - - @Autowired - private ExceptionTranslatorTestController controller; - - @Autowired - private ExceptionTranslator exceptionTranslator; - - @Autowired - private MappingJackson2HttpMessageConverter jacksonMessageConverter; - - private MockMvc mockMvc; - - @Before - public void setup() { - mockMvc = MockMvcBuilders.standaloneSetup(controller) - .setControllerAdvice(exceptionTranslator) - .setMessageConverters(jacksonMessageConverter) - .build(); - } - - @Test - public void testConcurrencyFailure() throws Exception { - mockMvc.perform(get("/test/concurrency-failure")) - .andExpect(status().isConflict()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); - } - - @Test - public void testMethodArgumentNotValid() throws Exception { - mockMvc.perform(post("/test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION)) - .andExpect(jsonPath("$.fieldErrors.[0].objectName").value("testDTO")) - .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) - .andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull")); - } - - @Test - public void testParameterizedError() throws Exception { - mockMvc.perform(get("/test/parameterized-error")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("test parameterized error")) - .andExpect(jsonPath("$.params.param0").value("param0_value")) - .andExpect(jsonPath("$.params.param1").value("param1_value")); - } - - @Test - public void testParameterizedError2() throws Exception { - mockMvc.perform(get("/test/parameterized-error2")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("test parameterized error")) - .andExpect(jsonPath("$.params.foo").value("foo_value")) - .andExpect(jsonPath("$.params.bar").value("bar_value")); - } - - @Test - public void testMissingServletRequestPartException() throws Exception { - mockMvc.perform(get("/test/missing-servlet-request-part")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")); - } - - @Test - public void testMissingServletRequestParameterException() throws Exception { - mockMvc.perform(get("/test/missing-servlet-request-parameter")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")); - } - - @Test - public void testAccessDenied() throws Exception { - mockMvc.perform(get("/test/access-denied")) - .andExpect(status().isForbidden()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.403")) - .andExpect(jsonPath("$.detail").value("test access denied!")); - } - - @Test - public void testUnauthorized() throws Exception { - mockMvc.perform(get("/test/unauthorized")) - .andExpect(status().isUnauthorized()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.401")) - .andExpect(jsonPath("$.path").value("/test/unauthorized")) - .andExpect(jsonPath("$.detail").value("test authentication failed!")); - } - - @Test - public void testMethodNotSupported() throws Exception { - mockMvc.perform(post("/test/access-denied")) - .andExpect(status().isMethodNotAllowed()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.405")) - .andExpect(jsonPath("$.detail").value("Request method 'POST' not supported")); - } - - @Test - public void testExceptionWithResponseStatus() throws Exception { - mockMvc.perform(get("/test/response-status")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")) - .andExpect(jsonPath("$.title").value("test response status")); - } - - @Test - public void testInternalServerError() throws Exception { - mockMvc.perform(get("/test/internal-server-error")) - .andExpect(status().isInternalServerError()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.500")) - .andExpect(jsonPath("$.title").value("Internal Server Error")); - } - -} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntegrationTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntegrationTest.java new file mode 100644 index 0000000000..e5ef08ee9c --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntegrationTest.java @@ -0,0 +1,150 @@ +package com.baeldung.jhipster5.web.rest.errors; + +import com.baeldung.jhipster5.BookstoreApp; +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.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.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.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Test class for the ExceptionTranslator controller advice. + * + * @see ExceptionTranslator + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookstoreApp.class) +public class ExceptionTranslatorIntegrationTest { + + @Autowired + private ExceptionTranslatorTestController controller; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders.standaloneSetup(controller) + .setControllerAdvice(exceptionTranslator) + .setMessageConverters(jacksonMessageConverter) + .build(); + } + + @Test + public void testConcurrencyFailure() throws Exception { + mockMvc.perform(get("/test/concurrency-failure")) + .andExpect(status().isConflict()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); + } + + @Test + public void testMethodArgumentNotValid() throws Exception { + mockMvc.perform(post("/test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION)) + .andExpect(jsonPath("$.fieldErrors.[0].objectName").value("testDTO")) + .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) + .andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull")); + } + + @Test + public void testParameterizedError() throws Exception { + mockMvc.perform(get("/test/parameterized-error")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("test parameterized error")) + .andExpect(jsonPath("$.params.param0").value("param0_value")) + .andExpect(jsonPath("$.params.param1").value("param1_value")); + } + + @Test + public void testParameterizedError2() throws Exception { + mockMvc.perform(get("/test/parameterized-error2")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("test parameterized error")) + .andExpect(jsonPath("$.params.foo").value("foo_value")) + .andExpect(jsonPath("$.params.bar").value("bar_value")); + } + + @Test + public void testMissingServletRequestPartException() throws Exception { + mockMvc.perform(get("/test/missing-servlet-request-part")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); + } + + @Test + public void testMissingServletRequestParameterException() throws Exception { + mockMvc.perform(get("/test/missing-servlet-request-parameter")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); + } + + @Test + public void testAccessDenied() throws Exception { + mockMvc.perform(get("/test/access-denied")) + .andExpect(status().isForbidden()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.403")) + .andExpect(jsonPath("$.detail").value("test access denied!")); + } + + @Test + public void testUnauthorized() throws Exception { + mockMvc.perform(get("/test/unauthorized")) + .andExpect(status().isUnauthorized()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.401")) + .andExpect(jsonPath("$.path").value("/test/unauthorized")) + .andExpect(jsonPath("$.detail").value("test authentication failed!")); + } + + @Test + public void testMethodNotSupported() throws Exception { + mockMvc.perform(post("/test/access-denied")) + .andExpect(status().isMethodNotAllowed()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.405")) + .andExpect(jsonPath("$.detail").value("Request method 'POST' not supported")); + } + + @Test + public void testExceptionWithResponseStatus() throws Exception { + mockMvc.perform(get("/test/response-status")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")) + .andExpect(jsonPath("$.title").value("test response status")); + } + + @Test + public void testInternalServerError() throws Exception { + mockMvc.perform(get("/test/internal-server-error")) + .andExpect(status().isInternalServerError()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.500")) + .andExpect(jsonPath("$.title").value("Internal Server Error")); + } + +} diff --git a/jhipster-5/pom.xml b/jhipster-5/pom.xml index cebbe25d8b..2a5132e50e 100644 --- a/jhipster-5/pom.xml +++ b/jhipster-5/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml index 86d94d0a44..c53ea8358e 100644 --- a/jhipster/jhipster-microservice/car-app/pom.xml +++ b/jhipster/jhipster-microservice/car-app/pom.xml @@ -17,6 +17,7 @@ + 1.0.0 -Djava.security.egd=file:/dev/./urandom -Xmx256m 3.6.2 2.0.0 @@ -433,7 +434,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml index 3051399ae6..a0bcc73e31 100644 --- a/jhipster/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster/jhipster-microservice/dealer-app/pom.xml @@ -92,6 +92,7 @@ 1.4.10.Final 1.1.0.Final v0.21.3 + 1.0.0 @@ -427,7 +428,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml index 4e2c19ed2d..c6dcbb3f3e 100644 --- a/jhipster/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster/jhipster-microservice/gateway-app/pom.xml @@ -96,6 +96,7 @@ 1.4.10.Final 1.1.0.Final v0.21.3 + 1.0.0 @@ -469,7 +470,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index 12dead99df..04f790faf5 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -302,7 +302,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -398,8 +398,8 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} org.mapstruct @@ -881,6 +881,9 @@ + 1.8 + 1.8 + 1.0.0 -Djava.security.egd=file:/dev/./urandom -Xmx256m 3.6.2 2.0.0 diff --git a/jhipster/jhipster-uaa/gateway/pom.xml b/jhipster/jhipster-uaa/gateway/pom.xml index 0f815bedad..b417bd7b57 100644 --- a/jhipster/jhipster-uaa/gateway/pom.xml +++ b/jhipster/jhipster-uaa/gateway/pom.xml @@ -236,7 +236,7 @@ org.zalando problem-spring-web - 0.24.0-RC.0 + ${spring.web.version} org.springframework.security.oauth @@ -559,7 +559,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -1012,6 +1012,8 @@ + 1.0.0 + 0.24.0 3.0.0 1.8 diff --git a/jhipster/jhipster-uaa/quotes/pom.xml b/jhipster/jhipster-uaa/quotes/pom.xml index 81ab23471f..f088ad2fd1 100644 --- a/jhipster/jhipster-uaa/quotes/pom.xml +++ b/jhipster/jhipster-uaa/quotes/pom.xml @@ -232,7 +232,7 @@ org.zalando problem-spring-web - 0.24.0-RC.0 + ${zalando.version} org.springframework.security.oauth @@ -910,5 +910,6 @@ ${project.basedir}/src/test/ + 0.24.0 diff --git a/jhipster/jhipster-uaa/uaa/pom.xml b/jhipster/jhipster-uaa/uaa/pom.xml index 2c4dd9d0f0..f9c1f226bb 100644 --- a/jhipster/jhipster-uaa/uaa/pom.xml +++ b/jhipster/jhipster-uaa/uaa/pom.xml @@ -232,7 +232,7 @@ org.zalando problem-spring-web - 0.24.0-RC.0 + ${spring.web.version} org.springframework.security.oauth @@ -543,7 +543,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -834,6 +834,8 @@ + 1.0.0 + 0.24.0 3.0.0 1.8 diff --git a/jjwt/pom.xml b/jjwt/pom.xml index 073f12a922..aa238fafb5 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -30,6 +30,11 @@ org.springframework.boot spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + io.jsonwebtoken diff --git a/jmeter/pom.xml b/jmeter/pom.xml index 64642695ff..945210edd7 100644 --- a/jmeter/pom.xml +++ b/jmeter/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/json-2/README.md b/json-2/README.md new file mode 100644 index 0000000000..c2b6b36a11 --- /dev/null +++ b/json-2/README.md @@ -0,0 +1,7 @@ +## JSON + +This module contains articles about JSON. + +### Relevant Articles: +- [Introduction to Jsoniter](https://www.baeldung.com/java-jsoniter) +- [Introduction to Moshi Json](https://www.baeldung.com/java-json-moshi) diff --git a/json-2/pom.xml b/json-2/pom.xml new file mode 100644 index 0000000000..e0295af59b --- /dev/null +++ b/json-2/pom.xml @@ -0,0 +1,58 @@ + + + com.baeldung + json-2 + 0.0.1-SNAPSHOT + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + + + com.jsoniter + jsoniter + ${jsoniter.version} + + + + junit + junit + ${junit.version} + test + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + com.squareup.moshi + moshi + ${moshi.version} + + + com.squareup.moshi + moshi-adapters + ${moshi.version} + + + org.apache.commons + commons-lang3 + 3.9 + + + + 0.9.23 + 3.11.1 + 1.9.2 + + diff --git a/json-2/src/main/java/com/baeldung/jsoniter/model/Name.java b/json-2/src/main/java/com/baeldung/jsoniter/model/Name.java new file mode 100644 index 0000000000..ed5e221235 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsoniter/model/Name.java @@ -0,0 +1,22 @@ +package com.baeldung.jsoniter.model; + +public class Name { + private String firstName; + private String surname; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } +} diff --git a/json-2/src/main/java/com/baeldung/jsoniter/model/Student.java b/json-2/src/main/java/com/baeldung/jsoniter/model/Student.java new file mode 100644 index 0000000000..07c73dd18e --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsoniter/model/Student.java @@ -0,0 +1,26 @@ +package com.baeldung.jsoniter.model; + +import com.jsoniter.annotation.JsonProperty; +import com.jsoniter.fuzzy.MaybeStringIntDecoder; + +public class Student { + @JsonProperty(decoder = MaybeStringIntDecoder.class) + private int id; + private Name name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Name getName() { + return name; + } + + public void setName(Name name) { + this.name = name; + } +} diff --git a/json-2/src/test/java/com/baeldung/jsoniter/JsoniterIntroUnitTest.java b/json-2/src/test/java/com/baeldung/jsoniter/JsoniterIntroUnitTest.java new file mode 100644 index 0000000000..09f82567a2 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsoniter/JsoniterIntroUnitTest.java @@ -0,0 +1,85 @@ +package com.baeldung.jsoniter; + +import com.baeldung.jsoniter.model.Name; +import com.baeldung.jsoniter.model.Student; +import com.jsoniter.JsonIterator; +import com.jsoniter.ValueType; +import com.jsoniter.any.Any; + +import org.junit.Test; + +import static com.jsoniter.ValueType.STRING; +import static org.assertj.core.api.Assertions.assertThat; + +public class JsoniterIntroUnitTest { + + @Test + public void whenParsedUsingBindAPI_thenConvertedToJavaObjectCorrectly() { + String input = "{\"id\":1,\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}"; + + Student student = JsonIterator.deserialize(input, Student.class); + + assertThat(student.getId()).isEqualTo(1); + assertThat(student.getName().getFirstName()).isEqualTo("Joe"); + assertThat(student.getName().getSurname()).isEqualTo("Blogg"); + } + + @Test + public void givenTypeInJsonFuzzy_whenFieldIsMaybeDecoded_thenFieldParsedCorrectly() { + String input = "{\"id\":\"1\",\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}"; + + Student student = JsonIterator.deserialize(input, Student.class); + + assertThat(student.getId()).isEqualTo(1); + } + + @Test + public void whenParsedUsingAnyAPI_thenFieldValueCanBeExtractedUsingTheFieldName() { + String input = "{\"id\":1,\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}"; + + Any any = JsonIterator.deserialize(input); + + assertThat(any.toInt("id")).isEqualTo(1); + assertThat(any.toString("name", "firstName")).isEqualTo("Joe"); + assertThat(any.toString("name", "surname")).isEqualTo("Blogg"); + } + + @Test + public void whenParsedUsingAnyAPI_thenFieldValueTypeIsCorrect() { + String input = "{\"id\":1,\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}"; + + Any any = JsonIterator.deserialize(input); + + assertThat(any.get("id").valueType()).isEqualTo(ValueType.NUMBER); + assertThat(any.get("name").valueType()).isEqualTo(ValueType.OBJECT); + assertThat(any.get("error").valueType()).isEqualTo(ValueType.INVALID); + } + + @Test + public void whenParsedUsingIteratorAPI_thenFieldValuesExtractedCorrectly() throws Exception { + Name name = new Name(); + String input = "{ \"firstName\" : \"Joe\", \"surname\" : \"Blogg\" }"; + JsonIterator iterator = JsonIterator.parse(input); + + for (String field = iterator.readObject(); field != null; field = iterator.readObject()) { + switch (field) { + case "firstName": + if (iterator.whatIsNext() == ValueType.STRING) { + name.setFirstName(iterator.readString()); + } + continue; + case "surname": + if (iterator.whatIsNext() == ValueType.STRING) { + name.setSurname(iterator.readString()); + } + continue; + default: + iterator.skip(); + } + } + + assertThat(name.getFirstName()).isEqualTo("Joe"); + assertThat(name.getSurname()).isEqualTo("Blogg"); + } + +} diff --git a/json-2/src/test/java/com/baeldung/moshi/AlternativeAdapterUnitTest.java b/json-2/src/test/java/com/baeldung/moshi/AlternativeAdapterUnitTest.java new file mode 100644 index 0000000000..63d80bfe58 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/moshi/AlternativeAdapterUnitTest.java @@ -0,0 +1,105 @@ +package com.baeldung.moshi; + +import java.io.IOException; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.time.Instant; + +import com.squareup.moshi.FromJson; +import com.squareup.moshi.JsonAdapter; +import com.squareup.moshi.JsonQualifier; +import com.squareup.moshi.Moshi; +import com.squareup.moshi.ToJson; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.junit.Test; + +public class AlternativeAdapterUnitTest { + @Test + public void whenSerializing_thenAlternativeAdapterUsed() { + Moshi moshi = new Moshi.Builder() + .add(new EpochMillisAdapter()) + .build(); + JsonAdapter jsonAdapter = moshi.adapter(Post.class); + + String json = jsonAdapter.toJson(new Post("Introduction to Moshi Json", "Baeldung", Instant.now())); + System.out.println(json); + } + + @Test + public void whenDeserializing_thenAlternativeAdapterUsed() throws IOException { + Moshi moshi = new Moshi.Builder() + .add(new EpochMillisAdapter()) + .build(); + JsonAdapter jsonAdapter = moshi.adapter(Post.class); + + String json = "{\"author\":\"Baeldung\",\"posted\":1582095269204,\"title\":\"Introduction to Moshi Json\"}"; + Post post = jsonAdapter.fromJson(json); + System.out.println(post); + + } + + public static class Post { + String title; + String author; + @EpochMillis Instant posted; + + public Post() { + } + + public Post(String title, String author, Instant posted) { + this.title = title; + this.author = author; + this.posted = posted; + } + + 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 Instant getPosted() { + return posted; + } + + public void setPosted(Instant posted) { + this.posted = posted; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("title", title).append("author", author).append("posted", posted) + .toString(); + } + } + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) + @JsonQualifier + public @interface EpochMillis { + } + + public static class EpochMillisAdapter { + @ToJson + public Long toJson(@EpochMillis Instant input) { + return input.toEpochMilli(); + } + @FromJson + @EpochMillis + public Instant fromJson(Long input) { + return Instant.ofEpochMilli(input); + } + + } +} diff --git a/json-2/src/test/java/com/baeldung/moshi/ArrayUnitTest.java b/json-2/src/test/java/com/baeldung/moshi/ArrayUnitTest.java new file mode 100644 index 0000000000..83bb2bb128 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/moshi/ArrayUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.moshi; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.List; + +import com.squareup.moshi.JsonAdapter; +import com.squareup.moshi.Moshi; +import com.squareup.moshi.Types; +import org.junit.Test; + +public class ArrayUnitTest { + @Test + public void whenSerializingList_thenJsonArrayProduced() { + Moshi moshi = new Moshi.Builder() + .build(); + Type type = Types.newParameterizedType(List.class, String.class); + JsonAdapter> jsonAdapter = moshi.adapter(type); + + String json = jsonAdapter.toJson(Arrays.asList("One", "Two", "Three")); + System.out.println(json); + } + + @Test + public void whenDeserializingJsonArray_thenListProduced() throws IOException { + Moshi moshi = new Moshi.Builder() + .build(); + Type type = Types.newParameterizedType(List.class, String.class); + JsonAdapter> jsonAdapter = moshi.adapter(type); + + String json = "[\"One\",\"Two\",\"Three\"]"; + List result = jsonAdapter.fromJson(json); + System.out.println(result); + } +} diff --git a/json-2/src/test/java/com/baeldung/moshi/ComplexAdapterUnitTest.java b/json-2/src/test/java/com/baeldung/moshi/ComplexAdapterUnitTest.java new file mode 100644 index 0000000000..f0f8e9a95d --- /dev/null +++ b/json-2/src/test/java/com/baeldung/moshi/ComplexAdapterUnitTest.java @@ -0,0 +1,94 @@ +package com.baeldung.moshi; + +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import com.squareup.moshi.FromJson; +import com.squareup.moshi.JsonAdapter; +import com.squareup.moshi.Moshi; +import com.squareup.moshi.ToJson; +import org.junit.Test; + +public class ComplexAdapterUnitTest { + @Test + public void whenSerializing_thenCorrectJsonProduced() { + Moshi moshi = new Moshi.Builder() + .add(new JsonDateTimeAdapter()) + .build(); + JsonAdapter jsonAdapter = moshi.adapter(ZonedDateTime.class); + + String json = jsonAdapter.toJson(ZonedDateTime.now()); + System.out.println(json); + } + + @Test + public void whenDeserializing_thenCorrectJsonConsumed() throws IOException { + Moshi moshi = new Moshi.Builder() + .add(new JsonDateTimeAdapter()) + .build(); + JsonAdapter jsonAdapter = moshi.adapter(ZonedDateTime.class); + + String json = "{\"date\":\"2020-02-17\",\"time\":\"07:53:27.064\",\"timezone\":\"Europe/London\"}"; + ZonedDateTime now = jsonAdapter.fromJson(json); + System.out.println(now); + + } + + public static class JsonDateTimeAdapter { + @ToJson + public JsonDateTime toJson(ZonedDateTime input) { + String date = input.toLocalDate().toString(); + String time = input.toLocalTime().toString(); + String timezone = input.getZone().toString(); + return new JsonDateTime(date, time, timezone); + } + @FromJson + public ZonedDateTime fromJson(JsonDateTime input) { + LocalDate date = LocalDate.parse(input.getDate()); + LocalTime time = LocalTime.parse(input.getTime()); + ZoneId timezone = ZoneId.of(input.getTimezone()); + return ZonedDateTime.of(date, time, timezone); + } + } + public static class JsonDateTime { + private String date; + private String time; + private String timezone; + + public JsonDateTime() { + } + + public JsonDateTime(String date, String time, String timezone) { + this.date = date; + this.time = time; + this.timezone = timezone; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } + } +} diff --git a/json-2/src/test/java/com/baeldung/moshi/DefaultUnitTest.java b/json-2/src/test/java/com/baeldung/moshi/DefaultUnitTest.java new file mode 100644 index 0000000000..0b4ecc23a5 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/moshi/DefaultUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.moshi; + +import java.io.IOException; +import java.time.Instant; + +import com.squareup.moshi.JsonAdapter; +import com.squareup.moshi.Moshi; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.junit.Test; + +public class DefaultUnitTest { + + @Test + public void whenDeserializing_thenFieldsGetDefaultValues() throws IOException { + Moshi moshi = new Moshi.Builder() + .build(); + JsonAdapter jsonAdapter = moshi.adapter(Post.class); + + String json = "{\"title\":\"My Post\"}"; + Post post = jsonAdapter.fromJson(json); + System.out.println(post); + } + public static class Post { + private String title; + private String author; + private String posted; + + public Post() { + posted = Instant.now().toString(); + } + + public Post(String title, String author, String posted) { + this.title = title; + this.author = author; + this.posted = posted; + } + + 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 getPosted() { + return posted; + } + + public void setPosted(String posted) { + this.posted = posted; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("title", title).append("author", author).append("posted", posted) + .toString(); + } + } +} diff --git a/json-2/src/test/java/com/baeldung/moshi/PrimitiveUnitTest.java b/json-2/src/test/java/com/baeldung/moshi/PrimitiveUnitTest.java new file mode 100644 index 0000000000..e26e93ba8c --- /dev/null +++ b/json-2/src/test/java/com/baeldung/moshi/PrimitiveUnitTest.java @@ -0,0 +1,77 @@ +package com.baeldung.moshi; + +import java.io.IOException; + +import com.squareup.moshi.JsonAdapter; +import com.squareup.moshi.Moshi; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.junit.Test; + +public class PrimitiveUnitTest { + @Test + public void whenSerializing_thenCorrectJsonProduced() { + Moshi moshi = new Moshi.Builder() + .build(); + JsonAdapter jsonAdapter = moshi.adapter(Post.class); + + Post post = new Post("My Post", "Baeldung", "This is my post"); + String json = jsonAdapter.toJson(post); + System.out.println(json); + } + + @Test + public void whenDeserializing_thenCorrectJsonConsumed() throws IOException { + Moshi moshi = new Moshi.Builder() + .build(); + JsonAdapter jsonAdapter = moshi.adapter(Post.class); + + String json = "{\"author\":\"Baeldung\",\"text\":\"This is my post\",\"title\":\"My Post\"}"; + Post post = jsonAdapter.fromJson(json); + System.out.println(post); + } + + public static class Post { + private String title; + private String author; + private String text; + + public Post() { + } + + public Post(String title, String author, String text) { + this.title = title; + this.author = author; + this.text = text; + } + + 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 getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("title", title).append("author", author).append("text", text) + .toString(); + } + } +} diff --git a/json-2/src/test/java/com/baeldung/moshi/RenameUnitTest.java b/json-2/src/test/java/com/baeldung/moshi/RenameUnitTest.java new file mode 100644 index 0000000000..2118538a19 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/moshi/RenameUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.moshi; + +import java.io.IOException; + +import com.squareup.moshi.Json; +import com.squareup.moshi.JsonAdapter; +import com.squareup.moshi.Moshi; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.junit.jupiter.api.Test; + +public class RenameUnitTest { + + @Test + public void whenSerializing_thenFieldsGetRenamed() { + Moshi moshi = new Moshi.Builder() + .build(); + JsonAdapter jsonAdapter = moshi.adapter(Post.class); + + Post post = new Post("My Post", "Baeldung"); + String json = jsonAdapter.toJson(post); + System.out.println(json); + } + + @Test + public void whenSerializing_thenRenamedFieldsGetConsumed() throws IOException { + Moshi moshi = new Moshi.Builder() + .build(); + JsonAdapter jsonAdapter = moshi.adapter(Post.class); + + String json = "{\"authored_by\":\"Baeldung\",\"title\":\"My Post\"}"; + Post post = jsonAdapter.fromJson(json); + System.out.println(post); + } + public static class Post { + private String title; + @Json(name = "authored_by") + private String author; + + public Post() { + } + + public Post(String title, String author) { + this.title = title; + this.author = author; + } + + 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 String toString() { + return new ToStringBuilder(this).append("title", title).append("author", author).toString(); + } + } +} diff --git a/json-2/src/test/java/com/baeldung/moshi/SimpleAdapterUnitTest.java b/json-2/src/test/java/com/baeldung/moshi/SimpleAdapterUnitTest.java new file mode 100644 index 0000000000..e0be2f8a66 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/moshi/SimpleAdapterUnitTest.java @@ -0,0 +1,129 @@ +package com.baeldung.moshi; + +import java.io.IOException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.squareup.moshi.FromJson; +import com.squareup.moshi.JsonAdapter; +import com.squareup.moshi.Moshi; +import com.squareup.moshi.ToJson; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.junit.Test; + +public class SimpleAdapterUnitTest { + @Test + public void whenSerializing_thenAdapterUsed() { + Moshi moshi = new Moshi.Builder() + .add(new AuthorAdapter()) + .build(); + JsonAdapter jsonAdapter = moshi.adapter(Post.class); + + Post post = new Post("My Post", new Author("Baeldung", "baeldung@example.com"), "This is my post"); + String json = jsonAdapter.toJson(post); + System.out.println(json); + } + + @Test + public void whenDeserializing_thenAdapterUsed() throws IOException { + Moshi moshi = new Moshi.Builder() + .add(new AuthorAdapter()) + .build(); + JsonAdapter jsonAdapter = moshi.adapter(Post.class); + + String json = "{\"author\":\"Baeldung \",\"text\":\"This is my post\",\"title\":\"My Post\"}"; + Post post = jsonAdapter.fromJson(json); + System.out.println(post); + } + public static class AuthorAdapter { + private Pattern pattern = Pattern.compile("^(.*) <(.*)>$"); + @ToJson + public String toJson(Author author) { + return author.name + " <" + author.email + ">"; + } + + @FromJson + public Author fromJson(String author) { + Matcher matcher = pattern.matcher(author); + return matcher.find() ? new Author(matcher.group(1), matcher.group(2)) : null; + } + } + + public static class Author { + private String name; + private String email; + + public Author() { + } + + public Author(String name, String email) { + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("name", name).append("email", email).toString(); + } + } + public static class Post { + private String title; + private Author author; + private String text; + + public Post() { + } + + public Post(String title, Author author, String text) { + this.title = title; + this.author = author; + this.text = text; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Author getAuthor() { + return author; + } + + public void setAuthor(Author author) { + this.author = author; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("title", title).append("author", author).append("text", text) + .toString(); + } + } +} diff --git a/json-2/src/test/java/com/baeldung/moshi/TransientUnitTest.java b/json-2/src/test/java/com/baeldung/moshi/TransientUnitTest.java new file mode 100644 index 0000000000..2554e937b3 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/moshi/TransientUnitTest.java @@ -0,0 +1,66 @@ +package com.baeldung.moshi; + +import java.io.IOException; + +import com.squareup.moshi.JsonAdapter; +import com.squareup.moshi.Moshi; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.junit.jupiter.api.Test; + +public class TransientUnitTest { + + @Test + public void whenSerializing_thenTransientFieldIgnored() { + Moshi moshi = new Moshi.Builder() + .build(); + JsonAdapter jsonAdapter = moshi.adapter(Post.class); + + Post post = new Post("My Post", "Baeldung"); + String json = jsonAdapter.toJson(post); + System.out.println(json); + } + + @Test + public void whenDeserializing_thenTransientFieldIgnored() throws IOException { + Moshi moshi = new Moshi.Builder() + .build(); + JsonAdapter jsonAdapter = moshi.adapter(Post.class); + + String json = "{\"authored_by\":\"Baeldung\",\"title\":\"My Post\"}"; + Post post = jsonAdapter.fromJson(json); + System.out.println(post); + } + public static class Post { + private String title; + private transient String author; + + public Post() { + } + + public Post(String title, String author) { + this.title = title; + this.author = author; + } + + 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 String toString() { + return new ToStringBuilder(this).append("title", title).append("author", author).toString(); + } + } +} diff --git a/json-2/src/test/resources/Student.json b/json-2/src/test/resources/Student.json new file mode 100644 index 0000000000..7ff3351e8e --- /dev/null +++ b/json-2/src/test/resources/Student.json @@ -0,0 +1 @@ +{"id":1,"name":{"firstName": "Joe", "surname":"Blogg"}} diff --git a/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyIntegrationTest.java b/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyIntegrationTest.java new file mode 100644 index 0000000000..8e854ead6a --- /dev/null +++ b/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.jsonproxy; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Proxy; + +import org.jsoup.Jsoup; +import org.junit.Test; + +public class JsoupProxyIntegrationTest { + + @Test + public void whenUsingHostAndPort_thenConnect() throws IOException { + Jsoup.connect("https://spring.io/blog") + .proxy("200.216.227.141", 53281) + .get(); + } + + @Test + public void whenUsingProxyClass_thenConnect() throws IOException { + Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("200.216.227.141", 53281)); + + Jsoup.connect("https://spring.io/blog") + .proxy(proxy) + .get(); + } +} diff --git a/jta/README.md b/jta/README.md index 0351177a0d..202019118d 100644 --- a/jta/README.md +++ b/jta/README.md @@ -3,4 +3,4 @@ This module contains articles about the Java Transaction API (JTA). ### Relevant Articles: -- [Guide to Java EE JTA](https://www.baeldung.com/jee-jta) +- [Guide to Jakarta EE JTA](https://www.baeldung.com/jee-jta) diff --git a/jws/pom.xml b/jws/pom.xml index e6ab7e05ec..be42798fd1 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -14,26 +14,6 @@ 1.0.0-SNAPSHOT - - - OpenNMS Repository - http://repo.opennms.org/maven2/ - - - - - - javax.samples.jnlp - jnlp-servlet - ${jnlp-servlet.version} - - - javax.samples.jnlp - jnlp-jardiff - ${jnlp-jardiff.version} - - - ${project.artifactId} @@ -84,8 +64,6 @@ 3.0.2 - 1.6.0 - 1.6.0 diff --git a/kaniko/dockerfile b/kaniko/dockerfile new file mode 100644 index 0000000000..0290bf16ed --- /dev/null +++ b/kaniko/dockerfile @@ -0,0 +1,2 @@ +FROM ubuntu +ENTRYPOINT ["/bin/bash", "-c", "echo hello"] diff --git a/kaniko/pod.yaml b/kaniko/pod.yaml new file mode 100644 index 0000000000..17f9a81b6d --- /dev/null +++ b/kaniko/pod.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Pod +metadata: + name: kaniko +spec: + containers: + - name: kaniko + image: gcr.io/kaniko-project/executor:latest + args: ["--dockerfile=/workspace/dockerfile", + "--context=dir://workspace", + "--no-push"] + volumeMounts: + - name: dockerfile-storage + mountPath: /workspace + restartPolicy: Never + volumes: + - name: dockerfile-storage + persistentVolumeClaim: + claimName: dockerfile-claim diff --git a/kaniko/volume-claim.yaml b/kaniko/volume-claim.yaml new file mode 100644 index 0000000000..7a1abbf05c --- /dev/null +++ b/kaniko/volume-claim.yaml @@ -0,0 +1,11 @@ +kind: PersistentVolumeClaim +apiVersion: v1 +metadata: + name: dockerfile-claim +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 8Gi + storageClassName: local-storage diff --git a/kaniko/volume.yaml b/kaniko/volume.yaml new file mode 100644 index 0000000000..e44663ec5a --- /dev/null +++ b/kaniko/volume.yaml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: PersistentVolume +metadata: + name: dockerfile + labels: + type: local +spec: + capacity: + storage: 10Gi + accessModes: + - ReadWriteOnce + storageClassName: local-storage + hostPath: + path: /home/docker/kaniko # Path to the local mount directory that was setup diff --git a/kotlin-libraries-2/README.md b/kotlin-libraries-2/README.md index 4064ef67d8..f725048acd 100644 --- a/kotlin-libraries-2/README.md +++ b/kotlin-libraries-2/README.md @@ -8,4 +8,7 @@ This module contains articles about Kotlin Libraries. - [Introduction to RxKotlin](https://www.baeldung.com/rxkotlin) - [MockK: A Mocking Library for Kotlin](https://www.baeldung.com/kotlin-mockk) - [Kotlin Immutable Collections](https://www.baeldung.com/kotlin-immutable-collections) +- [Dependency Injection for Kotlin with Injekt](https://www.baeldung.com/kotlin-dependency-injection-with-injekt) +- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel) +- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant) - More articles: [[<-- prev]](/kotlin-libraries) diff --git a/kotlin-libraries-2/pom.xml b/kotlin-libraries-2/pom.xml index 518142403e..254f2c6907 100644 --- a/kotlin-libraries-2/pom.xml +++ b/kotlin-libraries-2/pom.xml @@ -21,7 +21,7 @@ io.reactivex.rxjava2 rxkotlin - 2.3.0 + ${rxkotlin.version} junit @@ -39,6 +39,37 @@ kotlinx-collections-immutable ${kotlinx-collections-immutable.version} + + uy.kohesive.injekt + injekt-core + ${injekt-core.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 + ${kovenant.version} + pom + io.mockk @@ -49,9 +80,13 @@ + 1.16.1 + 1.15.0 + 3.3.0 27.1-jre 1.9.3 0.1 + 2.3.0 diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Interceptors.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Interceptors.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Post.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Post.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/injekt/DelegateInjectionApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/DelegateInjectionApplication.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/injekt/DelegateInjectionApplication.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/DelegateInjectionApplication.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt similarity index 80% rename from core-kotlin/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt index 744459b7fe..4205678981 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt +++ b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt @@ -1,8 +1,12 @@ package com.baeldung.injekt import org.slf4j.LoggerFactory -import uy.kohesive.injekt.* -import uy.kohesive.injekt.api.* +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.InjektMain +import uy.kohesive.injekt.api.InjektRegistrar +import uy.kohesive.injekt.api.addPerKeyFactory +import uy.kohesive.injekt.api.addSingletonFactory +import uy.kohesive.injekt.api.get class KeyedApplication { companion object : InjektMain() { diff --git a/core-kotlin/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt similarity index 94% rename from core-kotlin/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt index e802f3f6d5..96a0c9556a 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt +++ b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt @@ -1,7 +1,8 @@ package com.baeldung.injekt import org.slf4j.LoggerFactory -import uy.kohesive.injekt.* +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.InjektMain import uy.kohesive.injekt.api.* class ModularApplication { diff --git a/core-kotlin/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt similarity index 84% rename from core-kotlin/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt index a42f314349..f3167bc223 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt +++ b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt @@ -1,8 +1,12 @@ package com.baeldung.injekt import org.slf4j.LoggerFactory -import uy.kohesive.injekt.* -import uy.kohesive.injekt.api.* +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.InjektMain +import uy.kohesive.injekt.api.InjektRegistrar +import uy.kohesive.injekt.api.addPerThreadFactory +import uy.kohesive.injekt.api.addSingletonFactory +import uy.kohesive.injekt.api.get import java.util.* import java.util.concurrent.Executors import java.util.concurrent.TimeUnit diff --git a/core-kotlin/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt similarity index 75% rename from core-kotlin/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt index 2b07cd059f..5c2dc28ba5 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt +++ b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt @@ -1,8 +1,12 @@ package com.baeldung.injekt import org.slf4j.LoggerFactory -import uy.kohesive.injekt.* -import uy.kohesive.injekt.api.* +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.InjektMain +import uy.kohesive.injekt.api.InjektRegistrar +import uy.kohesive.injekt.api.addSingleton +import uy.kohesive.injekt.api.addSingletonFactory +import uy.kohesive.injekt.api.get class SimpleApplication { companion object : InjektMain() { diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpLiveTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpLiveTest.kt new file mode 100644 index 0000000000..69b6ae88c6 --- /dev/null +++ b/kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpLiveTest.kt @@ -0,0 +1,280 @@ +package com.baeldung.fuel + +import com.github.kittinunf.fuel.Fuel +import com.github.kittinunf.fuel.core.FuelManager +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 org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Test +import java.io.File +import java.util.concurrent.CountDownLatch + +/** + * These live tests make connections to the external systems: http://httpbin.org, https://jsonplaceholder.typicode.com + * Make sure these hosts are up and your internet connection is on before running the tests. + */ +internal class FuelHttpLiveTest { + + @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() + + } + + +// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library +// @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 -> }) +// } + +// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library +// @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/KovenantTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTest.kt similarity index 99% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTest.kt index 469118f0f6..046b7380f7 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt +++ b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.kovenant import nl.komponents.kovenant.* import nl.komponents.kovenant.Kovenant.deferred @@ -12,6 +12,7 @@ import java.util.* import java.util.concurrent.TimeUnit class KovenantTest { + @Before fun setupTestMode() { Kovenant.testMode { error -> diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTimeoutTest.kt similarity index 96% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTimeoutTest.kt index e37d2cc2fa..d98f9c538f 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt +++ b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTimeoutTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.kovenant import nl.komponents.kovenant.Promise import nl.komponents.kovenant.any diff --git a/kotlin-libraries/README.md b/kotlin-libraries/README.md index 99a57c8293..570bf9b1e5 100644 --- a/kotlin-libraries/README.md +++ b/kotlin-libraries/README.md @@ -10,7 +10,6 @@ This module contains articles about Kotlin Libraries. - [Writing Specifications with Kotlin and Spek](https://www.baeldung.com/kotlin-spek) - [Processing JSON with Kotlin and Klaxson](https://www.baeldung.com/kotlin-json-klaxson) - [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence) -- [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates) - [Introduction to Arrow in Kotlin](https://www.baeldung.com/kotlin-arrow) - [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor) - [REST API With Kotlin and Kovert](https://www.baeldung.com/kotlin-kovert) diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index dfd1dc363f..0d6e589377 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -33,19 +33,19 @@ org.jetbrains.spek spek-api - 1.1.5 + ${spek.version} test org.jetbrains.spek spek-subject-extension - 1.1.5 + ${spek.version} test org.jetbrains.spek spek-junit-platform-engine - 1.1.5 + ${spek.version} test @@ -166,6 +166,7 @@ 2.6 2.3.0 0.7.3 + 1.1.5 diff --git a/kotlin-quasar/pom.xml b/kotlin-quasar/pom.xml index a12d27c565..ec37fa8059 100644 --- a/kotlin-quasar/pom.xml +++ b/kotlin-quasar/pom.xml @@ -48,7 +48,7 @@ junit junit - 4.12 + ${junit.version} @@ -103,7 +103,7 @@ maven-dependency-plugin - 3.1.1 + ${dependency.plugin.version} getClasspathFilenames @@ -116,7 +116,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.1 + ${surefire.plugin.version} -Dco.paralleluniverse.fibers.verifyInstrumentation=true -javaagent:${co.paralleluniverse:quasar-core:jar} @@ -125,7 +125,7 @@ org.codehaus.mojo exec-maven-plugin - 1.3.2 + ${exec.plugin.version} target/classes echo @@ -145,6 +145,10 @@ 1.3.31 1.7.21 1.1.7 + 3.1.1 + 2.22.1 + 1.3.2 + 4.12 diff --git a/lagom/build.sbt b/lagom/build.sbt index 06927e3301..19aeccbd07 100644 --- a/lagom/build.sbt +++ b/lagom/build.sbt @@ -1,4 +1,4 @@ -organization in ThisBuild := "org.baeldung" +organization in ThisBuild := "com.baeldung" // the Scala version that will be used for cross-compiled libraries scalaVersion in ThisBuild := "2.11.8" diff --git a/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java new file mode 100644 index 0000000000..e212c45437 --- /dev/null +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java @@ -0,0 +1,23 @@ +package com.baeldung.lagom.helloworld.greeting.api; + +import static com.lightbend.lagom.javadsl.api.Service.named; +import static com.lightbend.lagom.javadsl.api.Service.restCall; + +import com.lightbend.lagom.javadsl.api.Descriptor; +import com.lightbend.lagom.javadsl.api.Service; +import com.lightbend.lagom.javadsl.api.ServiceCall; +import com.lightbend.lagom.javadsl.api.transport.Method; + +import akka.NotUsed; + +public interface GreetingService extends Service { + + public ServiceCall handleGreetFrom(String user); + + @Override + default Descriptor descriptor() { + return named("greetingservice").withCalls( + restCall(Method.GET, "/api/greeting/:fromUser", this::handleGreetFrom) + ).withAutoAcl(true); + } +} \ No newline at end of file diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java similarity index 94% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java index be9e713ec9..30d3930b75 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java similarity index 85% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java index 91fc74039d..125cf4bf38 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java @@ -1,9 +1,9 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import java.util.Optional; -import org.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; -import org.baeldung.lagom.helloworld.greeting.impl.GreetingEvent.ReceivedGreetingEvent; +import com.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; +import com.baeldung.lagom.helloworld.greeting.impl.GreetingEvent.ReceivedGreetingEvent; import com.lightbend.lagom.javadsl.persistence.PersistentEntity; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java similarity index 90% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java index e454f6cd1b..8800177add 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.lightbend.lagom.serialization.Jsonable; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java similarity index 85% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java index c28687291e..0c79b0d468 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java @@ -1,12 +1,12 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import org.baeldung.lagom.helloworld.greeting.api.GreetingService; -import org.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; -import org.baeldung.lagom.helloworld.weather.api.WeatherService; -import org.baeldung.lagom.helloworld.weather.api.WeatherStats; +import com.baeldung.lagom.helloworld.greeting.api.GreetingService; +import com.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; +import com.baeldung.lagom.helloworld.weather.api.WeatherService; +import com.baeldung.lagom.helloworld.weather.api.WeatherStats; import com.google.inject.Inject; import com.lightbend.lagom.javadsl.api.ServiceCall; diff --git a/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java new file mode 100644 index 0000000000..ba5142a5e6 --- /dev/null +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java @@ -0,0 +1,18 @@ +package com.baeldung.lagom.helloworld.greeting.impl; + +import com.baeldung.lagom.helloworld.greeting.api.GreetingService; +import com.baeldung.lagom.helloworld.weather.api.WeatherService; + +import com.google.inject.AbstractModule; +import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; + +/** + * The module that binds the GreetingService so that it can be served. + */ +public class GreetingServiceModule extends AbstractModule implements ServiceGuiceSupport { + @Override + protected void configure() { + bindServices(serviceBinding(GreetingService.class, GreetingServiceImpl.class)); + bindClient(WeatherService.class); + } +} diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingState.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java similarity index 89% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingState.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java index 125795601e..023c0510ae 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingState.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; diff --git a/lagom/greeting-api/src/main/java/org/baeldung/lagom/helloworld/greeting/api/GreetingService.java b/lagom/greeting-api/src/main/java/org/baeldung/lagom/helloworld/greeting/api/GreetingService.java deleted file mode 100644 index 93567f0185..0000000000 --- a/lagom/greeting-api/src/main/java/org/baeldung/lagom/helloworld/greeting/api/GreetingService.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.lagom.helloworld.greeting.api; - -import static com.lightbend.lagom.javadsl.api.Service.named; -import static com.lightbend.lagom.javadsl.api.Service.restCall; - -import com.lightbend.lagom.javadsl.api.Descriptor; -import com.lightbend.lagom.javadsl.api.Service; -import com.lightbend.lagom.javadsl.api.ServiceCall; -import com.lightbend.lagom.javadsl.api.transport.Method; - -import akka.NotUsed; - -public interface GreetingService extends Service { - - public ServiceCall handleGreetFrom(String user); - - @Override - default Descriptor descriptor() { - return named("greetingservice").withCalls( - restCall(Method.GET, "/api/greeting/:fromUser", this::handleGreetFrom) - ).withAutoAcl(true); - } -} \ No newline at end of file diff --git a/lagom/greeting-impl/bin/application.conf b/lagom/greeting-impl/bin/application.conf index 1e78ce4a79..3fd21ae72b 100644 --- a/lagom/greeting-impl/bin/application.conf +++ b/lagom/greeting-impl/bin/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file diff --git a/lagom/greeting-impl/bin/classes/application.conf b/lagom/greeting-impl/bin/classes/application.conf index 1e78ce4a79..3fd21ae72b 100644 --- a/lagom/greeting-impl/bin/classes/application.conf +++ b/lagom/greeting-impl/bin/classes/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java b/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java deleted file mode 100644 index 4813e91a7c..0000000000 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.lagom.helloworld.greeting.impl; - -import org.baeldung.lagom.helloworld.greeting.api.GreetingService; -import org.baeldung.lagom.helloworld.weather.api.WeatherService; - -import com.google.inject.AbstractModule; -import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; - -/** - * The module that binds the GreetingService so that it can be served. - */ -public class GreetingServiceModule extends AbstractModule implements ServiceGuiceSupport { - @Override - protected void configure() { - bindServices(serviceBinding(GreetingService.class, GreetingServiceImpl.class)); - bindClient(WeatherService.class); - } -} diff --git a/lagom/greeting-impl/src/main/resources/application.conf b/lagom/greeting-impl/src/main/resources/application.conf index 1e78ce4a79..3fd21ae72b 100644 --- a/lagom/greeting-impl/src/main/resources/application.conf +++ b/lagom/greeting-impl/src/main/resources/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file diff --git a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherService.java b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java similarity index 93% rename from lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherService.java rename to lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java index 888109322b..a0749222eb 100644 --- a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherService.java +++ b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.weather.api; +package com.baeldung.lagom.helloworld.weather.api; import static com.lightbend.lagom.javadsl.api.Service.named; import static com.lightbend.lagom.javadsl.api.Service.*; diff --git a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherStats.java b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java similarity index 93% rename from lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherStats.java rename to lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java index 23530a297d..aa04c5ad86 100644 --- a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherStats.java +++ b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.weather.api; +package com.baeldung.lagom.helloworld.weather.api; import java.util.Arrays; import java.util.Collections; diff --git a/lagom/weather-impl/bin/application.conf b/lagom/weather-impl/bin/application.conf index cf6cec2115..53d2dff8f2 100644 --- a/lagom/weather-impl/bin/application.conf +++ b/lagom/weather-impl/bin/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file diff --git a/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java new file mode 100644 index 0000000000..38e4b4d28f --- /dev/null +++ b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java @@ -0,0 +1,19 @@ +package com.baeldung.lagom.helloworld.weather.impl; + +import java.util.concurrent.CompletableFuture; + +import com.baeldung.lagom.helloworld.weather.api.WeatherService; +import com.baeldung.lagom.helloworld.weather.api.WeatherStats; + +import com.lightbend.lagom.javadsl.api.ServiceCall; + +import akka.NotUsed; + +public class WeatherServiceImpl implements WeatherService { + + @Override + public ServiceCall weatherStatsForToday() { + return (req) -> CompletableFuture.completedFuture(WeatherStats.forToday()); + } + +} diff --git a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java similarity index 78% rename from lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java rename to lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java index ac2834ff5c..85257ffa47 100644 --- a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java +++ b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java @@ -1,6 +1,6 @@ -package org.baeldung.lagom.helloworld.weather.impl; +package com.baeldung.lagom.helloworld.weather.impl; -import org.baeldung.lagom.helloworld.weather.api.WeatherService; +import com.baeldung.lagom.helloworld.weather.api.WeatherService; import com.google.inject.AbstractModule; import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; diff --git a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java b/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java deleted file mode 100644 index d7f97f9105..0000000000 --- a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung.lagom.helloworld.weather.impl; - -import java.util.concurrent.CompletableFuture; - -import org.baeldung.lagom.helloworld.weather.api.WeatherService; -import org.baeldung.lagom.helloworld.weather.api.WeatherStats; - -import com.lightbend.lagom.javadsl.api.ServiceCall; - -import akka.NotUsed; - -public class WeatherServiceImpl implements WeatherService { - - @Override - public ServiceCall weatherStatsForToday() { - return (req) -> CompletableFuture.completedFuture(WeatherStats.forToday()); - } - -} diff --git a/lagom/weather-impl/src/main/resources/application.conf b/lagom/weather-impl/src/main/resources/application.conf index cf6cec2115..53d2dff8f2 100644 --- a/lagom/weather-impl/src/main/resources/application.conf +++ b/lagom/weather-impl/src/main/resources/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file diff --git a/libraries-2/README.md b/libraries-2/README.md index 95c454edbb..8dae12a1cf 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -14,11 +14,9 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors) - [Templating with Handlebars](https://www.baeldung.com/handlebars) - [A Guide to Crawler4j](https://www.baeldung.com/crawler4j) -- [Decode an OkHttp JSON Response](https://www.baeldung.com/okhttp-json-response) - [Key Value Store with Chronicle Map](https://www.baeldung.com/java-chronicle-map) - [Guide to MapDB](https://www.baeldung.com/mapdb) - [A Guide to Apache Mesos](https://www.baeldung.com/apache-mesos) -- [JasperReports with Spring](https://www.baeldung.com/spring-jasper)] -- [Jetty ReactiveStreams HTTP Client](https://www.baeldung.com/jetty-reactivestreams-http-client) -- More articles [[<-- prev]](/libraries) +- [JasperReports with Spring](https://www.baeldung.com/spring-jasper) +- More articles [[<-- prev]](/libraries) [[next -->]](/libraries-3) diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 474ff563c2..3aa36c3f90 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -75,28 +75,7 @@ - - - com.squareup.okhttp3 - okhttp - ${okhttp.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.google.code.gson - gson - ${gson.version} - - - com.squareup.okhttp3 - mockwebserver - ${mockwebserver.version} - test - + edu.uci.ics crawler4j @@ -151,9 +130,6 @@ 2.1.4.RELEASE 0.28.3 1.1.0 - 3.14.2 - 2.8.5 - 3.14.2 4.1.2 6.6.0 5.1.9.RELEASE diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java index 6749f7fe0a..357bb7df89 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java @@ -1,14 +1,15 @@ package com.baeldung.handlebars; -import static org.assertj.core.api.Assertions.assertThat; - import com.github.jknack.handlebars.Handlebars; import com.github.jknack.handlebars.Template; import com.github.jknack.handlebars.io.ClassPathTemplateLoader; import com.github.jknack.handlebars.io.TemplateLoader; -import java.io.IOException; import org.junit.Test; +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; + /** * Showcases the built-in template helpers. * @@ -27,7 +28,7 @@ public class BuiltinHelperUnitTest { String templateString = template.apply(person); - assertThat(templateString).isEqualTo("\n

I live in World

\n"); + assertThat(templateString).contains("

I live in World

"); } @Test @@ -39,7 +40,7 @@ public class BuiltinHelperUnitTest { String templateString = template.apply(person); - assertThat(templateString).isEqualTo("\n

I live in World

\n"); + assertThat(templateString).contains("

I live in World

"); } @Test @@ -54,8 +55,8 @@ public class BuiltinHelperUnitTest { String templateString = template.apply(person); - assertThat(templateString).isEqualTo("\nJava is my friend.\n" - + "\nSpring is my friend.\n"); + assertThat(templateString) + .contains("Java is my friend.", "Spring is my friend."); } @Test @@ -70,8 +71,8 @@ public class BuiltinHelperUnitTest { String templateString = template.apply(person); - assertThat(templateString).isEqualTo("\nJava is my friend.\n" - + "\nSpring is my friend.\n"); + assertThat(templateString) + .contains("Java is my friend.", "Spring is my friend."); } @Test @@ -83,7 +84,7 @@ public class BuiltinHelperUnitTest { String templateString = template.apply(person); - assertThat(templateString).isEqualTo("\n

Baeldung is busy.

\n"); + assertThat(templateString).contains("

Baeldung is busy.

"); } @Test @@ -95,7 +96,7 @@ public class BuiltinHelperUnitTest { String templateString = template.apply(person); - assertThat(templateString).isEqualTo("\n

Baeldung is busy.

\n"); + assertThat(templateString).contains("

Baeldung is busy.

"); } private Person getPerson(String name) { diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java index 36f78f486e..376e44e4bd 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java @@ -1,14 +1,15 @@ package com.baeldung.handlebars; -import static org.assertj.core.api.Assertions.assertThat; - import com.github.jknack.handlebars.Handlebars; import com.github.jknack.handlebars.Template; import com.github.jknack.handlebars.io.ClassPathTemplateLoader; import com.github.jknack.handlebars.io.TemplateLoader; -import java.io.IOException; import org.junit.Test; +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; + /** * Showcases reusing the existing templates. * @@ -27,7 +28,8 @@ public class ReusingTemplatesUnitTest { String templateString = template.apply(person); - assertThat(templateString).isEqualTo("

Hi Baeldung!

\n

This is the page Baeldung

"); + assertThat(templateString) + .contains("

Hi Baeldung!

", "

This is the page Baeldung

"); } @Test @@ -39,11 +41,11 @@ public class ReusingTemplatesUnitTest { String templateString = template.apply(person); - assertThat(templateString).isEqualTo("\n\n" - + "\n" - + "\n This is the intro\n\n" - + "\n Hi there!\n\n" - + "\n" - + ""); + assertThat(templateString).contains("", + "", + "This is the intro", + "Hi there!", + "", + ""); } } diff --git a/libraries-3/README.md b/libraries-3/README.md index a9d48bb389..6279dcf5ad 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -9,3 +9,12 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m ### Relevant Articles: - [Parsing Command-Line Parameters with JCommander](https://www.baeldung.com/jcommander-parsing-command-line-parameters) +- [Guide to the Cactoos Library](https://www.baeldung.com/java-cactoos) +- [Parsing Command-Line Parameters with Airline](https://www.baeldung.com/java-airline) +- [Introduction to cache2k](https://www.baeldung.com/java-cache2k) +- [Introduction to the jcabi-aspects AOP Annotations Library](https://www.baeldung.com/java-jcabi-aspects) +- [Introduction to Takes](https://www.baeldung.com/java-takes) +- [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) +- [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro) +- [Quick Guide to Spring Cloud Circuit Breaker](https://www.baeldung.com/spring-cloud-circuit-breaker) +- More articles [[<-- prev]](/libraries-2) [[next -->]](/libraries-4) diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index c8980fd309..5334bfba70 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -23,10 +23,212 @@ lombok ${lombok.version}
+ + com.github.rvesse + airline + ${airline.version} + + + org.cactoos + cactoos + ${cactoos.version} + + + org.cache2k + cache2k-base-bom + ${cache2k.version} + pom + + + com.jcabi + jcabi-aspects + ${jcabi-aspects.version} + + + org.aspectj + aspectjrt + ${aspectjrt.version} + runtime + + + org.takes + takes + ${takes.version} + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + org.apache.velocity + velocity-engine-core + ${velocity-engine-core.version} + + + com.uber.nullaway + nullaway + 0.3.0 + + + org.codehaus.plexus + plexus-compiler-javac-errorprone + 2.8 + + + + com.google.errorprone + error_prone_core + 2.1.3 + + + + jitpack.io + https://jitpack.io + + + + + libraries-3 + + + com.jcabi + jcabi-maven-plugin + ${jcabi-maven-plugin.version} + + + + ajc + + + + + + org.aspectj + aspectjtools + ${aspectjtools.version} + + + org.aspectj + aspectjweaver + ${aspectjweaver.version} + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5 + + javac-with-errorprone + true + 1.8 + 1.8 + true + + + com.uber.nullaway + nullaway + 0.3.0 + + + + + + -XepExcludedPaths:(.*)/test/.*|(.*)/jcabi/.* + -XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway + + + + + org.codehaus.plexus + plexus-compiler-javac-errorprone + 2.8 + + + + com.google.errorprone + error_prone_core + 2.3.4 + + + + + + + src/main/webapp + true + + + + + + + reload + + + + src/main/resources + true + + + src/main/webapp + true + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + start-server + pre-integration-test + + java + + + + + com.baeldung.takes.TakesApp + false + + --port=${port} + + + + + + + + 1.78 1.18.6 + + 0.43 + 2.7.2 + 1.2.3.Final + 0.22.6 + 1.9.2 + 0.14.1 + 1.9.2 + 1.9.2 + + 1.19 + 4.4.13 + 4.5.12 + 2.2 + 1.6.0
diff --git a/libraries-3/src/main/java/com/baeldung/airline/CommandLine.java b/libraries-3/src/main/java/com/baeldung/airline/CommandLine.java new file mode 100644 index 0000000000..b4c3fc9b9e --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/airline/CommandLine.java @@ -0,0 +1,17 @@ +package com.baeldung.airline; + +import com.github.rvesse.airline.annotations.Cli; +import com.github.rvesse.airline.help.Help; + +@Cli(name = "baeldung-cli", +description = "Baeldung Airline Tutorial", +defaultCommand = Help.class, +commands = { DatabaseSetupCommand.class, LoggingCommand.class, Help.class }) +public class CommandLine { + + public static void main(String[] args) { + com.github.rvesse.airline.Cli cli = new com.github.rvesse.airline.Cli<>(CommandLine.class); + Runnable cmd = cli.parse(args); + cmd.run(); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/airline/DatabaseSetupCommand.java b/libraries-3/src/main/java/com/baeldung/airline/DatabaseSetupCommand.java new file mode 100644 index 0000000000..bf67fa33b6 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/airline/DatabaseSetupCommand.java @@ -0,0 +1,77 @@ +package com.baeldung.airline; + +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Inject; + +import com.github.rvesse.airline.HelpOption; +import com.github.rvesse.airline.annotations.Command; +import com.github.rvesse.airline.annotations.Option; +import com.github.rvesse.airline.annotations.OptionType; +import com.github.rvesse.airline.annotations.restrictions.AllowedRawValues; +import com.github.rvesse.airline.annotations.restrictions.MutuallyExclusiveWith; +import com.github.rvesse.airline.annotations.restrictions.Pattern; +import com.github.rvesse.airline.annotations.restrictions.RequiredOnlyIf; + +@Command(name = "setup-db", description = "Setup our database") +public class DatabaseSetupCommand implements Runnable { + @Inject + private HelpOption help; + + @Option(type = OptionType.COMMAND, + name = {"-d", "--database"}, + description = "Type of RDBMS.", + title = "RDBMS type: mysql|postgresql|mongodb") + @AllowedRawValues(allowedValues = { "mysql", "postgres", "mongodb" }) + protected String rdbmsMode = "mysql"; + + @Option(type = OptionType.COMMAND, + name = {"--rdbms:url", "--url"}, + description = "URL to use for connection to RDBMS.", + title = "RDBMS URL") + @MutuallyExclusiveWith(tag="mode") + @Pattern(pattern="^(http://.*):(d*)(.*)u=(.*)&p=(.*)") + protected String rdbmsUrl = ""; + + @Option(type = OptionType.COMMAND, + name = {"--rdbms:host", "--host"}, + description = "Host to use for connection to RDBMS.", + title = "RDBMS host") + @MutuallyExclusiveWith(tag="mode") + protected String rdbmsHost = ""; + + @RequiredOnlyIf(names={"--rdbms:host", "--host"}) + @Option(type = OptionType.COMMAND, + name = {"--rdbms:user", "-u", "--user"}, + description = "User for login to RDBMS.", + title = "RDBMS user") + protected String rdbmsUser; + + @RequiredOnlyIf(names={"--rdbms:host", "--host"}) + @Option(type = OptionType.COMMAND, + name = {"--rdbms:password", "--password"}, + description = "Password for login to RDBMS.", + title = "RDBMS password") + protected String rdbmsPassword; + + @Option(type = OptionType.COMMAND, + name = {"--driver", "--jars"}, + description = "List of drivers", + title = "--driver --driver ") + protected List jars = new ArrayList<>(); + + @Override + public void run() { + //skipping store our choices... + if (!help.showHelpIfRequested()) { + if(!"".equals(rdbmsHost)) { + System.out.println("Connecting to database host: " + rdbmsHost); + System.out.println("Credential: " + rdbmsUser + " / " + rdbmsPassword); + } else { + System.out.println("Connecting to database url: " + rdbmsUrl); + } + System.out.println(jars.toString()); + } + } +} diff --git a/libraries-3/src/main/java/com/baeldung/airline/LoggingCommand.java b/libraries-3/src/main/java/com/baeldung/airline/LoggingCommand.java new file mode 100644 index 0000000000..4a269f87fd --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/airline/LoggingCommand.java @@ -0,0 +1,24 @@ +package com.baeldung.airline; + +import javax.inject.Inject; + +import com.github.rvesse.airline.HelpOption; +import com.github.rvesse.airline.annotations.Command; +import com.github.rvesse.airline.annotations.Option; + +@Command(name = "setup-log", description = "Setup our log") +public class LoggingCommand implements Runnable { + + @Inject + private HelpOption help; + + @Option(name = { "-v", "--verbose" }, description = "Set log verbosity on/off") + private boolean verbose = false; + + @Override + public void run() { + //skipping store user choice + if (!help.showHelpIfRequested()) + System.out.println("Verbosity: " + verbose); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/arthas/FibonacciGenerator.java b/libraries-3/src/main/java/com/baeldung/arthas/FibonacciGenerator.java new file mode 100644 index 0000000000..27cf0dacf6 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/arthas/FibonacciGenerator.java @@ -0,0 +1,25 @@ +package com.baeldung.arthas; + +import java.io.IOException; + +import static java.lang.String.format; + +public class FibonacciGenerator { + + public static void main(String[] args) throws IOException { + System.out.println("Press a key to continue"); + System.in.read(); + for (int i = 0; i < 100; i++) { + long result = fibonacci(i); + System.out.println(format("fib(%d): %d", i, result)); + } + } + + public static long fibonacci(int n) { + if (n == 0 || n == 1) { + return 1L; + } else { + return fibonacci(n - 1) + fibonacci(n - 2); + } + } +} diff --git a/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelper.java b/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelper.java new file mode 100644 index 0000000000..cc646c9e17 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelper.java @@ -0,0 +1,36 @@ +package com.baeldung.cache2k; + +import java.util.Objects; + +import org.cache2k.Cache; +import org.cache2k.Cache2kBuilder; + +public class ProductHelper { + + private Cache cachedDiscounts; + + private int cacheMissCount = 0; + + public ProductHelper() { + cachedDiscounts = Cache2kBuilder.of(String.class, Integer.class) + .name("discount") + .eternal(true) + .entryCapacity(100) + .build(); + } + + public Integer getDiscount(String productType) { + Integer discount = cachedDiscounts.get(productType); + if (Objects.isNull(discount)) { + cacheMissCount++; + discount = "Sports".equalsIgnoreCase(productType) ? 20 : 10; + cachedDiscounts.put(productType, discount); + } + return discount; + } + + public int getCacheMissCount() { + return cacheMissCount; + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperUsingLoader.java b/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperUsingLoader.java new file mode 100644 index 0000000000..7b2ac4caa1 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperUsingLoader.java @@ -0,0 +1,38 @@ +package com.baeldung.cache2k; + +import java.util.concurrent.TimeUnit; + +import org.cache2k.Cache; +import org.cache2k.Cache2kBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ProductHelperUsingLoader { + + final Logger LOGGER = LoggerFactory.getLogger(ProductHelperUsingLoader.class); + + private Cache cachedDiscounts; + + private int cacheMissCount = 0; + + public ProductHelperUsingLoader() { + cachedDiscounts = Cache2kBuilder.of(String.class, Integer.class) + .name("discount-loader") + .expireAfterWrite(10, TimeUnit.MILLISECONDS) + .entryCapacity(100) + .loader((key) -> { + cacheMissCount++; + return "Sports".equalsIgnoreCase(key) ? 20 : 10; + }) + .build(); + } + + public Integer getDiscount(String productType) { + return cachedDiscounts.get(productType); + } + + public int getCacheMissCount() { + return cacheMissCount; + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperWithEventListener.java b/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperWithEventListener.java new file mode 100644 index 0000000000..90c6ee3adf --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperWithEventListener.java @@ -0,0 +1,46 @@ +package com.baeldung.cache2k; + +import java.util.concurrent.TimeUnit; + +import org.cache2k.Cache; +import org.cache2k.Cache2kBuilder; +import org.cache2k.CacheEntry; +import org.cache2k.event.CacheEntryCreatedListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ProductHelperWithEventListener { + + final Logger LOGGER = LoggerFactory.getLogger(ProductHelperWithEventListener.class); + + private Cache cachedDiscounts; + + private int cacheMissCount = 0; + + public ProductHelperWithEventListener() { + cachedDiscounts = Cache2kBuilder.of(String.class, Integer.class) + .name("discount-listener") + .expireAfterWrite(10, TimeUnit.MILLISECONDS) + .entryCapacity(100) + .loader((key) -> { + cacheMissCount++; + return "Sports".equalsIgnoreCase(key) ? 20 : 10; + }) + .addListener(new CacheEntryCreatedListener() { + @Override + public void onEntryCreated(Cache cache, CacheEntry entry) { + LOGGER.info("Entry created: [{}, {}].", entry.getKey(), entry.getValue()); + } + }) + .build(); + } + + public Integer getDiscount(String productType) { + return cachedDiscounts.get(productType); + } + + public int getCacheMissCount() { + return cacheMissCount; + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperWithExpiry.java b/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperWithExpiry.java new file mode 100644 index 0000000000..22b656fead --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperWithExpiry.java @@ -0,0 +1,38 @@ +package com.baeldung.cache2k; + +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import org.cache2k.Cache; +import org.cache2k.Cache2kBuilder; + +public class ProductHelperWithExpiry { + + private Cache cachedDiscounts; + + private int cacheMissCount = 0; + + public ProductHelperWithExpiry() { + cachedDiscounts = Cache2kBuilder.of(String.class, Integer.class) + .name("discount-expiry") + .expireAfterWrite(5, TimeUnit.MILLISECONDS) + .entryCapacity(100) + .build(); + + } + + public Integer getDiscount(String productType) { + Integer discount = cachedDiscounts.get(productType); + if (Objects.isNull(discount)) { + cacheMissCount++; + discount = "Sports".equalsIgnoreCase(productType) ? 20 : 10; + cachedDiscounts.put(productType, discount); + } + return discount; + } + + public int getCacheMissCount() { + return cacheMissCount; + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java new file mode 100644 index 0000000000..717c63ae63 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java @@ -0,0 +1,28 @@ +package com.baeldung.cactoos; + +import java.util.Collection; +import java.util.List; + +import org.cactoos.collection.Filtered; +import org.cactoos.iterable.IterableOf; +import org.cactoos.list.ListOf; +import org.cactoos.scalar.And; +import org.cactoos.text.FormattedText; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CactoosCollectionUtils { + + final Logger LOGGER = LoggerFactory.getLogger(CactoosCollectionUtils.class); + + public void iterateCollection(List strings) throws Exception { + new And((String input) -> LOGGER.info(new FormattedText("%s\n", input).asString()), strings).value(); + } + + public Collection getFilteredList(List strings) { + Collection filteredStrings = new ListOf<>( + new Filtered<>(string -> string.length() == 5, new IterableOf<>(strings))); + return filteredStrings; + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java new file mode 100644 index 0000000000..3e2903ebf4 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java @@ -0,0 +1,37 @@ +package com.baeldung.cactoos; + +import java.io.IOException; + +import org.cactoos.text.FormattedText; +import org.cactoos.text.IsBlank; +import org.cactoos.text.Lowered; +import org.cactoos.text.TextOf; +import org.cactoos.text.Upper; + +public class CactoosStringUtils { + + public String createString() throws IOException { + String testString = new TextOf("Test String").asString(); + return testString; + } + + public String createdFormattedString(String stringToFormat) throws IOException { + String formattedString = new FormattedText("Hello %s", stringToFormat).asString(); + return formattedString; + } + + public String toLowerCase(String testString) throws IOException { + String lowerCaseString = new Lowered(new TextOf(testString)).asString(); + return lowerCaseString; + } + + public String toUpperCase(String testString) throws Exception { + String upperCaseString = new Upper(new TextOf(testString)).asString(); + return upperCaseString; + } + + public boolean isBlank(String testString) throws Exception { + return new IsBlank(new TextOf(testString)) != null; + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/jcabi/JcabiAspectJ.java b/libraries-3/src/main/java/com/baeldung/jcabi/JcabiAspectJ.java new file mode 100644 index 0000000000..6bd345c59c --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcabi/JcabiAspectJ.java @@ -0,0 +1,112 @@ +package com.baeldung.jcabi; + + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import com.jcabi.aspects.Async; +import com.jcabi.aspects.Cacheable; +import com.jcabi.aspects.LogExceptions; +import com.jcabi.aspects.Loggable; +import com.jcabi.aspects.Quietly; +import com.jcabi.aspects.RetryOnFailure; +import com.jcabi.aspects.UnitedThrow; + +public class JcabiAspectJ { + + public static void main(String[] args) { + try { + displayFactorial(10); + getFactorial(10).get(); + + String result = cacheExchangeRates(); + if (result != cacheExchangeRates()) { + System.out.println(result); + } + + divideByZero(); + } catch(Exception e) { + e.printStackTrace(); + } + + divideByZeroQuietly(); + try { + processFile(); + } catch(Exception e) { + e.printStackTrace(); + } + + } + + @Loggable + @Async + public static void displayFactorial(int number) { + long result = factorial(number); + System.out.println(result); + } + + @Loggable + @Async + public static Future getFactorial(int number) { + Future factorialFuture = CompletableFuture.supplyAsync(() -> factorial(number)); + return factorialFuture; + } + + /** + * Finds factorial of a number + * @param number + * @return + */ + public static long factorial(int number) { + long result = 1; + for(int i=number;i>0;i--) { + result *= i; + } + return result; + } + + @Loggable + @Cacheable(lifetime = 2, unit = TimeUnit.SECONDS) + public static String cacheExchangeRates() { + String result = null; + try { + URL exchangeRateUrl = new URL("https://api.exchangeratesapi.io/latest"); + URLConnection con = exchangeRateUrl.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + result = in.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + + @LogExceptions + public static void divideByZero() { + int x = 1/0; + } + + @RetryOnFailure(attempts = 2, types = {java.lang.NumberFormatException.class}) + @Quietly + public static void divideByZeroQuietly() { + int x = 1/0; + } + + @UnitedThrow(IllegalStateException.class) + public static void processFile() throws IOException, InterruptedException { + BufferedReader reader = new BufferedReader(new FileReader("baeldung.txt")); + reader.readLine(); + + Thread thread = new Thread(); + thread.wait(2000); + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java b/libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java new file mode 100644 index 0000000000..1fab591cb0 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java @@ -0,0 +1,22 @@ +package com.baeldung.nullaway; + +public class NullAwayExample { + + /* + * 1- NullAway will warn about yearsToRetirement method + * 2- Uncomment @Nullable in printAge and NullAway will warn about this method + * 3- Add a standard null check to be NullAway compliant + * 4- Build will be SUCCESS + */ + + static Integer getAge(/*@Nullable*/ Person person) { + return person.getAge(); + } + + Integer yearsToRetirement() { + Person p = null; + // ... p never gets set correctly... + return 65 - getAge(p); + } + +} \ No newline at end of file diff --git a/libraries-3/src/main/java/com/baeldung/nullaway/Person.java b/libraries-3/src/main/java/com/baeldung/nullaway/Person.java new file mode 100644 index 0000000000..fcd88036a1 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/nullaway/Person.java @@ -0,0 +1,65 @@ +package com.baeldung.nullaway; + +public class Person { + int age; + String name; + String email; + + public Person(int age, String name, String email) { + super(); + this.age = age; + this.name = name; + this.email = email; + } + + public int getAge() { + return age; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Person [age="); + builder.append(age); + builder.append(", name="); + builder.append(name); + builder.append(", email="); + builder.append(email); + builder.append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Person other = (Person) obj; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + return true; + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/takes/TakesApp.java b/libraries-3/src/main/java/com/baeldung/takes/TakesApp.java new file mode 100644 index 0000000000..3c1407c291 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/takes/TakesApp.java @@ -0,0 +1,42 @@ +package com.baeldung.takes; + +import java.io.IOException; +import java.sql.SQLException; + +import org.takes.Response; +import org.takes.facets.fallback.Fallback; +import org.takes.facets.fallback.FbChain; +import org.takes.facets.fallback.FbStatus; +import org.takes.facets.fallback.RqFallback; +import org.takes.facets.fallback.TkFallback; +import org.takes.facets.fork.FkRegex; +import org.takes.facets.fork.TkFork; +import org.takes.http.Exit; +import org.takes.http.FtBasic; +import org.takes.misc.Opt; +import org.takes.rs.RsText; + +public final class TakesApp { + + public static void main(final String... args) throws IOException, SQLException { + new FtBasic( + new TkFallback( + new TkFork( + new FkRegex("/", new TakesHelloWorld()), + new FkRegex("/index", new TakesIndex()), + new FkRegex("/contact", new TakesContact()) + ), + new FbChain( + new FbStatus(404, new RsText("Page Not Found")), + new FbStatus(405, new RsText("Method Not Allowed")), + new Fallback() { + @Override + public Opt route(final RqFallback req) { + return new Opt.Single(new RsText(req.throwable().getMessage())); + } + }) + ), 6060 + ).start(Exit.NEVER); + } + +} \ No newline at end of file diff --git a/libraries-3/src/main/java/com/baeldung/takes/TakesContact.java b/libraries-3/src/main/java/com/baeldung/takes/TakesContact.java new file mode 100644 index 0000000000..e083bc3dc6 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/takes/TakesContact.java @@ -0,0 +1,22 @@ +package com.baeldung.takes; + +import java.io.IOException; + +import org.takes.Request; +import org.takes.Response; +import org.takes.Take; +import org.takes.rs.RsWithBody; +import org.takes.rs.RsWithStatus; +import org.takes.rs.RsWithType; + +public final class TakesContact implements Take { + + @Override + public Response act(Request req) throws IOException { + return new RsWithStatus( + new RsWithType( + new RsWithBody("Contact us at https://www.baeldung.com"), + "text/html"), 200); + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/takes/TakesHelloWorld.java b/libraries-3/src/main/java/com/baeldung/takes/TakesHelloWorld.java new file mode 100644 index 0000000000..9d1346d3c1 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/takes/TakesHelloWorld.java @@ -0,0 +1,15 @@ +package com.baeldung.takes; + +import org.takes.Request; +import org.takes.Response; +import org.takes.Take; +import org.takes.rs.RsText; + +public class TakesHelloWorld implements Take { + + @Override + public Response act(final Request request) { + return new RsText("Hello, world!"); + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/takes/TakesIndex.java b/libraries-3/src/main/java/com/baeldung/takes/TakesIndex.java new file mode 100644 index 0000000000..3f74ba9c67 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/takes/TakesIndex.java @@ -0,0 +1,24 @@ +package com.baeldung.takes; + +import java.io.IOException; + +import org.takes.Request; +import org.takes.Response; +import org.takes.Take; +import org.takes.rq.form.RqFormSmart; +import org.takes.rs.RsHtml; +import org.takes.rs.RsVelocity; + +public final class TakesIndex implements Take { + + @Override + public Response act(final Request req) throws IOException { + RqFormSmart form = new RqFormSmart(req); + String username = form.single("username"); + return new RsHtml( + new RsVelocity(this.getClass().getResource("/templates/index.vm"), + new RsVelocity.Pair("username", username)) + ); + } + +} diff --git a/libraries-3/src/main/webapp/templates/index.vm b/libraries-3/src/main/webapp/templates/index.vm new file mode 100644 index 0000000000..5a97f654ce --- /dev/null +++ b/libraries-3/src/main/webapp/templates/index.vm @@ -0,0 +1,9 @@ + + +Index + + +

Takes Web Application

+

Welcome, ${username}

+ + diff --git a/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperUnitTest.java b/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperUnitTest.java new file mode 100644 index 0000000000..e9b495279a --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.cache2k; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class ProductHelperUnitTest { + + @Test + public void whenInvokedGetDiscountTwice_thenGetItFromCache() { + ProductHelper productHelper = new ProductHelper(); + assertTrue(productHelper.getCacheMissCount() == 0); + assertTrue(productHelper.getDiscount("Sports") == 20); + assertTrue(productHelper.getDiscount("Sports") == 20); + assertTrue(productHelper.getCacheMissCount() == 1); + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperUsingLoaderUnitTest.java b/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperUsingLoaderUnitTest.java new file mode 100644 index 0000000000..3ad77aa2de --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperUsingLoaderUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.cache2k; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class ProductHelperUsingLoaderUnitTest { + + @Test + public void whenInvokedGetDiscount_thenPopulateCacheUsingLoader() { + ProductHelperUsingLoader productHelper = new ProductHelperUsingLoader(); + assertTrue(productHelper.getCacheMissCount() == 0); + + assertTrue(productHelper.getDiscount("Sports") == 20); + assertTrue(productHelper.getCacheMissCount() == 1); + + assertTrue(productHelper.getDiscount("Electronics") == 10); + assertTrue(productHelper.getCacheMissCount() == 2); + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperWithEventListenerUnitTest.java b/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperWithEventListenerUnitTest.java new file mode 100644 index 0000000000..9aeb9f0552 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperWithEventListenerUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.cache2k; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class ProductHelperWithEventListenerUnitTest { + + @Test + public void whenEntryAddedInCache_thenEventListenerCalled() { + ProductHelperWithEventListener productHelper = new ProductHelperWithEventListener(); + assertTrue(productHelper.getDiscount("Sports") == 20); + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperWithExpiryUnitTest.java b/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperWithExpiryUnitTest.java new file mode 100644 index 0000000000..a3303ca0aa --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperWithExpiryUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.cache2k; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class ProductHelperWithExpiryUnitTest { + + @Test + public void whenInvokedGetDiscountAfterExpiration_thenDiscountCalculatedAgain() throws InterruptedException { + ProductHelperWithExpiry productHelper = new ProductHelperWithExpiry(); + assertTrue(productHelper.getCacheMissCount() == 0); + assertTrue(productHelper.getDiscount("Sports") == 20); + assertTrue(productHelper.getCacheMissCount() == 1); + + Thread.sleep(20); + + assertTrue(productHelper.getDiscount("Sports") == 20); + assertTrue(productHelper.getCacheMissCount() == 2); + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java new file mode 100644 index 0000000000..c6bcbd7df7 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.cactoos; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; + +import org.junit.Test; + +public class CactoosCollectionUtilsUnitTest { + + @Test + public void whenFilteredClassIsCalledWithSpecificArgs_thenCorrespondingFilteredCollectionShouldBeReturned() throws IOException { + + CactoosCollectionUtils obj = new CactoosCollectionUtils(); + + // when + List strings = new ArrayList() { + { + add("Hello"); + add("John"); + add("Smith"); + add("Eric"); + add("Dizzy"); + } + }; + int size = obj.getFilteredList(strings).size(); + + // then + assertEquals(3, size); + + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java new file mode 100644 index 0000000000..67dd6d91e4 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.cactoos; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +public class CactoosStringUtilsUnitTest { + + @Test + public void whenFormattedTextIsPassedWithArgs_thenFormattedStringIsReturned() throws IOException { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + String formattedString = obj.createdFormattedString("John"); + + // then + assertEquals("Hello John", formattedString); + + } + + @Test + public void whenStringIsPassesdToLoweredOrUpperClass_thenCorrespondingStringIsReturned() throws Exception { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + String lowerCaseString = obj.toLowerCase("TeSt StrIng"); + String upperCaseString = obj.toUpperCase("TeSt StrIng"); + + // then + assertEquals("test string", lowerCaseString); + assertEquals("TEST STRING", upperCaseString); + + } + + @Test + public void whenEmptyStringIsPassesd_thenIsBlankReturnsTrue() throws Exception { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + boolean isBlankEmptyString = obj.isBlank(""); + boolean isBlankNull = obj.isBlank(null); + + // then + assertEquals(true, isBlankEmptyString); + assertEquals(true, isBlankNull); + + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/takes/TakesAppIntegrationTest.java b/libraries-3/src/test/java/com/baeldung/takes/TakesAppIntegrationTest.java new file mode 100644 index 0000000000..8b869d0742 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/takes/TakesAppIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.takes; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.net.URI; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.junit.Test; +import org.takes.http.FtRemote; + +public class TakesAppIntegrationTest { + + @Test + public void givenTake_whenRunRemoteServer_thenRespond() throws Exception { + new FtRemote(new TakesContact()).exec( + new FtRemote.Script() { + @Override + public void exec(final URI home) throws IOException { + HttpClient client = HttpClientBuilder.create().build(); + HttpResponse response = client.execute(new HttpGet(home)); + int statusCode = response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String result = EntityUtils.toString(entity); + + assertEquals(200, statusCode); + assertEquals("Contact us at https://www.baeldung.com", result); + } + }); + } +} diff --git a/libraries-3/src/test/java/com/baeldung/takes/TakesContactUnitTest.java b/libraries-3/src/test/java/com/baeldung/takes/TakesContactUnitTest.java new file mode 100644 index 0000000000..5f8b7c57fc --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/takes/TakesContactUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.takes; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.takes.rq.RqFake; +import org.takes.rs.RsPrint; + +public class TakesContactUnitTest { + + @Test + public void givenTake_whenInvokeActMethod_thenRespond() throws Exception { + final String resp = new RsPrint(new TakesContact().act(new RqFake())).printBody(); + assertEquals("Contact us at https://www.baeldung.com", resp); + } + +} diff --git a/libraries-4/README.md b/libraries-4/README.md new file mode 100644 index 0000000000..0dee9f1c1e --- /dev/null +++ b/libraries-4/README.md @@ -0,0 +1,21 @@ +## Libraries-4 + +This module contains articles about various Java libraries. +These are small libraries that are relatively easy to use and do not require any separate module of their own. + +The code examples related to different libraries are each in their own module. + +Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases. + +### Relevant articles +- [Quick Guide to RSS with Rome](https://www.baeldung.com/rome-rss) +- [Introduction to PCollections](https://www.baeldung.com/java-pcollections) +- [Introduction to Eclipse Collections](https://www.baeldung.com/eclipse-collections) +- [DistinctBy in the Java Stream API](https://www.baeldung.com/java-streams-distinct-by) +- [Introduction to NoException](https://www.baeldung.com/no-exception) +- [Spring Yarg Integration](https://www.baeldung.com/spring-yarg) +- [Delete a Directory Recursively in Java](https://www.baeldung.com/java-delete-directory) +- [Guide to JDeferred](https://www.baeldung.com/jdeferred) +- [Introduction to MBassador](https://www.baeldung.com/mbassador) +- [Using Pairs in Java](https://www.baeldung.com/java-pairs) +- More articles [[<-- prev]](/libraries-3) [[next -->]](/libraries-5) diff --git a/libraries-4/pom.xml b/libraries-4/pom.xml new file mode 100644 index 0000000000..f26e7fc055 --- /dev/null +++ b/libraries-4/pom.xml @@ -0,0 +1,116 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + libraries-4 + + + + org.jdeferred + jdeferred-core + ${jdeferred.version} + + + org.eclipse.collections + eclipse-collections + ${eclipse-collections.version} + + + com.haulmont.yarg + yarg + ${yarg.version} + + + net.engio + mbassador + ${mbassador.version} + + + com.machinezoo.noexception + noexception + ${noexception.version} + + + rome + rome + ${rome.version} + + + org.springframework + spring-web + ${spring.version} + + + org.datanucleus + javax.jdo + ${javax.jdo.version} + + + javax.servlet + servlet-api + ${javax.servlet.version} + + + io.vavr + vavr + ${vavr.version} + + + org.assertj + assertj-core + ${assertj.version} + + + org.pcollections + pcollections + ${pcollections.version} + + + org.awaitility + awaitility + ${awaitility.version} + test + + + one.util + streamex + ${streamex.version} + + + javax.el + javax.el-api + ${javax.el.version} + + + org.glassfish.web + javax.el + 2.2.4 + + + + + 1.2.6 + 8.2.0 + 1.1.0 + 2.0.12 + 1.3.1 + 1.0 + 4.3.8.RELEASE + 2.5 + 3.2.0-m7 + 0.9.0 + 3.6.2 + 2.1.2 + 3.0.0 + 0.6.5 + 3.0.0 + + + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java b/libraries-4/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java similarity index 100% rename from libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java rename to libraries-4/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java diff --git a/libraries/src/main/java/com/baeldung/distinct/Person.java b/libraries-4/src/main/java/com/baeldung/distinct/Person.java similarity index 100% rename from libraries/src/main/java/com/baeldung/distinct/Person.java rename to libraries-4/src/main/java/com/baeldung/distinct/Person.java diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java b/libraries-4/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java similarity index 100% rename from libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java rename to libraries-4/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java b/libraries-4/src/main/java/com/baeldung/eclipsecollections/Student.java similarity index 100% rename from libraries/src/main/java/com/baeldung/eclipsecollections/Student.java rename to libraries-4/src/main/java/com/baeldung/eclipsecollections/Student.java diff --git a/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java b/libraries-4/src/main/java/com/baeldung/jdeffered/FilterDemo.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java rename to libraries-4/src/main/java/com/baeldung/jdeffered/FilterDemo.java diff --git a/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java b/libraries-4/src/main/java/com/baeldung/jdeffered/PipeDemo.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java rename to libraries-4/src/main/java/com/baeldung/jdeffered/PipeDemo.java diff --git a/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java b/libraries-4/src/main/java/com/baeldung/jdeffered/PromiseDemo.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java rename to libraries-4/src/main/java/com/baeldung/jdeffered/PromiseDemo.java diff --git a/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java b/libraries-4/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java rename to libraries-4/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerDemo.java b/libraries-4/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerDemo.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerDemo.java rename to libraries-4/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerDemo.java diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java b/libraries-4/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java rename to libraries-4/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java b/libraries-4/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java rename to libraries-4/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java diff --git a/libraries/src/main/java/com/baeldung/mbassador/AckMessage.java b/libraries-4/src/main/java/com/baeldung/mbassador/AckMessage.java similarity index 100% rename from libraries/src/main/java/com/baeldung/mbassador/AckMessage.java rename to libraries-4/src/main/java/com/baeldung/mbassador/AckMessage.java diff --git a/libraries/src/main/java/com/baeldung/mbassador/Message.java b/libraries-4/src/main/java/com/baeldung/mbassador/Message.java similarity index 100% rename from libraries/src/main/java/com/baeldung/mbassador/Message.java rename to libraries-4/src/main/java/com/baeldung/mbassador/Message.java diff --git a/libraries/src/main/java/com/baeldung/mbassador/RejectMessage.java b/libraries-4/src/main/java/com/baeldung/mbassador/RejectMessage.java similarity index 100% rename from libraries/src/main/java/com/baeldung/mbassador/RejectMessage.java rename to libraries-4/src/main/java/com/baeldung/mbassador/RejectMessage.java diff --git a/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java b/libraries-4/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java rename to libraries-4/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java diff --git a/libraries/src/main/java/com/baeldung/pairs/CustomPair.java b/libraries-4/src/main/java/com/baeldung/pairs/CustomPair.java similarity index 100% rename from libraries/src/main/java/com/baeldung/pairs/CustomPair.java rename to libraries-4/src/main/java/com/baeldung/pairs/CustomPair.java diff --git a/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java b/libraries-4/src/main/java/com/baeldung/rome/RSSRomeExample.java similarity index 100% rename from libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java rename to libraries-4/src/main/java/com/baeldung/rome/RSSRomeExample.java diff --git a/libraries/src/main/java/com/baeldung/yarg/DocumentController.java b/libraries-4/src/main/java/com/baeldung/yarg/DocumentController.java similarity index 100% rename from libraries/src/main/java/com/baeldung/yarg/DocumentController.java rename to libraries-4/src/main/java/com/baeldung/yarg/DocumentController.java diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java b/libraries-4/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java rename to libraries-4/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java b/libraries-4/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java rename to libraries-4/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java b/libraries-4/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java rename to libraries-4/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java b/libraries-4/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java rename to libraries-4/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java b/libraries-4/src/test/java/com/baeldung/distinct/PersonDataGenerator.java similarity index 100% rename from libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java rename to libraries-4/src/test/java/com/baeldung/distinct/PersonDataGenerator.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/DetectPatternUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/DetectPatternUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java similarity index 90% rename from libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java index 38d95047ed..a1bd280658 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java +++ b/libraries-4/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java @@ -5,6 +5,7 @@ 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.Assert; import org.junit.Test; public class ForEachPatternUnitTest { @@ -23,7 +24,7 @@ public class ForEachPatternUnitTest { } for (int i = 0; i < map.size(); i++) { - assertEquals("New Value", map.get(i + 1)); + Assert.assertEquals("New Value", map.get(i + 1)); } } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/LazyIterationUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/LazyIterationUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/PartitionPatternUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/PartitionPatternUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/RejectPatternUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/RejectPatternUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/SelectPatternUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/SelectPatternUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexUnitTest.java b/libraries-4/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexUnitTest.java rename to libraries-4/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java b/libraries-4/src/test/java/com/baeldung/io/JavaDirectoryDeleteUnitTest.java similarity index 96% rename from libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java rename to libraries-4/src/test/java/com/baeldung/io/JavaDirectoryDeleteUnitTest.java index 53d9d11bbb..c9c8242cd5 100644 --- a/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java +++ b/libraries-4/src/test/java/com/baeldung/io/JavaDirectoryDeleteUnitTest.java @@ -1,138 +1,138 @@ -package com.baeldung.java.io; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -import org.apache.commons.io.FileUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.springframework.util.FileSystemUtils; - -public class JavaDirectoryDeleteUnitTest { - private static Path TEMP_DIRECTORY; - private static final String DIRECTORY_NAME = "toBeDeleted"; - - private static final List ALL_LINES = Arrays.asList("This is line 1", "This is line 2", "This is line 3", "This is line 4", "This is line 5", "This is line 6"); - - @BeforeClass - public static void initializeTempDirectory() throws IOException { - TEMP_DIRECTORY = Files.createTempDirectory("tmpForJUnit"); - } - - @AfterClass - public static void cleanTempDirectory() throws IOException { - FileUtils.deleteDirectory(TEMP_DIRECTORY.toFile()); - } - - @Before - public void setupDirectory() throws IOException { - Path tempPathForEachTest = Files.createDirectory(TEMP_DIRECTORY.resolve(DIRECTORY_NAME)); - - // Create a directory structure - Files.write(tempPathForEachTest.resolve("file1.txt"), ALL_LINES.subList(0, 2)); - Files.write(tempPathForEachTest.resolve("file2.txt"), ALL_LINES.subList(2, 4)); - - Files.createDirectories(tempPathForEachTest.resolve("Empty")); - - Path aSubDir = Files.createDirectories(tempPathForEachTest.resolve("notEmpty")); - Files.write(aSubDir.resolve("file3.txt"), ALL_LINES.subList(3, 5)); - Files.write(aSubDir.resolve("file4.txt"), ALL_LINES.subList(0, 3)); - - aSubDir = Files.createDirectories(aSubDir.resolve("anotherSubDirectory")); - Files.write(aSubDir.resolve("file5.txt"), ALL_LINES.subList(4, 5)); - Files.write(aSubDir.resolve("file6.txt"), ALL_LINES.subList(0, 2)); - } - - @After - public void checkAndCleanupIfRequired() throws IOException { - Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); - if (Files.exists(pathToBeDeleted)) { - FileUtils.deleteDirectory(pathToBeDeleted.toFile()); - } - } - - private boolean deleteDirectory(File directoryToBeDeleted) { - File[] allContents = directoryToBeDeleted.listFiles(); - - if (allContents != null) { - for (File file : allContents) { - deleteDirectory(file); - } - } - - return directoryToBeDeleted.delete(); - } - - @Test - public void givenDirectory_whenDeletedWithRecursion_thenIsGone() throws IOException { - Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); - - boolean result = deleteDirectory(pathToBeDeleted.toFile()); - - assertTrue("Could not delete directory", result); - assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); - } - - @Test - public void givenDirectory_whenDeletedWithCommonsIOFileUtils_thenIsGone() throws IOException { - Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); - - FileUtils.deleteDirectory(pathToBeDeleted.toFile()); - - assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); - } - - @Test - public void givenDirectory_whenDeletedWithSpringFileSystemUtils_thenIsGone() throws IOException { - Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); - - boolean result = FileSystemUtils.deleteRecursively(pathToBeDeleted.toFile()); - - assertTrue("Could not delete directory", result); - assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); - } - - @Test - public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException { - Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); - - Files.walk(pathToBeDeleted).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); - - assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); - } - - @Test - public void givenDirectory_whenDeletedWithNIO2WalkFileTree_thenIsGone() throws IOException { - Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); - - Files.walkFileTree(pathToBeDeleted, new SimpleFileVisitor() { - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - Files.delete(dir); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return FileVisitResult.CONTINUE; - } - }); - - assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); - } -} +package com.baeldung.io; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.util.FileSystemUtils; + +public class JavaDirectoryDeleteUnitTest { + private static Path TEMP_DIRECTORY; + private static final String DIRECTORY_NAME = "toBeDeleted"; + + private static final List ALL_LINES = Arrays.asList("This is line 1", "This is line 2", "This is line 3", "This is line 4", "This is line 5", "This is line 6"); + + @BeforeClass + public static void initializeTempDirectory() throws IOException { + TEMP_DIRECTORY = Files.createTempDirectory("tmpForJUnit"); + } + + @AfterClass + public static void cleanTempDirectory() throws IOException { + FileUtils.deleteDirectory(TEMP_DIRECTORY.toFile()); + } + + @Before + public void setupDirectory() throws IOException { + Path tempPathForEachTest = Files.createDirectory(TEMP_DIRECTORY.resolve(DIRECTORY_NAME)); + + // Create a directory structure + Files.write(tempPathForEachTest.resolve("file1.txt"), ALL_LINES.subList(0, 2)); + Files.write(tempPathForEachTest.resolve("file2.txt"), ALL_LINES.subList(2, 4)); + + Files.createDirectories(tempPathForEachTest.resolve("Empty")); + + Path aSubDir = Files.createDirectories(tempPathForEachTest.resolve("notEmpty")); + Files.write(aSubDir.resolve("file3.txt"), ALL_LINES.subList(3, 5)); + Files.write(aSubDir.resolve("file4.txt"), ALL_LINES.subList(0, 3)); + + aSubDir = Files.createDirectories(aSubDir.resolve("anotherSubDirectory")); + Files.write(aSubDir.resolve("file5.txt"), ALL_LINES.subList(4, 5)); + Files.write(aSubDir.resolve("file6.txt"), ALL_LINES.subList(0, 2)); + } + + @After + public void checkAndCleanupIfRequired() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + if (Files.exists(pathToBeDeleted)) { + FileUtils.deleteDirectory(pathToBeDeleted.toFile()); + } + } + + private boolean deleteDirectory(File directoryToBeDeleted) { + File[] allContents = directoryToBeDeleted.listFiles(); + + if (allContents != null) { + for (File file : allContents) { + deleteDirectory(file); + } + } + + return directoryToBeDeleted.delete(); + } + + @Test + public void givenDirectory_whenDeletedWithRecursion_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + boolean result = deleteDirectory(pathToBeDeleted.toFile()); + + assertTrue("Could not delete directory", result); + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithCommonsIOFileUtils_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + FileUtils.deleteDirectory(pathToBeDeleted.toFile()); + + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithSpringFileSystemUtils_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + boolean result = FileSystemUtils.deleteRecursively(pathToBeDeleted.toFile()); + + assertTrue("Could not delete directory", result); + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + Files.walk(pathToBeDeleted).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithNIO2WalkFileTree_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + Files.walkFileTree(pathToBeDeleted, new SimpleFileVisitor() { + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + Files.delete(dir); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + }); + + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } +} diff --git a/libraries/src/test/java/com/baeldung/jdeffered/JDeferredUnitTest.java b/libraries-4/src/test/java/com/baeldung/jdeffered/JDeferredUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/jdeffered/JDeferredUnitTest.java rename to libraries-4/src/test/java/com/baeldung/jdeffered/JDeferredUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchUnitTest.java b/libraries-4/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchUnitTest.java rename to libraries-4/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationUnitTest.java b/libraries-4/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationUnitTest.java rename to libraries-4/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorBasicUnitTest.java b/libraries-4/src/test/java/com/baeldung/mbassador/MBassadorBasicUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/mbassador/MBassadorBasicUnitTest.java rename to libraries-4/src/test/java/com/baeldung/mbassador/MBassadorBasicUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationUnitTest.java b/libraries-4/src/test/java/com/baeldung/mbassador/MBassadorConfigurationUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationUnitTest.java rename to libraries-4/src/test/java/com/baeldung/mbassador/MBassadorConfigurationUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorFilterUnitTest.java b/libraries-4/src/test/java/com/baeldung/mbassador/MBassadorFilterUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/mbassador/MBassadorFilterUnitTest.java rename to libraries-4/src/test/java/com/baeldung/mbassador/MBassadorFilterUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorHierarchyUnitTest.java b/libraries-4/src/test/java/com/baeldung/mbassador/MBassadorHierarchyUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/mbassador/MBassadorHierarchyUnitTest.java rename to libraries-4/src/test/java/com/baeldung/mbassador/MBassadorHierarchyUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java b/libraries-4/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java rename to libraries-4/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java b/libraries-4/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java rename to libraries-4/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/pairs/CoreJavaPairUnitTest.java b/libraries-4/src/test/java/com/baeldung/pairs/CoreJavaPairUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/pairs/CoreJavaPairUnitTest.java rename to libraries-4/src/test/java/com/baeldung/pairs/CoreJavaPairUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java b/libraries-4/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java rename to libraries-4/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/pairs/VavrPairsUnitTest.java b/libraries-4/src/test/java/com/baeldung/pairs/VavrPairsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/pairs/VavrPairsUnitTest.java rename to libraries-4/src/test/java/com/baeldung/pairs/VavrPairsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java b/libraries-4/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java rename to libraries-4/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java diff --git a/libraries-5/README.md b/libraries-5/README.md new file mode 100644 index 0000000000..f1e749b293 --- /dev/null +++ b/libraries-5/README.md @@ -0,0 +1,21 @@ +## Libraries-5 + +This module contains articles about various Java libraries. +These are small libraries that are relatively easy to use and do not require any separate module of their own. + +The code examples related to different libraries are each in their own module. + +Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases. + +### Relevant articles +- [Introduction to Caffeine](https://www.baeldung.com/java-caching-caffeine) +- [Introduction to StreamEx](https://www.baeldung.com/streamex) +- [A Docker Guide for Java](https://www.baeldung.com/docker-java-api) +- [Introduction to Akka Actors in Java](https://www.baeldung.com/akka-actors-java) +- [A Guide to Byte Buddy](https://www.baeldung.com/byte-buddy) +- [Introduction to jOOL](https://www.baeldung.com/jool) +- [Consumer Driven Contracts with Pact](https://www.baeldung.com/pact-junit-consumer-driven-contracts) +- [Introduction to Atlassian Fugue](https://www.baeldung.com/java-fugue) +- [Publish and Receive Messages with Nats Java Client](https://www.baeldung.com/nats-java-client) +- [Java Concurrency Utility with JCTools](https://www.baeldung.com/java-concurrency-jc-tools) +- More articles [[<-- prev]](/libraries-4) [[next -->]](/libraries-6) diff --git a/libraries-5/pom.xml b/libraries-5/pom.xml new file mode 100644 index 0000000000..63296d4a89 --- /dev/null +++ b/libraries-5/pom.xml @@ -0,0 +1,146 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + libraries-5 + 4.0.0 + + + + org.springframework + spring-web + ${spring.version} + + + org.assertj + assertj-core + ${assertj.version} + + + org.jooq + jool + ${jool.version} + + + au.com.dius + pact-jvm-consumer-junit_2.11 + ${pact.version} + test + + + org.codehaus.groovy + groovy-all + + + + + + + com.typesafe.akka + akka-actor_${scala.version} + ${typesafe-akka.version} + + + com.typesafe.akka + akka-testkit_${scala.version} + ${typesafe-akka.version} + test + + + + one.util + streamex + ${streamex.version} + + + net.bytebuddy + byte-buddy + ${bytebuddy.version} + + + net.bytebuddy + byte-buddy-agent + ${bytebuddy.version} + + + + + com.github.docker-java + docker-java + ${docker.version} + + + org.slf4j + slf4j-log4j12 + + + org.slf4j + jcl-over-slf4j + + + ch.qos.logback + logback-classic + + + + + + + com.github.ben-manes.caffeine + caffeine + ${caffeine.version} + + + com.google.code.findbugs + jsr305 + ${findbugs.version} + test + + + + io.atlassian.fugue + fugue + ${fugue.version} + + + io.nats + jnats + ${jnats.version} + + + org.jctools + jctools-core + ${jctools.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + + + 3.5.0 + 0.9.12 + 4.3.8.RELEASE + 3.6.2 + 2.11 + 2.5.11 + 0.6.5 + 1.7.1 + 3.0.14 + 2.5.5 + 3.0.2 + 4.5.1 + 1.0 + 2.1.2 + 1.19 + + + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/akka/FirstActor.java b/libraries-5/src/main/java/com/baeldung/akka/FirstActor.java similarity index 100% rename from libraries/src/main/java/com/baeldung/akka/FirstActor.java rename to libraries-5/src/main/java/com/baeldung/akka/FirstActor.java diff --git a/libraries/src/main/java/com/baeldung/akka/MyActor.java b/libraries-5/src/main/java/com/baeldung/akka/MyActor.java similarity index 100% rename from libraries/src/main/java/com/baeldung/akka/MyActor.java rename to libraries-5/src/main/java/com/baeldung/akka/MyActor.java diff --git a/libraries/src/main/java/com/baeldung/akka/PrinterActor.java b/libraries-5/src/main/java/com/baeldung/akka/PrinterActor.java similarity index 100% rename from libraries/src/main/java/com/baeldung/akka/PrinterActor.java rename to libraries-5/src/main/java/com/baeldung/akka/PrinterActor.java diff --git a/libraries/src/main/java/com/baeldung/akka/ReadingActor.java b/libraries-5/src/main/java/com/baeldung/akka/ReadingActor.java similarity index 100% rename from libraries/src/main/java/com/baeldung/akka/ReadingActor.java rename to libraries-5/src/main/java/com/baeldung/akka/ReadingActor.java diff --git a/libraries/src/main/java/com/baeldung/akka/WordCounterActor.java b/libraries-5/src/main/java/com/baeldung/akka/WordCounterActor.java similarity index 100% rename from libraries/src/main/java/com/baeldung/akka/WordCounterActor.java rename to libraries-5/src/main/java/com/baeldung/akka/WordCounterActor.java diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java b/libraries-5/src/main/java/com/baeldung/bytebuddy/Bar.java similarity index 100% rename from libraries/src/main/java/com/baeldung/bytebuddy/Bar.java rename to libraries-5/src/main/java/com/baeldung/bytebuddy/Bar.java diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java b/libraries-5/src/main/java/com/baeldung/bytebuddy/Foo.java similarity index 100% rename from libraries/src/main/java/com/baeldung/bytebuddy/Foo.java rename to libraries-5/src/main/java/com/baeldung/bytebuddy/Foo.java diff --git a/libraries/src/main/java/com/baeldung/caffeine/DataObject.java b/libraries-5/src/main/java/com/baeldung/caffeine/DataObject.java similarity index 100% rename from libraries/src/main/java/com/baeldung/caffeine/DataObject.java rename to libraries-5/src/main/java/com/baeldung/caffeine/DataObject.java diff --git a/libraries/src/main/java/com/baeldung/jctools/MpmcBenchmark.java b/libraries-5/src/main/java/com/baeldung/jctools/MpmcBenchmark.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jctools/MpmcBenchmark.java rename to libraries-5/src/main/java/com/baeldung/jctools/MpmcBenchmark.java diff --git a/libraries/src/main/java/com/baeldung/jctools/README.md b/libraries-5/src/main/java/com/baeldung/jctools/README.md similarity index 100% rename from libraries/src/main/java/com/baeldung/jctools/README.md rename to libraries-5/src/main/java/com/baeldung/jctools/README.md diff --git a/libraries/src/main/java/com/baeldung/jnats/NatsClient.java b/libraries-5/src/main/java/com/baeldung/jnats/NatsClient.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jnats/NatsClient.java rename to libraries-5/src/main/java/com/baeldung/jnats/NatsClient.java diff --git a/libraries/src/main/java/com/baeldung/streamex/Role.java b/libraries-5/src/main/java/com/baeldung/streamex/Role.java similarity index 100% rename from libraries/src/main/java/com/baeldung/streamex/Role.java rename to libraries-5/src/main/java/com/baeldung/streamex/Role.java diff --git a/libraries/src/main/java/com/baeldung/streamex/StreamEX.java b/libraries-5/src/main/java/com/baeldung/streamex/StreamEX.java similarity index 100% rename from libraries/src/main/java/com/baeldung/streamex/StreamEX.java rename to libraries-5/src/main/java/com/baeldung/streamex/StreamEX.java diff --git a/libraries/src/main/java/com/baeldung/streamex/User.java b/libraries-5/src/main/java/com/baeldung/streamex/User.java similarity index 100% rename from libraries/src/main/java/com/baeldung/streamex/User.java rename to libraries-5/src/main/java/com/baeldung/streamex/User.java diff --git a/libraries/src/test/java/com/baeldung/akka/AkkaActorsUnitTest.java b/libraries-5/src/test/java/com/baeldung/akka/AkkaActorsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/akka/AkkaActorsUnitTest.java rename to libraries-5/src/test/java/com/baeldung/akka/AkkaActorsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java b/libraries-5/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java rename to libraries-5/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java b/libraries-5/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java similarity index 88% rename from libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java rename to libraries-5/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java index d523d0ff8b..65c441c50d 100644 --- a/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java +++ b/libraries-5/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java @@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; +import org.junit.Assert; import org.junit.Test; import com.github.benmanes.caffeine.cache.*; @@ -65,43 +66,43 @@ public class CaffeineUnitTest { assertEquals("Data for " + key, dataObject.getData()); }); - cache.getAll(Arrays.asList("A", "B", "C")).thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size())); + cache.getAll(Arrays.asList("A", "B", "C")).thenAccept(dataObjectMap -> Assert.assertEquals(3, dataObjectMap.size())); } @Test public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() { LoadingCache cache = Caffeine.newBuilder().maximumSize(1).refreshAfterWrite(10, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k)); - assertEquals(0, cache.estimatedSize()); + Assert.assertEquals(0, cache.estimatedSize()); cache.get("A"); - assertEquals(1, cache.estimatedSize()); + Assert.assertEquals(1, cache.estimatedSize()); cache.get("B"); cache.cleanUp(); - assertEquals(1, cache.estimatedSize()); + Assert.assertEquals(1, cache.estimatedSize()); } @Test public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() { LoadingCache cache = Caffeine.newBuilder().maximumWeight(10).weigher((k, v) -> 5).build(k -> DataObject.get("Data for " + k)); - assertEquals(0, cache.estimatedSize()); + Assert.assertEquals(0, cache.estimatedSize()); cache.get("A"); - assertEquals(1, cache.estimatedSize()); + Assert.assertEquals(1, cache.estimatedSize()); cache.get("B"); - assertEquals(2, cache.estimatedSize()); + Assert.assertEquals(2, cache.estimatedSize()); cache.get("C"); cache.cleanUp(); - assertEquals(2, cache.estimatedSize()); + Assert.assertEquals(2, cache.estimatedSize()); } @Test @@ -138,7 +139,7 @@ public class CaffeineUnitTest { cache.get("A"); cache.get("A"); - assertEquals(1, cache.stats().hitCount()); - assertEquals(1, cache.stats().missCount()); + Assert.assertEquals(1, cache.stats().hitCount()); + Assert.assertEquals(1, cache.stats().missCount()); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java b/libraries-5/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java similarity index 94% rename from libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java rename to libraries-5/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java index e6f0fd1c31..007c70355a 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java +++ b/libraries-5/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java @@ -6,6 +6,8 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.PortBinding; import com.github.dockerjava.core.DockerClientBuilder; +import org.hamcrest.MatcherAssert; +import org.hamcrest.core.Is; import org.junit.BeforeClass; import org.junit.Test; @@ -51,7 +53,7 @@ public class ContainerLiveTest { CreateContainerResponse container = dockerClient.createContainerCmd("mongo:3.6").withCmd("--bind_ip_all").withName("mongo").withHostName("baeldung").withEnv("MONGO_LATEST_VERSION=3.6").withPortBindings(PortBinding.parse("9999:27017")).exec(); // then - assertThat(container.getId(), is(not(null))); + MatcherAssert.assertThat(container.getId(), is(not(null))); } @Test @@ -104,7 +106,7 @@ public class ContainerLiveTest { // then InspectContainerResponse containerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); - assertThat(containerResponse.getId(), is(container.getId())); + MatcherAssert.assertThat(containerResponse.getId(), Is.is(container.getId())); } @Test diff --git a/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java b/libraries-5/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java rename to libraries-5/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java diff --git a/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java b/libraries-5/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java similarity index 96% rename from libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java rename to libraries-5/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java index 7e8cd6a354..96e7922f2a 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java +++ b/libraries-5/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java @@ -8,6 +8,8 @@ import com.github.dockerjava.core.DockerClientBuilder; import com.github.dockerjava.core.command.BuildImageResultCallback; import com.github.dockerjava.core.command.PullImageResultCallback; import com.github.dockerjava.core.command.PushImageResultCallback; +import org.hamcrest.MatcherAssert; +import org.hamcrest.core.Is; import org.junit.BeforeClass; import org.junit.Test; @@ -81,7 +83,7 @@ public class ImageLiveTest { InspectImageResponse imageResponse = dockerClient.inspectImageCmd(image.getId()).exec(); // then - assertThat(imageResponse.getId(), is(image.getId())); + MatcherAssert.assertThat(imageResponse.getId(), Is.is(image.getId())); } @Test diff --git a/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java b/libraries-5/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java similarity index 95% rename from libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java rename to libraries-5/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java index d3abbe2e7e..31ad32c7b5 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java +++ b/libraries-5/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java @@ -5,6 +5,7 @@ import com.github.dockerjava.api.command.CreateNetworkResponse; import com.github.dockerjava.api.model.Network; import com.github.dockerjava.api.model.Network.Ipam; import com.github.dockerjava.core.DockerClientBuilder; +import org.hamcrest.MatcherAssert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; @@ -64,7 +65,7 @@ public class NetworkLiveTest { Network network = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec(); // then - assertThat(network.getName(), is(networkName)); + MatcherAssert.assertThat(network.getName(), is(networkName)); } @Test diff --git a/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java b/libraries-5/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java similarity index 92% rename from libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java rename to libraries-5/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java index 9e60a76b33..f2a078b2c6 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java +++ b/libraries-5/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java @@ -5,6 +5,7 @@ import com.github.dockerjava.api.command.CreateVolumeResponse; import com.github.dockerjava.api.command.InspectVolumeResponse; import com.github.dockerjava.api.command.ListVolumesResponse; import com.github.dockerjava.core.DockerClientBuilder; +import org.hamcrest.MatcherAssert; import org.junit.BeforeClass; import org.junit.Test; @@ -57,7 +58,7 @@ public class VolumeLiveTest { CreateVolumeResponse unnamedVolume = dockerClient.createVolumeCmd().exec(); // then - assertThat(unnamedVolume.getName(), is(not(null))); + MatcherAssert.assertThat(unnamedVolume.getName(), is(not(null))); } @Test @@ -67,7 +68,7 @@ public class VolumeLiveTest { CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("myNamedVolume").exec(); // then - assertThat(namedVolume.getName(), is(not(null))); + MatcherAssert.assertThat(namedVolume.getName(), is(not(null))); } @Test diff --git a/libraries/src/test/java/com/baeldung/atlassian/fugue/FugueUnitTest.java b/libraries-5/src/test/java/com/baeldung/fugue/FugueUnitTest.java similarity index 99% rename from libraries/src/test/java/com/baeldung/atlassian/fugue/FugueUnitTest.java rename to libraries-5/src/test/java/com/baeldung/fugue/FugueUnitTest.java index 773e39b76a..c3a89a1355 100644 --- a/libraries/src/test/java/com/baeldung/atlassian/fugue/FugueUnitTest.java +++ b/libraries-5/src/test/java/com/baeldung/fugue/FugueUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.atlassian.fugue; +package com.baeldung.fugue; import io.atlassian.fugue.*; import org.junit.Assert; diff --git a/libraries/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java b/libraries-5/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java similarity index 88% rename from libraries/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java rename to libraries-5/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java index 4a9d0fadb2..a5dacdbdac 100644 --- a/libraries/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java +++ b/libraries-5/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.jctools; +import org.assertj.core.api.Assertions; import org.jctools.queues.SpscArrayQueue; import org.jctools.queues.SpscChunkedArrayQueue; import org.junit.Test; @@ -44,16 +45,16 @@ public class JCToolsUnitTest { @Test public void whenQueueIsFull_thenNoMoreElementsCanBeAdded() throws InterruptedException { SpscChunkedArrayQueue queue = new SpscChunkedArrayQueue<>(8, 16); - assertThat(queue.capacity()).isEqualTo(16); + Assertions.assertThat(queue.capacity()).isEqualTo(16); CountDownLatch startConsuming = new CountDownLatch(1); CountDownLatch awakeProducer = new CountDownLatch(1); AtomicReference error = new AtomicReference<>(); Thread producer = new Thread(() -> { IntStream.range(0, queue.capacity()).forEach(i -> { - assertThat(queue.offer(i)).isTrue(); + Assertions.assertThat(queue.offer(i)).isTrue(); }); - assertThat(queue.offer(queue.capacity())).isFalse(); + Assertions.assertThat(queue.offer(queue.capacity())).isFalse(); startConsuming.countDown(); try { awakeProducer.await(); @@ -61,7 +62,7 @@ public class JCToolsUnitTest { throw new RuntimeException(e); } - assertThat(queue.offer(queue.capacity())).isTrue(); + Assertions.assertThat(queue.offer(queue.capacity())).isTrue(); }); producer.setUncaughtExceptionHandler((t, e) -> { error.set(e); diff --git a/libraries/src/test/java/com/baeldung/jnats/NatsClientLiveTest.java b/libraries-5/src/test/java/com/baeldung/jnats/NatsClientLiveTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/jnats/NatsClientLiveTest.java rename to libraries-5/src/test/java/com/baeldung/jnats/NatsClientLiveTest.java diff --git a/libraries/src/test/java/com/baeldung/jool/JOOLUnitTest.java b/libraries-5/src/test/java/com/baeldung/jool/JOOLUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/jool/JOOLUnitTest.java rename to libraries-5/src/test/java/com/baeldung/jool/JOOLUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java b/libraries-5/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java rename to libraries-5/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsUnitTest.java b/libraries-5/src/test/java/com/baeldung/streamex/StreamExMergeStreamsUnitTest.java similarity index 98% rename from libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsUnitTest.java rename to libraries-5/src/test/java/com/baeldung/streamex/StreamExMergeStreamsUnitTest.java index 220348bf36..b267eaea9b 100644 --- a/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsUnitTest.java +++ b/libraries-5/src/test/java/com/baeldung/streamex/StreamExMergeStreamsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.stream; +package com.baeldung.streamex; import one.util.streamex.StreamEx; import org.junit.Test; diff --git a/libraries/src/test/resources/dockerapi/Dockerfile b/libraries-5/src/test/resources/dockerapi/Dockerfile similarity index 100% rename from libraries/src/test/resources/dockerapi/Dockerfile rename to libraries-5/src/test/resources/dockerapi/Dockerfile diff --git a/libraries-6/README.md b/libraries-6/README.md new file mode 100644 index 0000000000..79bb83113e --- /dev/null +++ b/libraries-6/README.md @@ -0,0 +1,17 @@ +## Libraries-6 + +This module contains articles about various Java libraries. +These are small libraries that are relatively easy to use and do not require any separate module of their own. + +The code examples related to different libraries are each in their own module. + +Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases. + +### Relevant articles +- [Introduction to JavaPoet](https://www.baeldung.com/java-poet) +- [Guide to Resilience4j](https://www.baeldung.com/resilience4j) +- [Implementing a FTP-Client in Java](https://www.baeldung.com/java-ftp-client) +- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library) +- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library) +- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once) +- More articles [[<-- prev]](/libraries-5) diff --git a/libraries-6/pom.xml b/libraries-6/pom.xml new file mode 100644 index 0000000000..030e5aa77b --- /dev/null +++ b/libraries-6/pom.xml @@ -0,0 +1,111 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + libraries-6 + + + + org.functionaljava + functionaljava-java8 + ${functionaljava.version} + + + com.codepoetics + protonpack + ${protonpack.version} + + + org.apache.kafka + kafka-streams + ${kafka.version} + + + org.apache.kafka + kafka-clients + ${kafka.version} + test + test + + + io.github.resilience4j + resilience4j-circuitbreaker + ${resilience4j.version} + + + io.github.resilience4j + resilience4j-bulkhead + ${resilience4j.version} + + + io.github.resilience4j + resilience4j-retry + ${resilience4j.version} + + + io.github.resilience4j + resilience4j-timelimiter + ${resilience4j.version} + + + com.squareup + javapoet + ${javapoet.version} + + + org.mockftpserver + MockFtpServer + ${mockftpserver.version} + test + + + + org.reflections + reflections + ${reflections.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + commons-net + commons-net + ${commons-net.version} + + + org.assertj + assertj-core + ${assertj.version} + + + commons-io + commons-io + ${commonsio.version} + test + + + + + 2.0.0 + 1.10.0 + 0.9.11 + 2.7.1 + 4.8.1 + 0.12.1 + 1.15 + 3.6 + 3.6.2 + 2.6 + + + + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java b/libraries-6/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java similarity index 96% rename from libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java rename to libraries-6/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java index eaa201d1ba..e97f128b30 100644 --- a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java +++ b/libraries-6/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java @@ -1,43 +1,43 @@ -package com.baeldung.fj; - -import fj.F; -import fj.F1Functions; -import fj.Unit; -import fj.data.IO; -import fj.data.IOFunctions; - -public class FunctionalJavaIOMain { - - public static IO printLetters(final String s) { - return () -> { - for (int i = 0; i < s.length(); i++) { - System.out.println(s.charAt(i)); - } - return Unit.unit(); - }; - } - - public static void main(String[] args) { - - F> printLetters = i -> printLetters(i); - - IO lowerCase = IOFunctions.stdoutPrintln("What's your first Name ?"); - - IO input = IOFunctions.stdoutPrint("First Name: "); - - IO userInput = IOFunctions.append(lowerCase, input); - - IO readInput = IOFunctions.stdinReadLine(); - - F toUpperCase = i -> i.toUpperCase(); - - F> transformInput = F1Functions., String> o(printLetters).f(toUpperCase); - - IO readAndPrintResult = IOFunctions.bind(readInput, transformInput); - - IO program = IOFunctions.bind(userInput, nothing -> readAndPrintResult); - - IOFunctions.toSafe(program).run(); - - } -} +package com.baeldung.fj; + +import fj.F; +import fj.F1Functions; +import fj.Unit; +import fj.data.IO; +import fj.data.IOFunctions; + +public class FunctionalJavaIOMain { + + public static IO printLetters(final String s) { + return () -> { + for (int i = 0; i < s.length(); i++) { + System.out.println(s.charAt(i)); + } + return Unit.unit(); + }; + } + + public static void main(String[] args) { + + F> printLetters = i -> printLetters(i); + + IO lowerCase = IOFunctions.stdoutPrintln("What's your first Name ?"); + + IO input = IOFunctions.stdoutPrint("First Name: "); + + IO userInput = IOFunctions.append(lowerCase, input); + + IO readInput = IOFunctions.stdinReadLine(); + + F toUpperCase = i -> i.toUpperCase(); + + F> transformInput = F1Functions., String> o(printLetters).f(toUpperCase); + + IO readAndPrintResult = IOFunctions.bind(readInput, transformInput); + + IO program = IOFunctions.bind(userInput, nothing -> readAndPrintResult); + + IOFunctions.toSafe(program).run(); + + } +} diff --git a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java b/libraries-6/src/main/java/com/baeldung/fj/FunctionalJavaMain.java similarity index 96% rename from libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java rename to libraries-6/src/main/java/com/baeldung/fj/FunctionalJavaMain.java index c6412f2923..1a59e6c22a 100644 --- a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java +++ b/libraries-6/src/main/java/com/baeldung/fj/FunctionalJavaMain.java @@ -1,48 +1,48 @@ -package com.baeldung.fj; - -import fj.F; -import fj.Show; -import fj.data.Array; -import fj.data.List; -import fj.data.Option; -import fj.function.Characters; -import fj.function.Integers; - -public class FunctionalJavaMain { - - public static final F isEven = i -> i % 2 == 0; - - public static void main(String[] args) { - - List fList = List.list(3, 4, 5, 6); - List evenList = fList.map(isEven); - Show.listShow(Show.booleanShow).println(evenList); - - fList = fList.map(i -> i + 1); - Show.listShow(Show.intShow).println(fList); - - Array a = Array.array(17, 44, 67, 2, 22, 80, 1, 27); - Array b = a.filter(Integers.even); - Show.arrayShow(Show.intShow).println(b); - - Array array = Array.array("Welcome", "To", "baeldung"); - Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); - System.out.println(isExist); - - Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); - int sum = intArray.foldLeft(Integers.add, 0); - System.out.println(sum); - - Option n1 = Option.some(1); - Option n2 = Option.some(2); - - F> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none(); - - Option result1 = n1.bind(f1); - Option result2 = n2.bind(f1); - - Show.optionShow(Show.intShow).println(result1); - Show.optionShow(Show.intShow).println(result2); - } - -} +package com.baeldung.fj; + +import fj.F; +import fj.Show; +import fj.data.Array; +import fj.data.List; +import fj.data.Option; +import fj.function.Characters; +import fj.function.Integers; + +public class FunctionalJavaMain { + + public static final F isEven = i -> i % 2 == 0; + + public static void main(String[] args) { + + List fList = List.list(3, 4, 5, 6); + List evenList = fList.map(isEven); + Show.listShow(Show.booleanShow).println(evenList); + + fList = fList.map(i -> i + 1); + Show.listShow(Show.intShow).println(fList); + + Array a = Array.array(17, 44, 67, 2, 22, 80, 1, 27); + Array b = a.filter(Integers.even); + Show.arrayShow(Show.intShow).println(b); + + Array array = Array.array("Welcome", "To", "baeldung"); + Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); + System.out.println(isExist); + + Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); + int sum = intArray.foldLeft(Integers.add, 0); + System.out.println(sum); + + Option n1 = Option.some(1); + Option n2 = Option.some(2); + + F> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none(); + + Option result1 = n1.bind(f1); + Option result2 = n2.bind(f1); + + Show.optionShow(Show.intShow).println(result1); + Show.optionShow(Show.intShow).println(result2); + } + +} diff --git a/libraries/src/main/java/com/baeldung/ftp/FtpClient.java b/libraries-6/src/main/java/com/baeldung/ftp/FtpClient.java similarity index 100% rename from libraries/src/main/java/com/baeldung/ftp/FtpClient.java rename to libraries-6/src/main/java/com/baeldung/ftp/FtpClient.java diff --git a/libraries/src/main/java/com/baeldung/javapoet/PersonGenerator.java b/libraries-6/src/main/java/com/baeldung/javapoet/PersonGenerator.java similarity index 100% rename from libraries/src/main/java/com/baeldung/javapoet/PersonGenerator.java rename to libraries-6/src/main/java/com/baeldung/javapoet/PersonGenerator.java diff --git a/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java b/libraries-6/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java rename to libraries-6/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java diff --git a/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java b/libraries-6/src/main/java/com/baeldung/kafka/TransactionalWordCount.java similarity index 100% rename from libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java rename to libraries-6/src/main/java/com/baeldung/kafka/TransactionalWordCount.java diff --git a/libraries/src/main/java/com/baeldung/kafka/Tuple.java b/libraries-6/src/main/java/com/baeldung/kafka/Tuple.java similarity index 100% rename from libraries/src/main/java/com/baeldung/kafka/Tuple.java rename to libraries-6/src/main/java/com/baeldung/kafka/Tuple.java diff --git a/libraries/src/main/java/com/baeldung/reflections/ReflectionsApp.java b/libraries-6/src/main/java/com/baeldung/reflections/ReflectionsApp.java similarity index 97% rename from libraries/src/main/java/com/baeldung/reflections/ReflectionsApp.java rename to libraries-6/src/main/java/com/baeldung/reflections/ReflectionsApp.java index 30da8ea837..4f5b6dd183 100644 --- a/libraries/src/main/java/com/baeldung/reflections/ReflectionsApp.java +++ b/libraries-6/src/main/java/com/baeldung/reflections/ReflectionsApp.java @@ -1,71 +1,71 @@ -package com.baeldung.reflections; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.Date; -import java.util.Set; -import java.util.regex.Pattern; - -import org.reflections.Reflections; -import org.reflections.scanners.MethodAnnotationsScanner; -import org.reflections.scanners.MethodParameterScanner; -import org.reflections.scanners.ResourcesScanner; -import org.reflections.scanners.Scanner; -import org.reflections.scanners.SubTypesScanner; -import org.reflections.util.ClasspathHelper; -import org.reflections.util.ConfigurationBuilder; - -public class ReflectionsApp { - - public Set> getReflectionsSubTypes() { - Reflections reflections = new Reflections("org.reflections"); - Set> scannersSet = reflections.getSubTypesOf(Scanner.class); - return scannersSet; - } - - public Set> getJDKFunctinalInterfaces() { - Reflections reflections = new Reflections("java.util.function"); - Set> typesSet = reflections.getTypesAnnotatedWith(FunctionalInterface.class); - return typesSet; - } - - public Set getDateDeprecatedMethods() { - Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner()); - Set deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class); - return deprecatedMethodsSet; - } - - @SuppressWarnings("rawtypes") - public Set getDateDeprecatedConstructors() { - Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner()); - Set constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class); - return constructorsSet; - } - - public Set getMethodsWithDateParam() { - Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner()); - Set methodsSet = reflections.getMethodsMatchParams(Date.class); - return methodsSet; - } - - public Set getMethodsWithVoidReturn() { - Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner()); - Set methodsSet = reflections.getMethodsReturn(void.class); - return methodsSet; - } - - public Set getPomXmlPaths() { - Reflections reflections = new Reflections(new ResourcesScanner()); - Set resourcesSet = reflections.getResources(Pattern.compile(".*pom\\.xml")); - return resourcesSet; - } - - public Set> getReflectionsSubTypesUsingBuilder() { - Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections")) - .setScanners(new SubTypesScanner())); - - Set> scannersSet = reflections.getSubTypesOf(Scanner.class); - return scannersSet; - } - -} +package com.baeldung.reflections; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.Date; +import java.util.Set; +import java.util.regex.Pattern; + +import org.reflections.Reflections; +import org.reflections.scanners.MethodAnnotationsScanner; +import org.reflections.scanners.MethodParameterScanner; +import org.reflections.scanners.ResourcesScanner; +import org.reflections.scanners.Scanner; +import org.reflections.scanners.SubTypesScanner; +import org.reflections.util.ClasspathHelper; +import org.reflections.util.ConfigurationBuilder; + +public class ReflectionsApp { + + public Set> getReflectionsSubTypes() { + Reflections reflections = new Reflections("org.reflections"); + Set> scannersSet = reflections.getSubTypesOf(Scanner.class); + return scannersSet; + } + + public Set> getJDKFunctinalInterfaces() { + Reflections reflections = new Reflections("java.util.function"); + Set> typesSet = reflections.getTypesAnnotatedWith(FunctionalInterface.class); + return typesSet; + } + + public Set getDateDeprecatedMethods() { + Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner()); + Set deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class); + return deprecatedMethodsSet; + } + + @SuppressWarnings("rawtypes") + public Set getDateDeprecatedConstructors() { + Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner()); + Set constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class); + return constructorsSet; + } + + public Set getMethodsWithDateParam() { + Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner()); + Set methodsSet = reflections.getMethodsMatchParams(Date.class); + return methodsSet; + } + + public Set getMethodsWithVoidReturn() { + Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner()); + Set methodsSet = reflections.getMethodsReturn(void.class); + return methodsSet; + } + + public Set getPomXmlPaths() { + Reflections reflections = new Reflections(new ResourcesScanner()); + Set resourcesSet = reflections.getResources(Pattern.compile(".*pom\\.xml")); + return resourcesSet; + } + + public Set> getReflectionsSubTypesUsingBuilder() { + Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections")) + .setScanners(new SubTypesScanner())); + + Set> scannersSet = reflections.getSubTypesOf(Scanner.class); + return scannersSet; + } + +} diff --git a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java b/libraries-6/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java similarity index 95% rename from libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java rename to libraries-6/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java index 97ead07470..f79d334b23 100644 --- a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java +++ b/libraries-6/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import org.junit.Assert; import org.junit.Test; import fj.F; @@ -96,9 +97,9 @@ public class FunctionalJavaUnitTest { Option result2 = n2.bind(function); Option result3 = n3.bind(function); - assertEquals(Option.none(), result1); - assertEquals(Option.some(102), result2); - assertEquals(Option.none(), result3); + Assert.assertEquals(Option.none(), result1); + Assert.assertEquals(Option.some(102), result2); + Assert.assertEquals(Option.none(), result3); } @Test diff --git a/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java b/libraries-6/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java rename to libraries-6/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java diff --git a/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java b/libraries-6/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java rename to libraries-6/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/PersonGeneratorUnitTest.java b/libraries-6/src/test/java/com/baeldung/javapoet/test/PersonGeneratorUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/javapoet/test/PersonGeneratorUnitTest.java rename to libraries-6/src/test/java/com/baeldung/javapoet/test/PersonGeneratorUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/person/Gender.java b/libraries-6/src/test/java/com/baeldung/javapoet/test/person/Gender.java similarity index 100% rename from libraries/src/test/java/com/baeldung/javapoet/test/person/Gender.java rename to libraries-6/src/test/java/com/baeldung/javapoet/test/person/Gender.java diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/person/Person.java b/libraries-6/src/test/java/com/baeldung/javapoet/test/person/Person.java similarity index 100% rename from libraries/src/test/java/com/baeldung/javapoet/test/person/Person.java rename to libraries-6/src/test/java/com/baeldung/javapoet/test/person/Person.java diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/person/Student.java b/libraries-6/src/test/java/com/baeldung/javapoet/test/person/Student.java similarity index 100% rename from libraries/src/test/java/com/baeldung/javapoet/test/person/Student.java rename to libraries-6/src/test/java/com/baeldung/javapoet/test/person/Student.java diff --git a/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java b/libraries-6/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java rename to libraries-6/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java diff --git a/libraries/src/test/java/com/baeldung/reflections/ReflectionsUnitTest.java b/libraries-6/src/test/java/com/baeldung/reflections/ReflectionsUnitTest.java similarity index 96% rename from libraries/src/test/java/com/baeldung/reflections/ReflectionsUnitTest.java rename to libraries-6/src/test/java/com/baeldung/reflections/ReflectionsUnitTest.java index 9a3ef0747b..b86094b6f4 100644 --- a/libraries/src/test/java/com/baeldung/reflections/ReflectionsUnitTest.java +++ b/libraries-6/src/test/java/com/baeldung/reflections/ReflectionsUnitTest.java @@ -1,50 +1,50 @@ -package com.baeldung.reflections; - -import static org.junit.jupiter.api.Assertions.assertFalse; - -import org.junit.jupiter.api.Test; - -public class ReflectionsUnitTest { - - @Test - public void givenTypeThenGetAllSubTypes() { - ReflectionsApp reflectionsApp = new ReflectionsApp(); - assertFalse(reflectionsApp.getReflectionsSubTypes() - .isEmpty()); - } - - @Test - public void givenTypeAndUsingBuilderThenGetAllSubTypes() { - ReflectionsApp reflectionsApp = new ReflectionsApp(); - assertFalse(reflectionsApp.getReflectionsSubTypesUsingBuilder() - .isEmpty()); - } - - @Test - public void givenAnnotationThenGetAllAnnotatedMethods() { - ReflectionsApp reflectionsApp = new ReflectionsApp(); - assertFalse(reflectionsApp.getDateDeprecatedMethods() - .isEmpty()); - } - - @Test - public void givenAnnotationThenGetAllAnnotatedConstructors() { - ReflectionsApp reflectionsApp = new ReflectionsApp(); - assertFalse(reflectionsApp.getDateDeprecatedConstructors() - .isEmpty()); - } - - @Test - public void givenParamTypeThenGetAllMethods() { - ReflectionsApp reflectionsApp = new ReflectionsApp(); - assertFalse(reflectionsApp.getMethodsWithDateParam() - .isEmpty()); - } - - @Test - public void givenReturnTypeThenGetAllMethods() { - ReflectionsApp reflectionsApp = new ReflectionsApp(); - assertFalse(reflectionsApp.getMethodsWithVoidReturn() - .isEmpty()); - } -} +package com.baeldung.reflections; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.jupiter.api.Test; + +public class ReflectionsUnitTest { + + @Test + public void givenTypeThenGetAllSubTypes() { + ReflectionsApp reflectionsApp = new ReflectionsApp(); + assertFalse(reflectionsApp.getReflectionsSubTypes() + .isEmpty()); + } + + @Test + public void givenTypeAndUsingBuilderThenGetAllSubTypes() { + ReflectionsApp reflectionsApp = new ReflectionsApp(); + assertFalse(reflectionsApp.getReflectionsSubTypesUsingBuilder() + .isEmpty()); + } + + @Test + public void givenAnnotationThenGetAllAnnotatedMethods() { + ReflectionsApp reflectionsApp = new ReflectionsApp(); + assertFalse(reflectionsApp.getDateDeprecatedMethods() + .isEmpty()); + } + + @Test + public void givenAnnotationThenGetAllAnnotatedConstructors() { + ReflectionsApp reflectionsApp = new ReflectionsApp(); + assertFalse(reflectionsApp.getDateDeprecatedConstructors() + .isEmpty()); + } + + @Test + public void givenParamTypeThenGetAllMethods() { + ReflectionsApp reflectionsApp = new ReflectionsApp(); + assertFalse(reflectionsApp.getMethodsWithDateParam() + .isEmpty()); + } + + @Test + public void givenReturnTypeThenGetAllMethods() { + ReflectionsApp reflectionsApp = new ReflectionsApp(); + assertFalse(reflectionsApp.getMethodsWithVoidReturn() + .isEmpty()); + } +} diff --git a/libraries/src/test/java/com/baeldung/resilience4j/Resilience4jUnitTest.java b/libraries-6/src/test/java/com/baeldung/resilence4j/Resilience4jUnitTest.java similarity index 99% rename from libraries/src/test/java/com/baeldung/resilience4j/Resilience4jUnitTest.java rename to libraries-6/src/test/java/com/baeldung/resilence4j/Resilience4jUnitTest.java index ced95c99cb..1d69d20bc2 100644 --- a/libraries/src/test/java/com/baeldung/resilience4j/Resilience4jUnitTest.java +++ b/libraries-6/src/test/java/com/baeldung/resilence4j/Resilience4jUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.resilience4j; +package com.baeldung.resilence4j; import io.github.resilience4j.bulkhead.Bulkhead; import io.github.resilience4j.bulkhead.BulkheadConfig; diff --git a/spring-boot-angular/src/main/js/application/src/app/app.component.css b/libraries-6/src/test/resources/ftp/baz.txt similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/app.component.css rename to libraries-6/src/test/resources/ftp/baz.txt diff --git a/libraries-concurrency/README.md b/libraries-concurrency/README.md new file mode 100644 index 0000000000..d1ffe81fa8 --- /dev/null +++ b/libraries-concurrency/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Intro to Coroutines with Quasar](https://www.baeldung.com/java-quasar-coroutines) diff --git a/libraries-concurrency/coroutines-with-quasar/pom.xml b/libraries-concurrency/coroutines-with-quasar/pom.xml new file mode 100644 index 0000000000..59241272e7 --- /dev/null +++ b/libraries-concurrency/coroutines-with-quasar/pom.xml @@ -0,0 +1,84 @@ + + 4.0.0 + coroutines-with-quasar + coroutines-with-quasar + + + com.baeldung + libraries-concurrency + 1.0.0-SNAPSHOT + + + + + co.paralleluniverse + quasar-core + 0.8.0 + + + co.paralleluniverse + quasar-actors + 0.8.0 + + + co.paralleluniverse + quasar-reactive-streams + 0.8.0 + + + + + + + maven-dependency-plugin + 3.1.2 + + + getClasspathFilenames + + properties + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.baeldung.quasar.App + target/classes + java + + + -Dco.paralleluniverse.fibers.verifyInstrumentation=true + + + -javaagent:${co.paralleluniverse:quasar-core:jar} + + + -classpath + + + + com.baeldung.quasar.App + + + + + maven-compiler-plugin + 3.8.0 + + + org.apache.maven.plugins + maven-compiler-plugin + + 12 + 12 + + + + + diff --git a/libraries-concurrency/coroutines-with-quasar/src/main/java/com/baeldung/quasar/App.java b/libraries-concurrency/coroutines-with-quasar/src/main/java/com/baeldung/quasar/App.java new file mode 100644 index 0000000000..510877d1be --- /dev/null +++ b/libraries-concurrency/coroutines-with-quasar/src/main/java/com/baeldung/quasar/App.java @@ -0,0 +1,11 @@ +package com.baeldung.quasar; + +import co.paralleluniverse.fibers.Fiber; + +public class App { + public static void main(String[] args) { + new Fiber(() -> { + System.out.println("Inside fiber coroutine..."); + }).start(); + } +} diff --git a/libraries-concurrency/pom.xml b/libraries-concurrency/pom.xml new file mode 100644 index 0000000000..cb59b17674 --- /dev/null +++ b/libraries-concurrency/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + libraries-concurrency + libraries-concurrency + pom + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + + + \ No newline at end of file diff --git a/libraries-data-2/README.md b/libraries-data-2/README.md index 24618b5e37..f992186bd9 100644 --- a/libraries-data-2/README.md +++ b/libraries-data-2/README.md @@ -11,4 +11,7 @@ This module contains articles about libraries for data processing in Java. - [Guide to JMapper](https://www.baeldung.com/jmapper) - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) - [Intro to Derive4J](https://www.baeldung.com/derive4j) -More articles: [[<-- prev]](/../libraries-data) \ No newline at end of file +More articles: [[<-- prev]](/../libraries-data) + +##### Building the project +You can build the project from the command line using: *mvn clean install*, or in an IDE. If you have issues with the derive4j imports in your IDE, you have to add the folder: *target/generated-sources/annotations* to the project build path in your IDE. diff --git a/libraries-data-2/pom.xml b/libraries-data-2/pom.xml index e6106c0fe3..73c5452f77 100644 --- a/libraries-data-2/pom.xml +++ b/libraries-data-2/pom.xml @@ -128,6 +128,21 @@ ${awaitility.version} test + + org.rosuda.REngine + Rserve + ${rserve.version} + + + com.github.jbytecode + RCaller + ${rcaller.version} + + + org.renjin + renjin-script-engine + ${renjin.version} + @@ -137,6 +152,13 @@ http://repo.numericalmethod.com/maven/ default + + + + bedatadriven + bedatadriven public repo + https://nexus.bedatadriven.com/content/groups/public/ + @@ -153,6 +175,27 @@ 3.6.2 1.7.25 3.0.0 + RELEASE + 3.0 + 1.8.1 + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + com/baeldung/r/FastRMean.java + + + com/baeldung/r/FastRMeanUnitTest.java + + + + + +
\ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java b/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java new file mode 100644 index 0000000000..8348bfa403 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java @@ -0,0 +1,33 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +/** + * FastR showcase. + * + * @author Donato Rimenti + */ +public class FastRMean { + + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + */ + public double mean(int[] values) { + Context polyglot = Context.newBuilder() + .allowAllAccess(true) + .build(); + String meanScriptContent = RUtils.getMeanScriptContent(); + polyglot.eval("R", meanScriptContent); + Value rBindings = polyglot.getBindings("R"); + Value rInput = rBindings.getMember("c") + .execute(values); + return rBindings.getMember("customMean") + .execute(rInput) + .asDouble(); + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java new file mode 100644 index 0000000000..99edb8c043 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java @@ -0,0 +1,37 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import com.github.rcaller.rstuff.RCaller; +import com.github.rcaller.rstuff.RCallerOptions; +import com.github.rcaller.rstuff.RCode; + +/** + * RCaller showcase. + * + * @author Donato Rimenti + */ +public class RCallerMean { + + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + */ + public double mean(int[] values) throws IOException, URISyntaxException { + String fileContent = RUtils.getMeanScriptContent(); + RCode code = RCode.create(); + code.addRCode(fileContent); + code.addIntArray("input", values); + code.addRCode("result <- customMean(input)"); + RCaller caller = RCaller.create(code, RCallerOptions.create()); + caller.runAndReturnResult("result"); + return caller.getParser() + .getAsDoubleArray("result")[0]; + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java b/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java new file mode 100644 index 0000000000..a9393cdcc2 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java @@ -0,0 +1,33 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Collectors; + +/** + * Utility class for loading the script.R content. + * + * @author Donato Rimenti + */ +public class RUtils { + + /** + * Loads the script.R and returns its content as a string. + * + * @return the script.R content as a string + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + */ + static String getMeanScriptContent() throws IOException, URISyntaxException { + URI rScriptUri = RUtils.class.getClassLoader() + .getResource("script.R") + .toURI(); + Path inputScript = Paths.get(rScriptUri); + return Files.lines(inputScript) + .collect(Collectors.joining()); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java new file mode 100644 index 0000000000..4576ec5fb4 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java @@ -0,0 +1,36 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import javax.script.ScriptException; + +import org.renjin.script.RenjinScriptEngine; +import org.renjin.sexp.DoubleArrayVector; + +/** + * Renjin showcase. + * + * @author Donato Rimenti + */ +public class RenjinMean { + + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + * @throws ScriptException if any error occurs + */ + public double mean(int[] values) throws IOException, URISyntaxException, ScriptException { + RenjinScriptEngine engine = new RenjinScriptEngine(); + String meanScriptContent = RUtils.getMeanScriptContent(); + engine.put("input", values); + engine.eval(meanScriptContent); + DoubleArrayVector result = (DoubleArrayVector) engine.eval("customMean(input)"); + return result.asReal(); + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java new file mode 100644 index 0000000000..1aaa7fa847 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java @@ -0,0 +1,30 @@ +package com.baeldung.r; + +import org.rosuda.REngine.REXPMismatchException; +import org.rosuda.REngine.REngineException; +import org.rosuda.REngine.Rserve.RConnection; + +/** + * Rserve showcase. + * + * @author Donato Rimenti + */ +public class RserveMean { + + /** + * Connects to the Rserve istance listening on 127.0.0.1:6311 and invokes the + * customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws REngineException if any error occurs + * @throws REXPMismatchException if any error occurs + */ + public double mean(int[] values) throws REngineException, REXPMismatchException { + RConnection c = new RConnection(); + c.assign("input", values); + return c.eval("customMean(input)") + .asDouble(); + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java new file mode 100644 index 0000000000..4e7426b75a --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.r; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Test for {@link FastRMean}. + * + * @author Donato Rimenti + */ +@Ignore +public class FastRMeanUnitTest { + + /** + * Object to test. + */ + private FastRMean fastrMean = new FastRMean(); + + /** + * Test for {@link FastRMeanUnitTest#mean(int[])}. + */ + @Test + public void givenValues_whenMean_thenCorrect() { + int[] input = { 1, 2, 3, 4, 5 }; + double result = fastrMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java new file mode 100644 index 0000000000..ce6b3a4332 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java @@ -0,0 +1,37 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import javax.script.ScriptException; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Test for {@link RCallerMean}. + * + * @author Donato Rimenti + */ +@Ignore +public class RCallerMeanIntegrationTest { + + /** + * Object to test. + */ + private RCallerMean rcallerMean = new RCallerMean(); + + /** + * Test for {@link RCallerMeanIntegrationTest#mean(int[])}. + * + * @throws ScriptException if an error occurs + * @throws URISyntaxException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = rcallerMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java new file mode 100644 index 0000000000..f52d37d614 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import javax.script.ScriptException; + +import org.junit.Test; + +import org.junit.Assert; + +/** + * Test for {@link RenjinMean}. + * + * @author Donato Rimenti + */ +public class RenjinMeanUnitTest { + + /** + * Object to test. + */ + private RenjinMean renjinMean = new RenjinMean(); + + /** + * Test for {@link RenjinMeanUnitTest#mean(int[])}. + * + * @throws ScriptException if an error occurs + * @throws URISyntaxException if an error occurs + * @throws IOException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException, ScriptException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = renjinMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java new file mode 100644 index 0000000000..23d42bd8e9 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.r; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.rosuda.REngine.REXPMismatchException; +import org.rosuda.REngine.REngineException; + +/** + * Test for {@link RserveMean}. + * + * @author Donato Rimenti + */ +@Ignore +public class RserveMeanIntegrationTest { + + /** + * Object to test. + */ + private RserveMean rserveMean = new RserveMean(); + + /** + * Test for {@link RserveMeanIntegrationTest#mean(int[])}. + * + * @throws REXPMismatchException if an error occurs + * @throws REngineException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws REngineException, REXPMismatchException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = rserveMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/resources/script.R b/libraries-data-2/src/test/resources/script.R new file mode 100644 index 0000000000..08f859cc3d --- /dev/null +++ b/libraries-data-2/src/test/resources/script.R @@ -0,0 +1,3 @@ +customMean <- function(vector) { + mean(vector) +} \ No newline at end of file diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml index 682a6ed185..f028ffe8c3 100644 --- a/libraries-data-db/pom.xml +++ b/libraries-data-db/pom.xml @@ -183,7 +183,7 @@ io.ebean ebean-maven-plugin - 11.11.2 + ${ebean.plugin.version} @@ -202,6 +202,7 @@ + 11.11.2 16.5.1 3.0.0 1.8 diff --git a/libraries-data-io/README.md b/libraries-data-io/README.md index 550f353c97..3e68334ec9 100644 --- a/libraries-data-io/README.md +++ b/libraries-data-io/README.md @@ -9,3 +9,4 @@ This module contains articles about IO data processing libraries. - [Introduction To OpenCSV](https://www.baeldung.com/opencsv) - [Interact with Google Sheets from Java](https://www.baeldung.com/google-sheets-java-client) - [Introduction To Docx4J](https://www.baeldung.com/docx4j) +- [Breaking YAML Strings Over Multiple Lines](https://www.baeldung.com/yaml-multi-line) diff --git a/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/MultiLineStringsUnitTest.java b/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/MultiLineStringsUnitTest.java new file mode 100644 index 0000000000..836ac86339 --- /dev/null +++ b/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/MultiLineStringsUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.libraries.snakeyaml; + +import org.junit.Before; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; + +import java.io.File; +import java.io.InputStream; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class MultiLineStringsUnitTest { + + private Yaml yaml; + + @Before + public void setup() { + yaml = new Yaml(); + } + + @Test + public void whenLiteral_ThenLineBreaksArePresent() { + String key = parseYamlKey("literal.yaml", "key"); + assertEquals("Line1\nLine2\nLine3", key); + } + + @Test + public void whenLiteral_ThenEndingBreaksAreReducedToOne() { + String key = parseYamlKey("literal2.yaml", "key"); + assertEquals("\n\nLine1\n\nLine2\n\nLine3\n", key); + } + + @Test + public void whenFolded_ThenLineBreaksAreReplaced() { + String key = parseYamlKey("folded.yaml", "key"); + assertEquals("Line1 Line2 Line3", key); + } + + @Test + public void whenFolded_ThenEmptyLinesAreReducedToOne() { + String key = parseYamlKey("folded2.yaml", "key"); + assertEquals("Line1 Line2\n\nLine3\n", key); + } + + @Test + public void whenLiteralKeep_ThenLastEmptyLinesArePresent() { + String key = parseYamlKey("literal_keep.yaml", "key"); + assertEquals("Line1\nLine2\nLine3\n\n", key); + } + + @Test + public void whenLiteralStrip_ThenLastEmptyLinesAreRemoved() { + String key = parseYamlKey("literal_strip.yaml", "key"); + assertEquals("Line1\nLine2\nLine3", key); + } + + @Test + public void whenFoldedKeep_ThenLastEmptyLinesArePresent() { + String key = parseYamlKey("folded_keep.yaml", "key"); + assertEquals("Line1 Line2 Line3\n\n\n", key); + } + + @Test + public void whenFoldedStrip_ThenLastEmptyLinesAreRemoved() { + String key = parseYamlKey("folded_strip.yaml", "key"); + assertEquals("Line1 Line2 Line3", key); + } + + @Test + public void whenDoubleQuotes_ThenExplicitBreaksArePreserved() { + String key = parseYamlKey("plain_double_quotes.yaml", "key"); + assertEquals("Line1\nLine2\nLine3", key); + } + + @Test + public void whenSingleQuotes_ThenExplicitBreaksAreIgnored() { + String key = parseYamlKey("plain_single_quotes.yaml", "key"); + assertEquals("Line1\\nLine2\nLine3", key); + } + + String parseYamlKey(String fileName, String key) { + InputStream inputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("yaml" + File.separator + "multiline" + File.separator + fileName); + Map parsed = yaml.load(inputStream); + return parsed.get(key); + } + +} diff --git a/libraries-data-io/src/test/resources/yaml/multiline/folded.yaml b/libraries-data-io/src/test/resources/yaml/multiline/folded.yaml new file mode 100644 index 0000000000..c5fa743a08 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/folded.yaml @@ -0,0 +1,4 @@ +key: > + Line1 + Line2 + Line3 \ No newline at end of file diff --git a/libraries-data-io/src/test/resources/yaml/multiline/folded2.yaml b/libraries-data-io/src/test/resources/yaml/multiline/folded2.yaml new file mode 100644 index 0000000000..735abf9b2f --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/folded2.yaml @@ -0,0 +1,8 @@ +key: > + Line1 + Line2 + + + Line3 + + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/folded_keep.yaml b/libraries-data-io/src/test/resources/yaml/multiline/folded_keep.yaml new file mode 100644 index 0000000000..555291fd26 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/folded_keep.yaml @@ -0,0 +1,6 @@ +key: >+ + Line1 + Line2 + Line3 + + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/folded_strip.yaml b/libraries-data-io/src/test/resources/yaml/multiline/folded_strip.yaml new file mode 100644 index 0000000000..0a3a246dc2 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/folded_strip.yaml @@ -0,0 +1,7 @@ +key: >- + Line1 + Line2 + Line3 + + + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/literal.yaml b/libraries-data-io/src/test/resources/yaml/multiline/literal.yaml new file mode 100644 index 0000000000..7e02501a33 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/literal.yaml @@ -0,0 +1,4 @@ +key: | + Line1 + Line2 + Line3 \ No newline at end of file diff --git a/libraries-data-io/src/test/resources/yaml/multiline/literal2.yaml b/libraries-data-io/src/test/resources/yaml/multiline/literal2.yaml new file mode 100644 index 0000000000..7c7fed0163 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/literal2.yaml @@ -0,0 +1,10 @@ +key: | + + + Line1 + + Line2 + + Line3 + + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/literal_keep.yaml b/libraries-data-io/src/test/resources/yaml/multiline/literal_keep.yaml new file mode 100644 index 0000000000..37f22684dd --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/literal_keep.yaml @@ -0,0 +1,5 @@ +key: |+ + Line1 + Line2 + Line3 + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/literal_strip.yaml b/libraries-data-io/src/test/resources/yaml/multiline/literal_strip.yaml new file mode 100644 index 0000000000..0791e13d5d --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/literal_strip.yaml @@ -0,0 +1,5 @@ +key: |- + Line1 + Line2 + Line3 + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/plain_double_quotes.yaml b/libraries-data-io/src/test/resources/yaml/multiline/plain_double_quotes.yaml new file mode 100644 index 0000000000..ccab040a27 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/plain_double_quotes.yaml @@ -0,0 +1 @@ +key: "Line1\nLine2\nLine3" \ No newline at end of file diff --git a/libraries-data-io/src/test/resources/yaml/multiline/plain_single_quotes.yaml b/libraries-data-io/src/test/resources/yaml/multiline/plain_single_quotes.yaml new file mode 100644 index 0000000000..acbf35a462 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/plain_single_quotes.yaml @@ -0,0 +1,3 @@ +key: 'Line1\nLine2 + + Line3' \ No newline at end of file diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 2086ecb614..1267982c49 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -74,19 +74,19 @@ commons-cli commons-cli - 1.2 + ${commons.cli.version} provided commons-io commons-io - 2.1 + ${commons.io.version} provided commons-httpclient commons-httpclient - 3.0.1 + ${httpclient.version} provided @@ -133,7 +133,7 @@ org.apache.maven.plugins maven-assembly-plugin - 2.3 + ${assembly.plugin.version} src/main/resources/assembly/hadoop-job.xml @@ -158,6 +158,10 @@ + 2.3 + 1.2 + 2.1 + 3.0.1 1.2.2 1.0.0 2.4.0 diff --git a/libraries-http-2/README.md b/libraries-http-2/README.md new file mode 100644 index 0000000000..5ba45eb4a9 --- /dev/null +++ b/libraries-http-2/README.md @@ -0,0 +1,10 @@ +## HTTP + +This module contains articles about HTTP libraries. + +### Relevant Articles: + +- [Jetty ReactiveStreams HTTP Client](https://www.baeldung.com/jetty-reactivestreams-http-client) +- [Decode an OkHttp JSON Response](https://www.baeldung.com/okhttp-json-response) +- More articles [[<-- prev]](/libraries-http) + diff --git a/libraries-http-2/pom.xml b/libraries-http-2/pom.xml new file mode 100644 index 0000000000..c0a4f6455d --- /dev/null +++ b/libraries-http-2/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + libraries-http-2 + libraries-http-2 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + com.squareup.okhttp3 + okhttp + ${okhttp.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.google.code.gson + gson + ${gson.version} + + + com.squareup.okhttp3 + mockwebserver + ${mockwebserver.version} + test + + + + + 3.14.2 + 2.8.5 + 3.14.2 + 2.9.8 + + + diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java similarity index 100% rename from libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java rename to libraries-http-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java b/libraries-http-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java similarity index 100% rename from libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java rename to libraries-http-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java diff --git a/libraries-http/README.md b/libraries-http/README.md index f5afb2d277..61b2904cee 100644 --- a/libraries-http/README.md +++ b/libraries-http/README.md @@ -12,3 +12,6 @@ This module contains articles about HTTP libraries. - [Introduction to Retrofit](https://www.baeldung.com/retrofit) - [A Guide to Unirest](https://www.baeldung.com/unirest) - [Creating REST Microservices with Javalin](https://www.baeldung.com/javalin-rest-microservices) +- [A Quick Guide to Timeouts in OkHttp](https://www.baeldung.com/okhttp-timeouts) +- [A Quick Guide to Post Requests with OkHttp](https://www.baeldung.com/okhttp-post) +- More articles [[next -->]](/libraries-http-2) diff --git a/libraries-http/pom.xml b/libraries-http/pom.xml index 6261456486..cbc74ce132 100644 --- a/libraries-http/pom.xml +++ b/libraries-http/pom.xml @@ -71,7 +71,7 @@ com.google.code.gson gson - 2.8.5 + ${gson.version} @@ -116,6 +116,7 @@ + 2.8.5 4.5.3 2.9.8 3.6.2 diff --git a/libraries-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java b/libraries-io/src/test/java/com/baeldung/java/io/remote/SftpFileTransferLiveTest.java similarity index 99% rename from libraries-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java rename to libraries-io/src/test/java/com/baeldung/java/io/remote/SftpFileTransferLiveTest.java index 192153bc90..5846128082 100644 --- a/libraries-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java +++ b/libraries-io/src/test/java/com/baeldung/java/io/remote/SftpFileTransferLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.io.remote; +package com.baeldung.java.io.remote; import java.io.IOException; diff --git a/libraries-security/README.md b/libraries-security/README.md index 819bc866cf..580ebdeab0 100644 --- a/libraries-security/README.md +++ b/libraries-security/README.md @@ -9,4 +9,4 @@ This module contains articles about security libraries. - [Guide to Google Tink](https://www.baeldung.com/google-tink) - [Introduction to BouncyCastle with Java](https://www.baeldung.com/java-bouncy-castle) - [Intro to Jasypt](https://www.baeldung.com/jasypt) -- [Digital Signature in Java](https://www.baeldung.com/java-digital-signature) +- [Digital Signatures in Java](https://www.baeldung.com/java-digital-signature) diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index e287de4527..e02f766141 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -23,7 +23,9 @@ org.springframework.security.oauth spring-security-oauth2 + ${spring-boot.version} + org.springframework spring-web diff --git a/libraries-security/src/main/resources/Baeldung.p12 b/libraries-security/src/main/resources/Baeldung.p12 new file mode 100644 index 0000000000..65ec8bc8fe Binary files /dev/null and b/libraries-security/src/main/resources/Baeldung.p12 differ diff --git a/libraries-server/README.md b/libraries-server/README.md index d9e6b8b206..7e41f33a0c 100644 --- a/libraries-server/README.md +++ b/libraries-server/README.md @@ -13,3 +13,4 @@ This module contains articles about server libraries. - [MQTT Client in Java](https://www.baeldung.com/java-mqtt-client) - [Guide to XMPP Smack Client](https://www.baeldung.com/xmpp-smack-chat-client) - [A Guide to NanoHTTPD](https://www.baeldung.com/nanohttpd) +- [HTTP/2 in Jetty](https://www.baeldung.com/jetty-http-2) diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index a849708cd8..eb9cb61e56 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -5,6 +5,7 @@ libraries-server 0.0.1-SNAPSHOT libraries-server + war com.baeldung @@ -105,12 +106,51 @@ + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.version} + + 8888 + quit + + -Xbootclasspath/p:${settings.localRepository}/org/mortbay/jetty/alpn/alpn-boot/${alpn.version}/alpn-boot-${alpn.version}.jar + + ${basedir}/src/main/config/jetty.xml + + / + + + + + org.eclipse.jetty.http2 + http2-server + ${jetty.version} + + + org.eclipse.jetty + jetty-alpn-openjdk8-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlets + ${jetty.version} + + + + + 3.6.2 4.5.3 - 9.4.8.v20171121 + 9.4.27.v20200227 4.1.20.Final + 8.1.11.v20170118 8.5.24 4.3.1 1.2.0 diff --git a/libraries-server/src/main/config/jetty.xml b/libraries-server/src/main/config/jetty.xml new file mode 100644 index 0000000000..fd4a50382b --- /dev/null +++ b/libraries-server/src/main/config/jetty.xml @@ -0,0 +1,79 @@ + + + + + + + src/main/resources/keystore.jks + storepwd + src/main/resources/truststore.jks + storepwd + TLSv1.2 + + + + + + + + + + + + + + + + + http/1.1 + + + + + + + + + + + + 8443 + + + + + + + + + + + + + + + + + + alpn + + + + + h2,h2-17 + + + + + + + + + + + + 8444 + + + + \ No newline at end of file diff --git a/libraries-server/src/main/java/com/baeldung/jetty/http2/Http2JettyServlet.java b/libraries-server/src/main/java/com/baeldung/jetty/http2/Http2JettyServlet.java new file mode 100644 index 0000000000..56b75c45d3 --- /dev/null +++ b/libraries-server/src/main/java/com/baeldung/jetty/http2/Http2JettyServlet.java @@ -0,0 +1,29 @@ +package com.baeldung.jetty.http2; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class Http2JettyServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.addHeader("Cache-control", "no-store, no-cache, must-revalidate"); + response.addDateHeader("Last-Modified", 0); + response.addDateHeader("Expires", 0); + + String requestPath = request.getRequestURI(); + InputStream input = getServletContext().getResourceAsStream(requestPath); + OutputStream output = response.getOutputStream(); + byte[] buffer = new byte[1024]; + int read; + while ((read = input.read(buffer)) >= 0) { + output.write(buffer, 0, read); + } + } + +} diff --git a/libraries-server/src/main/resources/keystore.jks b/libraries-server/src/main/resources/keystore.jks new file mode 100644 index 0000000000..428ba54776 Binary files /dev/null and b/libraries-server/src/main/resources/keystore.jks differ diff --git a/libraries-server/src/main/resources/truststore.jks b/libraries-server/src/main/resources/truststore.jks new file mode 100644 index 0000000000..839cb8c351 Binary files /dev/null and b/libraries-server/src/main/resources/truststore.jks differ diff --git a/libraries-server/src/main/webapp/WEB-INF/web.xml b/libraries-server/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..75d7e11c64 --- /dev/null +++ b/libraries-server/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,33 @@ + + + + + http2Jetty + com.baeldung.jetty.http2.Http2JettyServlet + + + http2Jetty + /images/* + + + + push + org.eclipse.jetty.servlets.PushCacheFilter + + ports + 8444 + + + maxAssociations + 32 + + + + push + /* + + + \ No newline at end of file diff --git a/libraries-server/src/main/webapp/http2.html b/libraries-server/src/main/webapp/http2.html new file mode 100644 index 0000000000..4563945a5e --- /dev/null +++ b/libraries-server/src/main/webapp/http2.html @@ -0,0 +1,14 @@ + + + + Baeldung HTTP/2 Client in Jetty + + +

HTTP/2 Demo

+
+ latest articles + rest with spring + weekly reviews +
+ + \ No newline at end of file diff --git a/libraries-server/src/main/webapp/images/homepage-latest_articles.jpg b/libraries-server/src/main/webapp/images/homepage-latest_articles.jpg new file mode 100644 index 0000000000..59e78e4560 Binary files /dev/null and b/libraries-server/src/main/webapp/images/homepage-latest_articles.jpg differ diff --git a/libraries-server/src/main/webapp/images/homepage-rest_with_spring.jpg b/libraries-server/src/main/webapp/images/homepage-rest_with_spring.jpg new file mode 100644 index 0000000000..43d9221e85 Binary files /dev/null and b/libraries-server/src/main/webapp/images/homepage-rest_with_spring.jpg differ diff --git a/libraries-server/src/main/webapp/images/homepage-weekly_reviews.jpg b/libraries-server/src/main/webapp/images/homepage-weekly_reviews.jpg new file mode 100644 index 0000000000..0d6d111911 Binary files /dev/null and b/libraries-server/src/main/webapp/images/homepage-weekly_reviews.jpg differ diff --git a/libraries-server/src/main/webapp/index.html b/libraries-server/src/main/webapp/index.html new file mode 100644 index 0000000000..2497893d82 --- /dev/null +++ b/libraries-server/src/main/webapp/index.html @@ -0,0 +1,12 @@ + + + + Baeldung: HTTP2 Client in Jetty + + +

HTTP/1.1

+
+

HTTP/2 Push

+
+ + \ No newline at end of file diff --git a/libraries-testing/README.md b/libraries-testing/README.md index 332debfe18..ffdefe4b19 100644 --- a/libraries-testing/README.md +++ b/libraries-testing/README.md @@ -11,3 +11,4 @@ This module contains articles about test libraries. - [Introduction to Awaitlity](https://www.baeldung.com/awaitlity-testing) - [Introduction to Hoverfly in Java](https://www.baeldung.com/hoverfly) - [Testing with Hamcrest](https://www.baeldung.com/java-junit-hamcrest-guide) +- [Introduction To DBUnit](https://www.baeldung.com/java-dbunit) diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index c84f8dda76..ad6c81a3d6 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -127,7 +127,28 @@ org.asciidoctor asciidoctor-maven-plugin - 1.5.7.1 + ${asciidoctor.version} + + + + org.dbunit + dbunit + ${dbunit.version} + test + + + + com.h2database + h2 + ${h2.version} + test + + + + org.assertj + assertj-core + ${assertj-core.version} + test @@ -150,11 +171,22 @@
+ + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven-compiler-plugin.source} + ${maven-compiler-plugin.target} + + + - 1.9.9 + 1.5.7.1 + 1.9.9 1.9.0 1.9.0 1.9.27 @@ -165,6 +197,12 @@ 4.1.1 3.6.2 2.0.0.0 + 1.4.200 + 2.7.0 + 3.14.0 + 1.8 + 1.8 + 3.8.1
diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java b/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java new file mode 100644 index 0000000000..cc29d9c58a --- /dev/null +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java @@ -0,0 +1,8 @@ +package com.baeldung.dbunit; + +public class ConnectionSettings { + public static final String JDBC_DRIVER = org.h2.Driver.class.getName(); + public static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:dbunit/schema.sql'"; + public static final String USER = "sa"; + public static final String PASSWORD = ""; +} diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java new file mode 100644 index 0000000000..93c7e9a456 --- /dev/null +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -0,0 +1,168 @@ +package com.baeldung.dbunit; + +import org.dbunit.Assertion; +import org.dbunit.DataSourceBasedDBTestCase; +import org.dbunit.assertion.DiffCollectingFailureHandler; +import org.dbunit.assertion.Difference; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.operation.DatabaseOperation; +import org.h2.jdbcx.JdbcDataSource; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.platform.commons.logging.Logger; +import org.junit.platform.commons.logging.LoggerFactory; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import javax.sql.DataSource; +import java.io.InputStream; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; + +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static java.util.stream.Collectors.joining; +import static org.assertj.core.api.Assertions.assertThat; +import static org.dbunit.Assertion.assertEqualsIgnoreCols; + +@RunWith(JUnit4.class) +public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { + + private static final Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); + + @Override + protected DataSource getDataSource() { + JdbcDataSource dataSource = new JdbcDataSource(); + dataSource.setURL(JDBC_URL); + dataSource.setUser("sa"); + dataSource.setPassword(""); + return dataSource; + } + + @Override + protected IDataSet getDataSet() throws Exception { + try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(resourceAsStream); + } + } + + @Override + protected DatabaseOperation getSetUpOperation() { + return DatabaseOperation.REFRESH; + } + + @Override + protected DatabaseOperation getTearDownOperation() { + return DatabaseOperation.DELETE_ALL; + } + + @Before + public void setUp() throws Exception { + super.setUp(); + } + + @After + public void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void givenDataSet_whenSelect_thenFirstTitleIsGreyTShirt() throws SQLException { + final Connection connection = getDataSource().getConnection(); + + final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test + public void givenDataSetEmptySchema_whenDataSetCreated_thenTablesAreEqual() throws Exception { + final IDataSet expectedDataSet = getDataSet(); + final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + final IDataSet databaseDataSet = getConnection().createDataSet(); + final ITable actualTable = databaseDataSet.getTable("CLIENTS"); + Assertion.assertEquals(expectedTable, actualTable); + } + + @Test + public void givenDataSet_whenInsert_thenTableHasNewClient() throws Exception { + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-user.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + final Connection conn = getDataSource().getConnection(); + + conn.createStatement() + .executeUpdate( + "INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); + final ITable actualData = getConnection() + .createQueryTable( + "result_name", + "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); + + assertEqualsIgnoreCols(expectedTable, actualData, new String[] { "id" }); + } + } + + @Test + public void givenDataSet_whenDelete_thenItemIsDeleted() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final InputStream is = DataSourceDBUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenUpdate_thenItemHasNewName() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final InputStream is = DataSourceDBUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenInsertUnexpectedData_thenFailOnAllUnexpectedValues() throws Exception { + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-multiple-failures.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = expectedDataSet.getTable("ITEMS"); + final Connection conn = getDataSource().getConnection(); + final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); + + conn.createStatement().executeUpdate( + "INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); + final ITable actualData = getConnection().createDataSet().getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualData, collectingHandler); + if (!collectingHandler.getDiffList().isEmpty()) { + String message = (String) collectingHandler + .getDiffList() + .stream() + .map(d -> formatDifference((Difference) d)).collect(joining("\n")); + logger.error(() -> message); + } + } + } + + private static String formatDifference(Difference diff) { + return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff.getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff.getActualValue(); + } +} diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java new file mode 100644 index 0000000000..6243af9676 --- /dev/null +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -0,0 +1,159 @@ +package com.baeldung.dbunit; + +import org.dbunit.Assertion; +import org.dbunit.IDatabaseTester; +import org.dbunit.JdbcDatabaseTester; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.filter.DefaultColumnFilter; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.operation.DatabaseOperation; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.InputStream; +import java.sql.Connection; +import java.sql.ResultSet; + +import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; +import static com.baeldung.dbunit.ConnectionSettings.USER; +import static org.assertj.core.api.Assertions.assertThat; +import static org.dbunit.Assertion.assertEquals; + +@RunWith(JUnit4.class) +public class OldSchoolDbUnitTest { + + private static IDatabaseTester tester = null; + + @BeforeClass + public static void setUp() throws Exception { + tester = initDatabaseTester(); + } + + private static IDatabaseTester initDatabaseTester() throws Exception { + final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); + tester.setDataSet(initDataSet()); + tester.setSetUpOperation(DatabaseOperation.REFRESH); + tester.setTearDownOperation(DatabaseOperation.DELETE_ALL); + return tester; + } + + private static IDataSet initDataSet() throws Exception { + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(is); + } + } + + @Before + public void setup() throws Exception { + tester.onSetup(); + } + + @After + public void tearDown() throws Exception { + tester.onTearDown(); + } + + @Test + public void givenDataSet_whenSelect_thenFirstTitleIsGreyTShirt() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test + public void givenDataSet_whenInsert_thenGetResultsAreStillEqualIfIgnoringColumnsWithDifferentProduced() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + final String[] excludedColumns = { "id", "produced" }; + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable( + expectedDataSet.getTable("ITEMS"), excludedColumns); + + connection.createStatement().executeUpdate( + "INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + final ITable actualTable = DefaultColumnFilter.excludedColumnsTable( + databaseDataSet.getTable("ITEMS"), excludedColumns); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenDelete_thenItemIsRemoved() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenDelete_thenItemIsRemovedAndResultsEqualIfProducedIsIgnored() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); + + assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenUpdate_thenItemHasNewName() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenUpdateWithNoProduced_thenItemHasNewName() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[] { "produced" }); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); + assertEquals(expectedTable, actualTable); + } + } + +} diff --git a/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java b/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java index ce9638c4af..822468e91f 100644 --- a/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java @@ -78,10 +78,10 @@ public class JsonAssertUnitTest { @Test public void givenArray_whenComparing_thenOrderMustMatchForStrict() throws JSONException { - String result = "[Alex, Barbera, Charlie, Xavier]"; - JSONAssert.assertEquals("[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.LENIENT); - JSONAssert.assertEquals("[Alex, Barbera, Charlie, Xavier]", result, JSONCompareMode.STRICT); - JSONAssert.assertNotEquals("[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.STRICT); + String result = "[Alex, Barbera, Charlie, Wolf]"; + JSONAssert.assertEquals("[Charlie, Alex, Wolf, Barbera]", result, JSONCompareMode.LENIENT); + JSONAssert.assertEquals("[Alex, Barbera, Charlie, Wolf]", result, JSONCompareMode.STRICT); + JSONAssert.assertNotEquals("[Charlie, Alex, Wolf, Barbera]", result, JSONCompareMode.STRICT); } @Test @@ -94,7 +94,7 @@ public class JsonAssertUnitTest { @Test public void whenComparingSizeOfArray_thenPass() throws JSONException { - String names = "{names:[Alex, Barbera, Charlie, Xavier]}"; + String names = "{names:[Alex, Barbera, Charlie, Wolf]}"; JSONAssert.assertEquals("{names:[4]}", names, new ArraySizeComparator(JSONCompareMode.LENIENT)); } diff --git a/libraries-testing/src/test/resources/dbunit/data.xml b/libraries-testing/src/test/resources/dbunit/data.xml new file mode 100644 index 0000000000..4865dec54c --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/data.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/expected-ignoring-registered_at.xml b/libraries-testing/src/test/resources/dbunit/expected-ignoring-registered_at.xml new file mode 100644 index 0000000000..ea57b6a961 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/expected-ignoring-registered_at.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/libraries-testing/src/test/resources/dbunit/expected-multiple-failures.xml b/libraries-testing/src/test/resources/dbunit/expected-multiple-failures.xml new file mode 100644 index 0000000000..ea57b6a961 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/expected-multiple-failures.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/libraries-testing/src/test/resources/dbunit/expected-user.xml b/libraries-testing/src/test/resources/dbunit/expected-user.xml new file mode 100644 index 0000000000..631dd84210 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/expected-user.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/libraries-testing/src/test/resources/dbunit/items.xml b/libraries-testing/src/test/resources/dbunit/items.xml new file mode 100644 index 0000000000..d13e93bbe0 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_delete.xml b/libraries-testing/src/test/resources/dbunit/items_exp_delete.xml new file mode 100644 index 0000000000..a6fa2b33e8 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_delete.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_delete_no_produced.xml b/libraries-testing/src/test/resources/dbunit/items_exp_delete_no_produced.xml new file mode 100644 index 0000000000..3e7f854f5f --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_delete_no_produced.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_rename.xml b/libraries-testing/src/test/resources/dbunit/items_exp_rename.xml new file mode 100644 index 0000000000..32f1d57cf6 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_rename.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml b/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml new file mode 100644 index 0000000000..4f14b17113 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/schema.sql b/libraries-testing/src/test/resources/dbunit/schema.sql new file mode 100644 index 0000000000..c2a8d2d630 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/schema.sql @@ -0,0 +1,28 @@ +CREATE TABLE IF NOT EXISTS CLIENTS +( + `id` int AUTO_INCREMENT NOT NULL, + `first_name` varchar(100) NOT NULL, + `last_name` varchar(100) NOT NULL, + PRIMARY KEY (`id`) +); + +CREATE TABLE IF NOT EXISTS ITEMS +( + `id` int AUTO_INCREMENT NOT NULL, + `title` varchar(100) NOT NULL, + `produced` date, + `price` float, + PRIMARY KEY (`id`) +); + +CREATE TABLE IF NOT EXISTS PURCHASES +( + `id` int NOT NULL AUTO_INCREMENT, + `id_user` int NOT NULL, + `id_item` int NOT NULL, + `total_price` float NOT NULL, + `quantity` int(11) NOT NULL, + PRIMARY KEY (`id`), + FOREIGN KEY (`id_user`) REFERENCES CLIENTS (`id`) ON DELETE CASCADE, + FOREIGN KEY (`id_item`) REFERENCES ITEMS (`id`) ON DELETE CASCADE ON UPDATE CASCADE +); diff --git a/libraries-testing/src/test/resources/dbunit/users.xml b/libraries-testing/src/test/resources/dbunit/users.xml new file mode 100644 index 0000000000..f04943c4cc --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/users.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml b/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml new file mode 100644 index 0000000000..20a2f2f1a7 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml b/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml new file mode 100644 index 0000000000..1ab6cf53b8 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/libraries/README.md b/libraries/README.md index 79ba8fe55d..b61289504c 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -19,30 +19,4 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Software Transactional Memory in Java Using Multiverse](https://www.baeldung.com/java-multiverse-stm) - [Locality-Sensitive Hashing in Java Using Java-LSH](https://www.baeldung.com/locality-sensitive-hashing) - [Introduction to Neuroph](https://www.baeldung.com/neuroph) -- [Quick Guide to RSS with Rome](https://www.baeldung.com/rome-rss) -- [Introduction to PCollections](https://www.baeldung.com/java-pcollections) -- [Introduction to Eclipse Collections](https://www.baeldung.com/eclipse-collections) -- [DistinctBy in the Java Stream API](https://www.baeldung.com/java-streams-distinct-by) -- [Introduction to NoException](https://www.baeldung.com/no-exception) -- [Spring Yarg Integration](https://www.baeldung.com/spring-yarg) -- [Delete a Directory Recursively in Java](https://www.baeldung.com/java-delete-directory) -- [Guide to JDeferred](https://www.baeldung.com/jdeferred) -- [Introduction to MBassador](https://www.baeldung.com/mbassador) -- [Using Pairs in Java](https://www.baeldung.com/java-pairs) -- [Introduction to Caffeine](https://www.baeldung.com/java-caching-caffeine) -- [Introduction to StreamEx](https://www.baeldung.com/streamex) -- [A Docker Guide for Java](https://www.baeldung.com/docker-java-api) -- [Introduction to Akka Actors in Java](https://www.baeldung.com/akka-actors-java) -- [A Guide to Byte Buddy](https://www.baeldung.com/byte-buddy) -- [Introduction to jOOL](https://www.baeldung.com/jool) -- [Consumer Driven Contracts with Pact](https://www.baeldung.com/pact-junit-consumer-driven-contracts) -- [Introduction to Atlassian Fugue](https://www.baeldung.com/java-fugue) -- [Publish and Receive Messages with Nats Java Client](https://www.baeldung.com/nats-java-client) -- [Java Concurrency Utility with JCTools](https://www.baeldung.com/java-concurrency-jc-tools) -- [Introduction to JavaPoet](https://www.baeldung.com/java-poet) -- [Guide to Resilience4j](https://www.baeldung.com/resilience4j) -- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once) -- [Implementing a FTP-Client in Java](https://www.baeldung.com/java-ftp-client) -- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library) -- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library) - More articles [[next -->]](/libraries-2) diff --git a/libraries/pom.xml b/libraries/pom.xml index 13f91711fd..fee66f928d 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -12,18 +12,6 @@ - - - com.typesafe.akka - akka-actor_2.12 - ${typesafe-akka.version} - - - com.typesafe.akka - akka-testkit_2.12 - ${typesafe-akka.version} - test - org.beykery @@ -63,18 +51,6 @@ javers-core ${javers.version} - - - io.nats - jnats - ${jnats.version} - - - - rome - rome - ${rome.version} - net.serenity-bdd serenity-core @@ -218,11 +194,6 @@ quartz ${quartz.version} - - one.util - streamex - ${streamex.version} - org.jooq jool @@ -245,28 +216,9 @@ ${java-lsh.version} - au.com.dius - pact-jvm-consumer-junit_2.11 - ${pact.version} - test - - - org.codehaus.groovy - groovy-all - - - - - org.awaitility - awaitility - ${awaitility.version} - test - - - org.awaitility - awaitility-proxy - ${awaitility.version} - test + commons-io + commons-io + ${commonsio.version} org.hamcrest @@ -274,89 +226,12 @@ ${org.hamcrest.java-hamcrest.version} test - - net.bytebuddy - byte-buddy - ${bytebuddy.version} - - - net.bytebuddy - byte-buddy-agent - ${bytebuddy.version} - - - org.pcollections - pcollections - ${pcollections.version} - - - com.machinezoo.noexception - noexception - ${noexception.version} - - - org.eclipse.collections - eclipse-collections - ${eclipse-collections.version} - - - io.vavr - vavr - ${vavr.version} - - - com.haulmont.yarg - yarg - ${yarg.version} - - - net.engio - mbassador - ${mbassador.version} - - - org.jdeferred - jdeferred-core - ${jdeferred.version} - com.codepoetics protonpack ${protonpack.version} - - org.functionaljava - functionaljava-java8 - ${functionaljava.version} - - - com.github.ben-manes.caffeine - caffeine - ${caffeine.version} - - - - - com.github.docker-java - docker-java - ${docker.version} - - - org.slf4j - slf4j-log4j12 - - - org.slf4j - jcl-over-slf4j - - - ch.qos.logback - logback-classic - - - - @@ -364,78 +239,12 @@ google-oauth-client-jetty ${google-api.version} - - org.apache.kafka - kafka-streams - ${kafka.version} - - - org.apache.kafka - kafka-clients - ${kafka.version} - test - test - - - - - io.atlassian.fugue - fugue - ${fugue.version} - - - - org.jctools - jctools-core - ${jctools.version} - - - - - io.github.resilience4j - resilience4j-circuitbreaker - ${resilience4j.version} - - - io.github.resilience4j - resilience4j-bulkhead - ${resilience4j.version} - - - io.github.resilience4j - resilience4j-retry - ${resilience4j.version} - - - io.github.resilience4j - resilience4j-timelimiter - ${resilience4j.version} - - - com.squareup - javapoet - ${javapoet.version} - org.hamcrest hamcrest-all ${hamcrest-all.version} test - - - org.mockftpserver - MockFtpServer - ${mockftpserver.version} - test - - - - org.reflections - reflections - ${reflections.version} - - @@ -523,7 +332,7 @@ org.apache.maven.plugins maven-shade-plugin - 2.2 + ${shade.plugin.version} package @@ -552,17 +361,17 @@ + + 2.2 0.7.0 3.2.7 1.2 3.6.2 3.1.0 - 1.0 - 2.92 1.9.26 1.41.0 @@ -571,26 +380,10 @@ 1.1.0 0.10 3.5.0 - 3.0.0 2.0.0.0 - 1.7.1 - 2.1.2 - 1.0 - 8.2.0 - 0.6.5 - 0.9.0 - 1.15 - 2.5.5 1.23.0 - 2.0.0 - 3.0.14 - 0.9.4.0006L - 2.1.2 - 2.5.11 - 0.12.1 - 1.10.0 1.3 3.2.0-m7 5.1.1 @@ -603,16 +396,9 @@ 2.3.0 0.9.12 1.19 - 1.1.0 - 2.0.4 - 1.3.1 - 1.2.6 - 4.8.1 - 4.5.1 3.0.2 - 2.7.1 3.6 - 0.9.11 + 2.6
diff --git a/linux-bash/command-line-arguments/src/main/bash/README.md b/linux-bash/command-line-arguments/src/main/bash/README.md new file mode 100644 index 0000000000..27d89fff99 --- /dev/null +++ b/linux-bash/command-line-arguments/src/main/bash/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [How to Use Command Line Arguments in a Bash Script](https://www.baeldung.com/linux/use-command-line-arguments-in-bash-script) diff --git a/linux-bash/functions/src/main/bash/README.md b/linux-bash/functions/src/main/bash/README.md new file mode 100644 index 0000000000..5fb6958b9d --- /dev/null +++ b/linux-bash/functions/src/main/bash/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Bash Functions in Linux](https://www.baeldung.com/linux/bash-functions) diff --git a/linux-bash/functions/src/main/bash/functions.sh b/linux-bash/functions/src/main/bash/functions.sh new file mode 100755 index 0000000000..41ff0ca434 --- /dev/null +++ b/linux-bash/functions/src/main/bash/functions.sh @@ -0,0 +1,208 @@ +#!/bin/bash + +# Subsection 2.1 +simple_function() { + for ((i=0;i<5;++i)) do + echo -n " "$i" "; + done +} + +function simple_function_no_parantheses { + for ((i=0;i<5;++i)) do + echo -n " "$i" "; + done +} + +function simple_for_loop() + for ((i=0;i<5;++i)) do + echo -n " "$i" "; + done + +function simple_comparison() + if [[ "$1" -lt 5 ]]; then + echo "$1 is smaller than 5" + else + echo "$1 is greater than 5" + fi + +# Subsection 2.2 +function simple_inputs() { + echo "This is the first argument [$1]" + echo "This is the second argument [$2]" + echo "Calling function with $# aruments" +} + +# Subsection 2.3 +global_sum=0 +function global_sum_outputs() { + global_sum=$(($1+$2)) +} + +function cs_sum_outputs() { + sum=$(($1+$2)) + echo $sum +} + +# Subsection 2.4 +function arg_ref_sum_outputs() { + declare -n sum_ref=$3 + sum_ref=$(($1+$2)) +} + +# Subsection 3.1 +variable="baeldung" +function variable_scope2() { + echo "Variable inside function variable_scope2: [$variable]" + local variable="ipsum" +} + +function variable_scope() { + local variable="lorem" + echo "Variable inside function variable_scope: [$variable]" + variable_scope2 +} + +# Subsection 3.2 +subshell_sum=0 +function simple_subshell_sum() ( + subshell_sum=$(($1+$2)) + echo "Value of sum in function with global variables: [$subshell_sum]" +) + +function simple_subshell_ref_sum() ( + declare -n sum_ref=$3 + sum_ref=$(($1+$2)) + echo "Value of sum in function with ref arguments: [$sum_ref]" +) + +# Subsection 3.3 +function redirection_in() { + while read input; + do + echo "$input" + done +} < infile + +function redirection_in_ps() { + read + while read -a input; + do + echo "User[${input[2]}]->File[${input[8]}]" + done +} < <(ls -ll /) + +function redirection_out_ps() { + declare -a output=("baeldung" "lorem" "ipsum" "caracg") + for element in "${output[@]}" + do + echo "$element" + done +} > >(grep "g") + +function redirection_out() { + declare -a output=("baeldung" "lorem" "ipsum") + for element in "${output[@]}" + do + echo "$element" + done +} > outfile + +# Subsection 3.4 +function fibonnaci_recursion() { + argument=$1 + if [[ "$argument" -eq 0 ]] || [[ "$argument" -eq 1 ]]; then + echo $argument + else + first=$(fibonnaci_recursion $(($argument-1))) + second=$(fibonnaci_recursion $(($argument-2))) + echo $(( $first + $second )) + fi +} + +# main menu entry point +echo "****Functions samples menu*****" +PS3="Your choice (1,2,3 etc.):" +options=("function_definitions" "function_input_args" "function_outputs" \ + "function_variables" "function_subshells" "function_redirections" \ + "function_recursion" "quit") +select option in "${options[@]}" +do + case $option in + "function_definitions") + echo -e "\n" + echo "**Different ways to define a function**" + echo -e "No function keyword:" + simple_function + echo -e "\nNo function parantheses:" + simple_function_no_parantheses + echo -e "\nOmitting curly braces:" + simple_for_loop + echo -e "\n" + ;; + "function_input_args") + echo -e "\n" + echo "**Passing inputs to a function**" + simple_inputs lorem ipsum + echo -e "\n" + ;; + "function_outputs") + echo -e "\n" + echo "**Getting outputs from a function**" + global_sum_outputs 1 2 + echo -e ">1+2 using global variables: [$global_sum]" + cs_sum=$(cs_sum_outputs 1 2) + echo -e ">1+2 using command substitution: [$cs_sum]" + arg_ref_sum_outputs 1 2 arg_ref_sum + echo -e ">1+2 using argument references: [$arg_ref_sum]" + echo -e "\n" + ;; + "function_variables") + echo -e "\n" + echo "**Overriding variable scopes**" + echo "Global value of variable: [$variable]" + variable_scope + echo -e "\n" + ;; + "function_subshells") + echo -e "\n" + echo "**Running function in subshell**" + echo "Global value of sum: [$subshell_sum]" + simple_subshell_sum 1 2 + echo "Value of sum after subshell function with \ +global variables: [$subshell_sum]" + subshell_sum_arg_ref=0 + simple_subshell_ref_sum 1 2 subshell_sum_arg_ref + echo "Value of sum after subshell function with \ +ref arguments: [$subshell_sum_arg_ref]" + echo -e "\n" + ;; + "function_redirections") + echo -e "\n" + echo "**Function redirections**" + echo -e ">Function input redirection from file:" + redirection_in + echo -e ">Function input redirection from command:" + redirection_in_ps + echo -e ">Function output redirection to file:" + redirection_out + cat outfile + echo -e ">Function output redirection to command:" + red_ps=$(redirection_out_ps) + echo "$red_ps" + echo -e "\n" + ;; + "function_recursion") + echo -e "\n" + echo "**Function recursion**" + fibo_res1=$(fibonnaci_recursion 7) + echo "The 7th Fibonnaci number: [$fibo_res1]" + fibo_res2=$(fibonnaci_recursion 15) + echo "The 15th Fibonnaci number: [$fibo_res2]" + echo -e "\n" + ;; + "quit") + break + ;; + *) echo "Invalid option";; + esac +done \ No newline at end of file diff --git a/linux-bash/functions/src/main/bash/infile b/linux-bash/functions/src/main/bash/infile new file mode 100644 index 0000000000..b1fa680af4 --- /dev/null +++ b/linux-bash/functions/src/main/bash/infile @@ -0,0 +1,3 @@ +Honda Insight 2010 +Honda Element 2006 +Chevrolet Avalanche 2002 diff --git a/linux-bash/read/README.md b/linux-bash/read/README.md new file mode 100644 index 0000000000..56c1dd5b24 --- /dev/null +++ b/linux-bash/read/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Guide to the Linux read Command](https://www.baeldung.com/linux/read-command) diff --git a/linux-bash/read/src/main/bash/file.csv b/linux-bash/read/src/main/bash/file.csv new file mode 100644 index 0000000000..69a50772ab --- /dev/null +++ b/linux-bash/read/src/main/bash/file.csv @@ -0,0 +1 @@ +car,car model,car year,car vin;Mercury,Grand Marquis,2000,2G61S5S33F9986032;Mitsubishi,Truck,1995,SCFFDABE1CG137362;Ford,Mustang,1968,2G4WS55J351278031;Ford,Crown Victoria,1996,4T1BK1EB8EU586249;GMC,Envoy,2004,WVGEF9BP3FD720618; diff --git a/linux-bash/read/src/main/bash/read_inputs.sh b/linux-bash/read/src/main/bash/read_inputs.sh new file mode 100755 index 0000000000..30eb598ac3 --- /dev/null +++ b/linux-bash/read/src/main/bash/read_inputs.sh @@ -0,0 +1,122 @@ +#!/bin/bash + +# section 2.1 +default_read(){ + read input1 input2 input3 + echo "[$input1] [$input2] [$input3]" +} + +# section 2.2 +custom_ifs_no_array(){ + OLDIFS=$IFS + IFS=";" + read input1 input2 input3 + echo "[$input1] [$input2] [$input3]" + # restore default IFS after we're finished so current shell behaves like before + IFS=$OLDIFS +} + +# Section 2.3 +prompt_read_password(){ + prompt="You shall not pass:" + read -p "$prompt" -s input + echo -e "\ninput password [$input]" +} + +array_read(){ + declare -a input_array + text="baeldung is a cool tech site" + read -e -i "$text" -a input_array + for input in ${input_array[@]} + do + echo " word [$input]" + done +} + +# section 3.1 +file_read(){ + exec {file_descriptor}<"./file.csv" + declare -a input_array + delimiter=";" + while IFS="," read -a input_array -d $delimiter -u $file_descriptor + do + echo "${input_array[0]},${input_array[2]}" + done + exec {file_descriptor}>&- +} + +# section 3.2 +command_pipe(){ + ls -ll / | { declare -a input + read + while read -a input; + do + echo "${input[0]} ${input[8]}" + done } +} + +# section 3.3 +timeout_input_read(){ + prompt="You shall not pass:" + read -p "$prompt" -s -r -t 5 input + if [ -z "$input" ]; then + echo -e "\ntimeout occured!" + else + echo -e "\ninput word [$input]" + fi +} + +exactly_n_read(){ + prompt="Reading exactly 11 chars:" + read -p "$prompt" -N 11 -t 5 input1 input2 + echo -e "\ninput word1 [$input1]" + echo "input word2 [$input2]" +} + +# main menu entry point +echo "****Read command samples menu*****" +PS3="Your choice (1,2,3 etc.):" +options=("default_read" "custom_ifs_no_array" "prompt_read_password" \ + "array_read" "file_read" "command_pipe" "timeout_input_read" \ + "exactly_n_read" "quit") +select option in "${options[@]}" +do + case $option in + "default_read") + echo "Enter something separated by spaces" + default_read + ;; + "custom_ifs_no_array") + echo "Enter something separated by ;" + custom_ifs_no_array + ;; + "prompt_read_password") + echo "Enter an invisible password after the prompt" + prompt_read_password + ;; + "array_read") + echo "Enter something else or just return" + array_read + ;; + "file_read") + echo "Reading from one liner csv file" + file_read + ;; + "command_pipe") + echo "Listing files and access rights from /" + command_pipe + ;; + "timeout_input_read") + echo "Enter something in 5 seconds or less" + timeout_input_read + ;; + "exactly_n_read") + echo "Enter at least 11 characters or wait 5 seconds" + exactly_n_read + ;; + "quit") + break + ;; + *) echo "Invalid option";; + esac +done \ No newline at end of file diff --git a/linux-bash/text/README.md b/linux-bash/text/README.md index e0ee0c1600..20df2a33ec 100644 --- a/linux-bash/text/README.md +++ b/linux-bash/text/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: -- [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/remove-text-after-x-in-file) +- [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/tr-manipulate-strings) +- [Linux Commands for Appending Multiple Lines to a File](https://www.baeldung.com/linux/appending-multiple-lines-to-file2) diff --git a/logging-modules/flogger/pom.xml b/logging-modules/flogger/pom.xml index c27e2c8d7a..f553a4a961 100644 --- a/logging-modules/flogger/pom.xml +++ b/logging-modules/flogger/pom.xml @@ -15,26 +15,26 @@ com.google.flogger flogger - 0.4 + ${flogger.version} com.google.flogger flogger-system-backend - 0.4 + ${flogger.version} runtime com.google.flogger flogger-slf4j-backend - 0.4 + ${flogger.version} com.google.flogger flogger-log4j-backend - 0.4 + ${flogger.version} com.sun.jmx @@ -54,13 +54,18 @@ log4j log4j - 1.2.17 + ${log4j.version} log4j apache-log4j-extras - 1.2.17 + ${log4j.version} + + 0.4 + 1.2.17 + +
\ No newline at end of file diff --git a/logging-modules/log-mdc/README.md b/logging-modules/log-mdc/README.md index 3841224824..0d516619ef 100644 --- a/logging-modules/log-mdc/README.md +++ b/logging-modules/log-mdc/README.md @@ -1,8 +1,8 @@ ### Relevant Articles: - TBD -- [Improved Java Logging with Mapped Diagnostic Context (MDC)](http://www.baeldung.com/mdc-in-log4j-2-logback) -- [Java Logging with Nested Diagnostic Context (NDC)](http://www.baeldung.com/java-logging-ndc-log4j) -- [Drools Using Rules from Excel Files](http://www.baeldung.com/drools-excel) +- [Improved Java Logging with Mapped Diagnostic Context (MDC)](https://www.baeldung.com/mdc-in-log4j-2-logback) +- [Java Logging with Nested Diagnostic Context (NDC)](https://www.baeldung.com/java-logging-ndc-log4j) +- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel) ### References diff --git a/logging-modules/logback/README.md b/logging-modules/logback/README.md index 58dc8ce541..05a4ab9308 100644 --- a/logging-modules/logback/README.md +++ b/logging-modules/logback/README.md @@ -2,3 +2,4 @@ - [Get Log Output in JSON](https://www.baeldung.com/java-log-json-output) - [SLF4J Warning: Class Path Contains Multiple SLF4J Bindings](https://www.baeldung.com/slf4j-classpath-multiple-bindings) +- [Sending Emails with Logback](https://www.baeldung.com/logback-send-email) diff --git a/logging-modules/logback/pom.xml b/logging-modules/logback/pom.xml index 6ffc9e1235..ee430949df 100644 --- a/logging-modules/logback/pom.xml +++ b/logging-modules/logback/pom.xml @@ -50,12 +50,25 @@ + + javax.mail + mail + ${javax.mail.version} + + + javax.activation + activation + ${javax.activation.version} + runtime + 1.2.3 0.1.5 3.3.5 + 1.4.7 + 1.1.1
diff --git a/logging-modules/logback/src/main/resources/logback.xml b/logging-modules/logback/src/main/resources/logback.xml index 37ae2adbb0..76ddc2e3ee 100644 --- a/logging-modules/logback/src/main/resources/logback.xml +++ b/logging-modules/logback/src/main/resources/logback.xml @@ -10,9 +10,47 @@ + + OUR-SMTP-HOST-ADDRESS + + EMAIL-RECIPIENT-1 + EMAIL-RECIPIENT-2 + SENDER-EMAIL-ADDRESS + BAELDUNG: %logger{20} - %msg + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n + + + + + OUR-SMTP-HOST-ADDRESS + EMAIL-RECIPIENT + SENDER-EMAIL-ADDRESS + BAELDUNG: %logger{20} - %msg + + + + 5 + + + + + smtp.gmail.com + 587 + true + false + SENDER-EMAIL@gmail.com + GMAIL-ACCT-PASSWORD + EMAIL-RECIPIENT + SENDER-EMAIL@gmail.com + BAELDUNG: %logger{20} - %msg + + + + \ No newline at end of file diff --git a/lombok-custom/pom.xml b/lombok-custom/pom.xml index 1455a4f6c6..220367bfe9 100644 --- a/lombok-custom/pom.xml +++ b/lombok-custom/pom.xml @@ -36,12 +36,12 @@ - default-tools.jar + default-profile - - java.vendor - Oracle Corporation - + true + + ${java.home}/../lib/tools.jar + diff --git a/lombok/src/main/README.md b/lombok/src/main/README.md new file mode 100644 index 0000000000..4092d8ce99 --- /dev/null +++ b/lombok/src/main/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Guide to the Linux wc Command](https://www.baeldung.com/linux/wc-command) diff --git a/machine-learning/pom.xml b/machine-learning/pom.xml index 7bc0332012..99b7e33579 100644 --- a/machine-learning/pom.xml +++ b/machine-learning/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 machine-learning 1.0-SNAPSHOT @@ -13,14 +15,6 @@ 1.0.0-SNAPSHOT - - UTF-8 - 1.7 - 1.7 - 1.3.50 - 0.9.1 - - org.jetbrains.kotlin @@ -63,41 +57,41 @@ maven-clean-plugin - 3.1.0 + ${clean.plugin.version} maven-resources-plugin - 3.0.2 + ${resources.plugin.version} maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} maven-surefire-plugin - 2.22.1 + ${surefire.plugin.version} maven-jar-plugin - 3.0.2 + ${jar.plugin.version} maven-install-plugin - 2.5.2 + ${install.plugin.version} maven-deploy-plugin - 2.8.2 + ${deploy.plugin.version} maven-site-plugin - 3.7.1 + ${site.plugin.version} maven-project-info-reports-plugin - 3.0.0 + ${report.plugin.version} @@ -149,4 +143,21 @@ + + UTF-8 + 1.7 + 1.7 + 1.3.50 + 0.9.1 + 3.1.0 + 3.0.2 + 3.0.2 + 3.8.0 + 2.22.1 + 2.5.2 + 2.8.2 + 3.7.1 + 3.0.0 + + diff --git a/maven-all/compiler-plugin-java-9/README.md b/maven-all/compiler-plugin-java-9/README.md index d0b7b72acc..0e02d56946 100644 --- a/maven-all/compiler-plugin-java-9/README.md +++ b/maven-all/compiler-plugin-java-9/README.md @@ -1,3 +1,3 @@ ### Relevant Articles -- [Maven Compiler Plugin](http://www.baeldung.com/maven-compiler-plugin) \ No newline at end of file +- [Maven Compiler Plugin](https://www.baeldung.com/maven-compiler-plugin) diff --git a/maven-all/compiler-plugin-java-9/pom.xml b/maven-all/compiler-plugin-java-9/pom.xml index 1975e1f7cd..6baadb451c 100644 --- a/maven-all/compiler-plugin-java-9/pom.xml +++ b/maven-all/compiler-plugin-java-9/pom.xml @@ -12,13 +12,19 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 9 - 9 + ${source.version} + ${target.version} + + 3.8.0 + 9 + 9 + + \ No newline at end of file diff --git a/maven-all/maven-custom-plugin/README.md b/maven-all/maven-custom-plugin/README.md new file mode 100644 index 0000000000..55d147c337 --- /dev/null +++ b/maven-all/maven-custom-plugin/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [How to Create a Maven Plugin](https://www.baeldung.com/maven-plugin) diff --git a/maven-all/maven-custom-plugin/usage-example/pom.xml b/maven-all/maven-custom-plugin/usage-example/pom.xml index 542a02b3eb..ef6f08a3fb 100644 --- a/maven-all/maven-custom-plugin/usage-example/pom.xml +++ b/maven-all/maven-custom-plugin/usage-example/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 com.baeldung example @@ -12,12 +13,12 @@ org.apache.commons commons-lang3 - 3.9 + ${commons.lang3.version} junit junit - 4.12 + ${junit.version} test @@ -42,4 +43,9 @@ + + 3.9 + 4.12 + +
diff --git a/maven-all/maven-unused-dependencies/pom.xml b/maven-all/maven-unused-dependencies/pom.xml new file mode 100644 index 0000000000..825858e481 --- /dev/null +++ b/maven-all/maven-unused-dependencies/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + com.baeldung + maven-unused-dependencies + 0.0.1-SNAPSHOT + + + 3.2.2 + 1.7.25 + 3.1.2 + 3.1 + + + + + commons-collections + commons-collections + ${commons-collections.version} + + + org.slf4j + slf4j-api + ${slf4j-api.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + maven-dependency-plugin + ${maven-dependency-plugin.version} + + + + + \ No newline at end of file diff --git a/maven-all/maven-unused-dependencies/src/main/java/com/baeldung/mavendependencyplugin/UnusedDependenciesExample.java b/maven-all/maven-unused-dependencies/src/main/java/com/baeldung/mavendependencyplugin/UnusedDependenciesExample.java new file mode 100644 index 0000000000..c9390880ed --- /dev/null +++ b/maven-all/maven-unused-dependencies/src/main/java/com/baeldung/mavendependencyplugin/UnusedDependenciesExample.java @@ -0,0 +1,17 @@ +package com.baeldung.mavendependencyplugin; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class UnusedDependenciesExample { + + /** + * When the Maven dependency analyzer analyzes the code, it will see that the slf4j dependency is being used in this method. + * + * @return the slf4j {@link Logger}. + */ + public Logger getLogger() { + return LoggerFactory.getLogger(UnusedDependenciesExample.class); + } + +} diff --git a/maven-all/maven-war-plugin/pom.xml b/maven-all/maven-war-plugin/pom.xml index 233a9f3571..915be306ca 100644 --- a/maven-all/maven-war-plugin/pom.xml +++ b/maven-all/maven-war-plugin/pom.xml @@ -14,7 +14,7 @@ maven-war-plugin - 3.1.0 + ${war.plugin.version} false @@ -26,6 +26,7 @@ false + 3.1.0
\ No newline at end of file diff --git a/maven-all/maven/README.md b/maven-all/maven/README.md index ced4a52703..c5f46ca184 100644 --- a/maven-all/maven/README.md +++ b/maven-all/maven/README.md @@ -7,7 +7,6 @@ have their own dedicated modules. - [Guide to the Core Maven Plugins](https://www.baeldung.com/core-maven-plugins) - [Maven Resources Plugin](https://www.baeldung.com/maven-resources-plugin) -- [Maven Compiler Plugin](https://www.baeldung.com/maven-compiler-plugin) - [Quick Guide to the Maven Surefire Plugin](https://www.baeldung.com/maven-surefire-plugin) - [The Maven Failsafe Plugin](https://www.baeldung.com/maven-failsafe-plugin) - [The Maven Verifier Plugin](https://www.baeldung.com/maven-verifier-plugin) diff --git a/maven-all/maven/custom-rule/README.md b/maven-all/maven/custom-rule/README.md deleted file mode 100644 index 44d43050e7..0000000000 --- a/maven-all/maven/custom-rule/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin) diff --git a/maven-all/maven/custom-rule/src/main/java/com/baeldung/enforcer/MyCustomRule.java b/maven-all/maven/custom-rule/src/main/java/com/baeldung/enforcer/MyCustomRule.java index 9b72f40bf1..db636c2308 100644 --- a/maven-all/maven/custom-rule/src/main/java/com/baeldung/enforcer/MyCustomRule.java +++ b/maven-all/maven/custom-rule/src/main/java/com/baeldung/enforcer/MyCustomRule.java @@ -19,8 +19,8 @@ public class MyCustomRule implements EnforcerRule { String groupId = (String) enforcerRuleHelper.evaluate("${project.groupId}"); - if (groupId == null || !groupId.startsWith("org.baeldung")) { - throw new EnforcerRuleException("Project group id does not start with org.baeldung"); + if (groupId == null || !groupId.startsWith("com.baeldung")) { + throw new EnforcerRuleException("Project group id does not start with com.baeldung"); } } diff --git a/maven-all/maven/proxy/README.md b/maven-all/maven/proxy/README.md new file mode 100644 index 0000000000..9ae1fd6ad5 --- /dev/null +++ b/maven-all/maven/proxy/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Using Maven Behind a Proxy](https://www.baeldung.com/maven-behind-proxy) diff --git a/maven-all/pom.xml b/maven-all/pom.xml new file mode 100644 index 0000000000..3a79a2a686 --- /dev/null +++ b/maven-all/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + maven-all + 0.0.1-SNAPSHOT + maven-all + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + maven + maven-custom-plugin/counter-maven-plugin + maven-war-plugin + profiles + versions-maven-plugin + + + diff --git a/maven-all/profiles/pom.xml b/maven-all/profiles/pom.xml index 01b191c7d6..4ae6d1ee40 100644 --- a/maven-all/profiles/pom.xml +++ b/maven-all/profiles/pom.xml @@ -73,7 +73,7 @@ org.apache.maven.plugins maven-help-plugin - 3.2.0 + ${help.plugin.version} show-profiles @@ -87,4 +87,8 @@ + + 3.2.0 + +
\ No newline at end of file diff --git a/maven-all/versions-maven-plugin/original/README.md b/maven-all/versions-maven-plugin/original/README.md deleted file mode 100644 index 5652a9b7e4..0000000000 --- a/maven-all/versions-maven-plugin/original/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Use the Latest Version of a Dependency in Maven](https://www.baeldung.com/maven-dependency-latest-version) diff --git a/maven-all/versions-maven-plugin/original/pom.xml b/maven-all/versions-maven-plugin/original/pom.xml index c6c1657b25..54140aec9b 100644 --- a/maven-all/versions-maven-plugin/original/pom.xml +++ b/maven-all/versions-maven-plugin/original/pom.xml @@ -46,7 +46,7 @@ org.codehaus.mojo versions-maven-plugin - 2.7 + ${versions.plugin.version} org.apache.commons:commons-collections4 @@ -76,6 +76,7 @@ 4.0 3.0 1.9.1 + 2.7
\ No newline at end of file diff --git a/maven-all/versions-maven-plugin/pom.xml b/maven-all/versions-maven-plugin/pom.xml index 3ce25d16f9..9793f55b28 100644 --- a/maven-all/versions-maven-plugin/pom.xml +++ b/maven-all/versions-maven-plugin/pom.xml @@ -12,19 +12,19 @@ commons-io commons-io - 2.3 + ${commons.io.version} org.apache.commons commons-collections4 - 4.0 + ${commons.collections4.version} org.apache.commons commons-lang3 - 3.0 + ${commons.lang3.version} @@ -36,7 +36,7 @@ commons-beanutils commons-beanutils - 1.9.1 + ${commons.beanutils.version} @@ -45,7 +45,7 @@ org.codehaus.mojo versions-maven-plugin - 2.7 + ${versions.plugin.version} org.apache.commons:commons-collections4 @@ -71,6 +71,11 @@ 1.15 + 2.3 + 2.7 + 1.9.1 + 3.0 + 4.0
\ No newline at end of file diff --git a/maven-archetype/src/main/resources/archetype-resources/pom.xml b/maven-archetype/src/main/resources/archetype-resources/pom.xml index a5c813652d..fc568349bc 100644 --- a/maven-archetype/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetype/src/main/resources/archetype-resources/pom.xml @@ -1,21 +1,13 @@ - + 4.0.0 ${groupId} ${artifactId} ${version} war - - UTF-8 - 1.8 - 1.8 - false - ${liberty-plugin-version} - 9080 - 9443 - - ${artifactId} @@ -65,17 +57,29 @@ javax.enterprise cdi-api - 2.0 + ${cdi.api.version} provided javax.ws.rs javax.ws.rs-api - 2.1 + ${rsapi.api.version} provided + + UTF-8 + 1.8 + 1.8 + false + ${liberty-plugin-version} + 9080 + 9443 + 2.0 + 2.1 + + diff --git a/maven-java-11/README.md b/maven-java-11/README.md deleted file mode 100644 index fcb6ea3f06..0000000000 --- a/maven-java-11/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Maven and Java 11 - -This module contains articles about Maven with Java 11+. - -### Relevant Articles: - -- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms) diff --git a/maven-java-11/multimodule-maven-project/daomodule/pom.xml b/maven-java-11/multimodule-maven-project/daomodule/pom.xml deleted file mode 100644 index cbe0b4cb95..0000000000 --- a/maven-java-11/multimodule-maven-project/daomodule/pom.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - 4.0.0 - com.baeldung.daomodule - daomodule - 1.0 - daomodule - jar - - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - - - diff --git a/maven-java-11/multimodule-maven-project/daomodule/src/main/java/com/baeldung/dao/Dao.java b/maven-java-11/multimodule-maven-project/daomodule/src/main/java/com/baeldung/dao/Dao.java deleted file mode 100644 index f86ae8abb3..0000000000 --- a/maven-java-11/multimodule-maven-project/daomodule/src/main/java/com/baeldung/dao/Dao.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.dao; - -import java.util.List; -import java.util.Optional; - -public interface Dao { - - Optional findById(int id); - - List findAll(); - -} diff --git a/maven-java-11/multimodule-maven-project/daomodule/src/main/java/module-info.java b/maven-java-11/multimodule-maven-project/daomodule/src/main/java/module-info.java deleted file mode 100644 index 072d7ad007..0000000000 --- a/maven-java-11/multimodule-maven-project/daomodule/src/main/java/module-info.java +++ /dev/null @@ -1,3 +0,0 @@ -module com.baeldung.dao { - exports com.baeldung.dao; -} diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml b/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml deleted file mode 100644 index 228619ed74..0000000000 --- a/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - 4.0.0 - com.baeldung.entitymodule - entitymodule - 1.0 - entitymodule - jar - - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - - - - 11 - 11 - - - diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/com/baeldung/entity/User.java b/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/com/baeldung/entity/User.java deleted file mode 100644 index 22022a2e6d..0000000000 --- a/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/com/baeldung/entity/User.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.entity; - -public class User { - - private final String name; - - public User(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - @Override - public String toString() { - return "User{" + "name=" + name + '}'; - } -} diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/module-info.java b/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/module-info.java deleted file mode 100644 index 67a3097352..0000000000 --- a/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/module-info.java +++ /dev/null @@ -1,3 +0,0 @@ -module com.baeldung.entity { - exports com.baeldung.entity; -} diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml deleted file mode 100644 index 42b06bbebd..0000000000 --- a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - 4.0.0 - com.baeldung.mainappmodule - mainappmodule - 1.0 - mainappmodule - jar - - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - - - - - com.baeldung.entitymodule - entitymodule - 1.0 - - - com.baeldung.daomodule - daomodule - 1.0 - - - com.baeldung.userdaomodule - userdaomodule - 1.0 - - - - diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/com/baeldung/mainapp/Application.java b/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/com/baeldung/mainapp/Application.java deleted file mode 100644 index 0c0df7461b..0000000000 --- a/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/com/baeldung/mainapp/Application.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.mainapp; - -import com.baeldung.dao.Dao; -import com.baeldung.entity.User; -import com.baeldung.userdao.UserDao; -import java.util.HashMap; -import java.util.Map; - -public class Application { - - public static void main(String[] args) { - Map users = new HashMap<>(); - users.put(1, new User("Julie")); - users.put(2, new User("David")); - Dao userDao = new UserDao(users); - userDao.findAll().forEach(System.out::println); - } - -} diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/module-info.java b/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/module-info.java deleted file mode 100644 index c688fcf7de..0000000000 --- a/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/module-info.java +++ /dev/null @@ -1,6 +0,0 @@ -module com.baeldung.mainapp { - requires com.baeldung.entity; - requires com.baeldung.userdao; - requires com.baeldung.dao; - uses com.baeldung.dao.Dao; -} diff --git a/maven-java-11/multimodule-maven-project/pom.xml b/maven-java-11/multimodule-maven-project/pom.xml deleted file mode 100644 index a79dff93d3..0000000000 --- a/maven-java-11/multimodule-maven-project/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - 4.0.0 - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - multimodule-maven-project - pom - - - com.baeldung.maven-java-11 - maven-java-11 - 1.0 - - - - entitymodule - daomodule - userdaomodule - mainappmodule - - - - - - junit - junit - 4.12 - test - - - org.assertj - assertj-core - 3.12.2 - test - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - 11 - 11 - - - - - - - - UTF-8 - - - diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml deleted file mode 100644 index 3eb5897f8b..0000000000 --- a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - 4.0.0 - com.baeldung.userdaomodule - userdaomodule - 1.0 - userdaomodule - jar - - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - - - - - com.baeldung.entitymodule - entitymodule - 1.0 - - - com.baeldung.daomodule - daomodule - 1.0 - - - junit - junit - test - - - - diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/com/baeldung/userdao/UserDao.java b/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/com/baeldung/userdao/UserDao.java deleted file mode 100644 index 1f1ea38a60..0000000000 --- a/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/com/baeldung/userdao/UserDao.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.userdao; - -import com.baeldung.dao.Dao; -import com.baeldung.entity.User; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class UserDao implements Dao { - - private final Map users; - - public UserDao() { - users = new HashMap<>(); - } - - public UserDao(Map users) { - this.users = users; - } - - @Override - public List findAll() { - return new ArrayList<>(users.values()); - } - - @Override - public Optional findById(int id) { - return Optional.ofNullable(users.get(id)); - } -} \ No newline at end of file diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/module-info.java b/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/module-info.java deleted file mode 100644 index f1cb217e23..0000000000 --- a/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/module-info.java +++ /dev/null @@ -1,6 +0,0 @@ -module com.baeldung.userdao { - requires com.baeldung.entity; - requires com.baeldung.dao; - provides com.baeldung.dao.Dao with com.baeldung.userdao.UserDao; - exports com.baeldung.userdao; -} diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/src/test/java/com/baeldung/userdao/test/UserDaoUnitTest.java b/maven-java-11/multimodule-maven-project/userdaomodule/src/test/java/com/baeldung/userdao/test/UserDaoUnitTest.java deleted file mode 100644 index 191d17ff32..0000000000 --- a/maven-java-11/multimodule-maven-project/userdaomodule/src/test/java/com/baeldung/userdao/test/UserDaoUnitTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.userdao.test; - -import com.baeldung.dao.Dao; -import com.baeldung.entity.User; -import com.baeldung.userdao.UserDao; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.*; -import org.junit.Before; -import org.junit.Test; - -public class UserDaoUnitTest { - - private Dao userDao; - - @Before - public void setUpUserDaoInstance() { - Map users = new HashMap<>(); - users.put(1, new User("Julie")); - users.put(2, new User("David")); - userDao = new UserDao(users); - } - - @Test - public void givenUserDaoIntance_whenCalledFindById_thenCorrect() { - assertThat(userDao.findById(1), isA(Optional.class)); - } - - @Test - public void givenUserDaoIntance_whenCalledFindAll_thenCorrect() { - assertThat(userDao.findAll(), isA(List.class)); - } -} diff --git a/maven-java-11/pom.xml b/maven-java-11/pom.xml deleted file mode 100644 index 10e80365c8..0000000000 --- a/maven-java-11/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - 4.0.0 - com.baeldung.maven-java-11 - maven-java-11 - 1.0 - maven-java-11 - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - multimodule-maven-project - - - - UTF-8 - 11 - 11 - - - diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-polyglot/maven-polyglot-json-extension/pom.xml index 0043bae151..15166046c1 100644 --- a/maven-polyglot/maven-polyglot-json-extension/pom.xml +++ b/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -34,7 +34,7 @@ org.codehaus.plexus plexus-component-metadata - 1.7.1 + ${plexus.component.version} @@ -48,6 +48,7 @@ 3.5.4 + 1.7.1 \ No newline at end of file diff --git a/maven-polyglot/pom.xml b/maven-polyglot/pom.xml new file mode 100644 index 0000000000..eb4e629a96 --- /dev/null +++ b/maven-polyglot/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + maven-polyglot + 0.0.1-SNAPSHOT + maven-polyglot + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + maven-polyglot-json-extension + + + + diff --git a/mesos-marathon/README.md b/mesos-marathon/README.md index 65b2361698..8e5b8e4974 100644 --- a/mesos-marathon/README.md +++ b/mesos-marathon/README.md @@ -6,4 +6,4 @@ This module contains articles about Marathon and Mesos. - [Simple Jenkins Pipeline with Marathon and Mesos](https://www.baeldung.com/jenkins-pipeline-with-marathon-mesos) - To run the pipeline, please modify the dockerise.sh file with your own useranema and password for docker login. + To run the pipeline, please modify the dockerise.sh file with your own username and password for docker login. diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml index 4fb819c434..42798bb209 100644 --- a/mesos-marathon/pom.xml +++ b/mesos-marathon/pom.xml @@ -7,9 +7,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java b/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java index 85331516f9..dfe944a316 100644 --- a/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java +++ b/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java @@ -3,8 +3,8 @@ package com.baeldung; 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.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; diff --git a/micronaut/pom.xml b/micronaut/pom.xml index 13639c11ff..2cb05cc1b9 100644 --- a/micronaut/pom.xml +++ b/micronaut/pom.xml @@ -49,7 +49,7 @@ javax.annotation javax.annotation-api - 1.3.2 + ${annotation.api.version} compile @@ -60,19 +60,19 @@ ch.qos.logback logback-classic - 1.2.3 + ${lombok.version} runtime junit junit - 4.12 + ${junit.version} test io.projectreactor reactor-core - 3.1.6.RELEASE + ${reactor.version} @@ -81,7 +81,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.1.0 + ${shade.plugin.version} package @@ -102,7 +102,7 @@ org.codehaus.mojo exec-maven-plugin - 1.6.0 + ${exec.plugin.version} java @@ -118,7 +118,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + ${compiler.plugin.version} ${jdk.version} ${jdk.version} @@ -142,6 +142,13 @@ com.baeldung.micronaut.helloworld.server.ServerApplication 1.0.0.RC2 1.8 + 1.3.2 + 1.2.3 + 4.12 + 3.1.6.RELEASE + 3.7.0 + 1.6.0 + 3.1.0
diff --git a/micronaut/src/main/resources/application.yml b/micronaut/src/main/resources/application.yml index 4119026dd6..32daacd4aa 100644 --- a/micronaut/src/main/resources/application.yml +++ b/micronaut/src/main/resources/application.yml @@ -2,4 +2,4 @@ micronaut: application: name: hello-world-server server: - port: 9080 \ No newline at end of file + port: ${random.port} \ No newline at end of file diff --git a/muleesb/pom.xml b/muleesb/pom.xml index c8468c1e00..e7c7e50cbe 100644 --- a/muleesb/pom.xml +++ b/muleesb/pom.xml @@ -83,7 +83,7 @@ com.mulesoft.munit mule-munit-support - ${mule.munit.support.version} + ${mule.version} test @@ -106,18 +106,19 @@ - org.mule.tools - muleesb-maven-plugin - ${muleesb-maven-plugin.version} + org.mule.tools.maven + mule-maven-plugin + 2.2.1 + standalone ${mule.version} - /home/abir/AnypointStudio/workspace/variablescopetest deploy + deploy - start + deploy @@ -210,11 +211,9 @@ - 3.8.1 + 3.9.0 1.2 1.3.6 - 3.9.0 - 1.0 1.7 diff --git a/mybatis/src/main/java/com/baeldung/mybatis/mapper/AddressMapper.java b/mybatis/src/main/java/com/baeldung/mybatis/mapper/AddressMapper.java index e96a4837db..c79ef667bd 100644 --- a/mybatis/src/main/java/com/baeldung/mybatis/mapper/AddressMapper.java +++ b/mybatis/src/main/java/com/baeldung/mybatis/mapper/AddressMapper.java @@ -14,8 +14,8 @@ public interface AddressMapper { @Results(value = { @Result(property = "addressId", column = "addressId"), @Result(property = "streetAddress", column = "streetAddress"), @Result(property = "person", column = "personId", javaType = Person.class, one = @One(select = "getPerson")) }) - Address getAddresses(Integer addressID); + Address getAddresses(Integer addressId); @Select("SELECT personId FROM address WHERE addressId = #{addressId})") - Person getPerson(Integer personId); + Person getPerson(Integer addressId); } diff --git a/netflix-modules/README.md b/netflix-modules/README.md new file mode 100644 index 0000000000..7f7a9656fb --- /dev/null +++ b/netflix-modules/README.md @@ -0,0 +1,7 @@ +## Netflix Modules + +This module contains articles about Netflix. + +### Relevant articles + +- [Introduction to Netflix Genie](https://www.baeldung.com/netflix-genie-intro) diff --git a/netflix-modules/genie/pom.xml b/netflix-modules/genie/pom.xml new file mode 100644 index 0000000000..2c7c04b26b --- /dev/null +++ b/netflix-modules/genie/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + genie + Genie + jar + Sample project for Netflix Genie + + + com.baeldung + netflix-modules + 1.0.0-SNAPSHOT + + + \ No newline at end of file diff --git a/netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/docker-compose.yml b/netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/docker-compose.yml similarity index 100% rename from netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/docker-compose.yml rename to netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/docker-compose.yml diff --git a/netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/init_demo.py b/netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/init_demo.py similarity index 100% rename from netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/init_demo.py rename to netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/init_demo.py diff --git a/netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/run_spark_submit_job.py b/netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/run_spark_submit_job.py similarity index 100% rename from netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/run_spark_submit_job.py rename to netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/run_spark_submit_job.py diff --git a/netflix-modules/pom.xml b/netflix-modules/pom.xml new file mode 100644 index 0000000000..9ed22498d8 --- /dev/null +++ b/netflix-modules/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + netflix-modules + Netflix Modules + pom + Module for Netflix projects + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + genie + + + \ No newline at end of file diff --git a/netflix/README.md b/netflix/README.md deleted file mode 100644 index 0af07d37a8..0000000000 --- a/netflix/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Netflix - -This module contains articles about Netflix. - -### Relevant articles - -- [Introduction to Netflix Genie](https://github.com/eugenp/tutorials/tree/master/netflix/genie) diff --git a/netflix/genie/pom.xml b/netflix/genie/pom.xml deleted file mode 100644 index 2288c5338a..0000000000 --- a/netflix/genie/pom.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - 4.0.0 - genie - 1.0.0-SNAPSHOT - Genie - jar - Sample project for Netflix Genie - - - com.baeldung - netflix - 1.0.0-SNAPSHOT - - - \ No newline at end of file diff --git a/netflix/pom.xml b/netflix/pom.xml deleted file mode 100644 index 6cf81cd7ab..0000000000 --- a/netflix/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - netflix - 1.0.0-SNAPSHOT - Netflix - pom - Module for Netflix projects - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - genie - - - \ No newline at end of file diff --git a/netty/README.md b/netty/README.md new file mode 100644 index 0000000000..30c63cd5a8 --- /dev/null +++ b/netty/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [HTTP/2 in Netty](https://www.baeldung.com/netty-http2) diff --git a/netty/pom.xml b/netty/pom.xml new file mode 100644 index 0000000000..1a33eef92e --- /dev/null +++ b/netty/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + netty + 0.0.1-SNAPSHOT + netty + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + io.netty + netty-all + ${netty.version} + + + + org.conscrypt + conscrypt-openjdk-uber + 2.4.0 + + + + + + 4.1.48.Final + + + \ No newline at end of file diff --git a/netty/src/main/java/com/baeldung/netty/http2/Http2Util.java b/netty/src/main/java/com/baeldung/netty/http2/Http2Util.java new file mode 100644 index 0000000000..62b6d4c4ed --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/Http2Util.java @@ -0,0 +1,135 @@ +package com.baeldung.netty.http2; + +import static io.netty.handler.logging.LogLevel.INFO; + +import java.security.cert.CertificateException; + +import javax.net.ssl.SSLException; + +import com.baeldung.netty.http2.client.Http2ClientResponseHandler; +import com.baeldung.netty.http2.client.Http2SettingsHandler; +import com.baeldung.netty.http2.server.Http2ServerResponseHandler; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPipeline; +import io.netty.handler.codec.http.DefaultFullHttpRequest; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpHeaderValues; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpScheme; +import io.netty.handler.codec.http.HttpVersion; +import io.netty.handler.codec.http2.DefaultHttp2Connection; +import io.netty.handler.codec.http2.DelegatingDecompressorFrameListener; +import io.netty.handler.codec.http2.Http2Connection; +import io.netty.handler.codec.http2.Http2FrameCodecBuilder; +import io.netty.handler.codec.http2.Http2FrameLogger; +import io.netty.handler.codec.http2.Http2SecurityUtil; +import io.netty.handler.codec.http2.HttpConversionUtil; +import io.netty.handler.codec.http2.HttpToHttp2ConnectionHandler; +import io.netty.handler.codec.http2.HttpToHttp2ConnectionHandlerBuilder; +import io.netty.handler.codec.http2.InboundHttp2ToHttpAdapterBuilder; +import io.netty.handler.ssl.ApplicationProtocolConfig; +import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol; +import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior; +import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior; +import io.netty.handler.ssl.ApplicationProtocolNames; +import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.SslProvider; +import io.netty.handler.ssl.SupportedCipherSuiteFilter; +import io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import io.netty.handler.ssl.util.SelfSignedCertificate; + +public class Http2Util { + public static SslContext createSSLContext(boolean isServer) throws SSLException, CertificateException { + + SslContext sslCtx; + + SelfSignedCertificate ssc = new SelfSignedCertificate(); + + if (isServer) { + sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) + .sslProvider(SslProvider.JDK) + .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) + .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, + SelectorFailureBehavior.NO_ADVERTISE, + SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) + .build(); + } else { + sslCtx = SslContextBuilder.forClient() + .sslProvider(SslProvider.JDK) + .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, + SelectorFailureBehavior.NO_ADVERTISE, + SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2)) + .build(); + } + return sslCtx; + + } + + public static ApplicationProtocolNegotiationHandler getServerAPNHandler() { + ApplicationProtocolNegotiationHandler serverAPNHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) { + + @Override + protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { + if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { + ctx.pipeline() + .addLast(Http2FrameCodecBuilder.forServer() + .build(), new Http2ServerResponseHandler()); + return; + } + throw new IllegalStateException("Protocol: " + protocol + " not supported"); + } + }; + return serverAPNHandler; + + } + + public static ApplicationProtocolNegotiationHandler getClientAPNHandler(int maxContentLength, Http2SettingsHandler settingsHandler, Http2ClientResponseHandler responseHandler) { + final Http2FrameLogger logger = new Http2FrameLogger(INFO, Http2Util.class); + final Http2Connection connection = new DefaultHttp2Connection(false); + + HttpToHttp2ConnectionHandler connectionHandler = new HttpToHttp2ConnectionHandlerBuilder() + .frameListener(new DelegatingDecompressorFrameListener(connection, new InboundHttp2ToHttpAdapterBuilder(connection).maxContentLength(maxContentLength) + .propagateSettings(true) + .build())) + .frameLogger(logger) + .connection(connection) + .build(); + + ApplicationProtocolNegotiationHandler clientAPNHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) { + @Override + protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { + if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { + ChannelPipeline p = ctx.pipeline(); + p.addLast(connectionHandler); + p.addLast(settingsHandler, responseHandler); + return; + } + ctx.close(); + throw new IllegalStateException("Protocol: " + protocol + " not supported"); + } + }; + + return clientAPNHandler; + + } + + public static FullHttpRequest createGetRequest(String host, int port) { + FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.valueOf("HTTP/2.0"), HttpMethod.GET, "/", Unpooled.EMPTY_BUFFER); + request.headers() + .add(HttpHeaderNames.HOST, new String(host + ":" + port)); + request.headers() + .add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), HttpScheme.HTTPS); + request.headers() + .add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); + request.headers() + .add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); + return request; + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientInitializer.java b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientInitializer.java new file mode 100644 index 0000000000..d50240fcb2 --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientInitializer.java @@ -0,0 +1,46 @@ +package com.baeldung.netty.http2.client; + +import com.baeldung.netty.http2.Http2Util; + +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.socket.SocketChannel; +import io.netty.handler.ssl.SslContext; + +public class Http2ClientInitializer extends ChannelInitializer { + + private final SslContext sslCtx; + private final int maxContentLength; + private Http2SettingsHandler settingsHandler; + private Http2ClientResponseHandler responseHandler; + private String host; + private int port; + + public Http2ClientInitializer(SslContext sslCtx, int maxContentLength, String host, int port) { + this.sslCtx = sslCtx; + this.maxContentLength = maxContentLength; + this.host = host; + this.port = port; + } + + @Override + public void initChannel(SocketChannel ch) throws Exception { + + settingsHandler = new Http2SettingsHandler(ch.newPromise()); + responseHandler = new Http2ClientResponseHandler(); + + if (sslCtx != null) { + ChannelPipeline pipeline = ch.pipeline(); + pipeline.addLast(sslCtx.newHandler(ch.alloc(), host, port)); + pipeline.addLast(Http2Util.getClientAPNHandler(maxContentLength, settingsHandler, responseHandler)); + } + } + + public Http2SettingsHandler getSettingsHandler() { + return settingsHandler; + } + + public Http2ClientResponseHandler getResponseHandler() { + return responseHandler; + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientResponseHandler.java b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientResponseHandler.java new file mode 100644 index 0000000000..4e17155bbc --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientResponseHandler.java @@ -0,0 +1,128 @@ +package com.baeldung.netty.http2.client; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http.FullHttpResponse; +import io.netty.handler.codec.http2.HttpConversionUtil; +import io.netty.util.CharsetUtil; + +public class Http2ClientResponseHandler extends SimpleChannelInboundHandler { + + private final Logger logger = LoggerFactory.getLogger(Http2ClientResponseHandler.class); + private final Map streamidMap; + + public Http2ClientResponseHandler() { + streamidMap = new HashMap(); + } + + public MapValues put(int streamId, ChannelFuture writeFuture, ChannelPromise promise) { + return streamidMap.put(streamId, new MapValues(writeFuture, promise)); + } + + public String awaitResponses(long timeout, TimeUnit unit) { + + Iterator> itr = streamidMap.entrySet() + .iterator(); + + String response = null; + + while (itr.hasNext()) { + Entry entry = itr.next(); + ChannelFuture writeFuture = entry.getValue() + .getWriteFuture(); + + if (!writeFuture.awaitUninterruptibly(timeout, unit)) { + throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey()); + } + if (!writeFuture.isSuccess()) { + throw new RuntimeException(writeFuture.cause()); + } + ChannelPromise promise = entry.getValue() + .getPromise(); + + if (!promise.awaitUninterruptibly(timeout, unit)) { + throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey()); + } + if (!promise.isSuccess()) { + throw new RuntimeException(promise.cause()); + } + logger.info("---Stream id: " + entry.getKey() + " received---"); + response = entry.getValue().getResponse(); + + itr.remove(); + } + + return response; + + } + + @Override + protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { + Integer streamId = msg.headers() + .getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); + if (streamId == null) { + logger.error("HttpResponseHandler unexpected message received: " + msg); + return; + } + + MapValues value = streamidMap.get(streamId); + + if (value == null) { + logger.error("Message received for unknown stream id " + streamId); + ctx.close(); + } else { + ByteBuf content = msg.content(); + if (content.isReadable()) { + int contentLength = content.readableBytes(); + byte[] arr = new byte[contentLength]; + content.readBytes(arr); + String response = new String(arr, 0, contentLength, CharsetUtil.UTF_8); + logger.info("Response from Server: "+ (response)); + value.setResponse(response); + } + + value.getPromise() + .setSuccess(); + } + } + + public static class MapValues { + ChannelFuture writeFuture; + ChannelPromise promise; + String response; + + public String getResponse() { + return response; + } + + public void setResponse(String response) { + this.response = response; + } + + public MapValues(ChannelFuture writeFuture2, ChannelPromise promise2) { + this.writeFuture = writeFuture2; + this.promise = promise2; + } + + public ChannelFuture getWriteFuture() { + return writeFuture; + } + + public ChannelPromise getPromise() { + return promise; + } + + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/client/Http2SettingsHandler.java b/netty/src/main/java/com/baeldung/netty/http2/client/Http2SettingsHandler.java new file mode 100644 index 0000000000..93841187c7 --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/client/Http2SettingsHandler.java @@ -0,0 +1,30 @@ +package com.baeldung.netty.http2.client; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http2.Http2Settings; + +import java.util.concurrent.TimeUnit; + +public class Http2SettingsHandler extends SimpleChannelInboundHandler { + private final ChannelPromise promise; + + public Http2SettingsHandler(ChannelPromise promise) { + this.promise = promise; + } + + public void awaitSettings(long timeout, TimeUnit unit) throws Exception { + if (!promise.awaitUninterruptibly(timeout, unit)) { + throw new IllegalStateException("Timed out waiting for settings"); + } + } + + @Override + protected void channelRead0(ChannelHandlerContext ctx, Http2Settings msg) throws Exception { + promise.setSuccess(); + + ctx.pipeline() + .remove(this); + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/server/Http2Server.java b/netty/src/main/java/com/baeldung/netty/http2/server/Http2Server.java new file mode 100644 index 0000000000..a8e9e59953 --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/server/Http2Server.java @@ -0,0 +1,59 @@ +package com.baeldung.netty.http2.server; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.netty.http2.Http2Util; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; +import io.netty.handler.ssl.SslContext; + +public final class Http2Server { + + private static final int PORT = 8443; + private static final Logger logger = LoggerFactory.getLogger(Http2Server.class); + + public static void main(String[] args) throws Exception { + SslContext sslCtx = Http2Util.createSSLContext(true); + + EventLoopGroup group = new NioEventLoopGroup(); + try { + ServerBootstrap b = new ServerBootstrap(); + b.option(ChannelOption.SO_BACKLOG, 1024); + b.group(group) + .channel(NioServerSocketChannel.class) + .handler(new LoggingHandler(LogLevel.INFO)) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) throws Exception { + if (sslCtx != null) { + ch.pipeline() + .addLast(sslCtx.newHandler(ch.alloc()), Http2Util.getServerAPNHandler()); + } + } + + }); + + Channel ch = b.bind(PORT) + .sync() + .channel(); + + logger.info("HTTP/2 Server is listening on https://127.0.0.1:" + PORT + '/'); + + ch.closeFuture() + .sync(); + } finally { + group.shutdownGracefully(); + } + } + +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/server/Http2ServerResponseHandler.java b/netty/src/main/java/com/baeldung/netty/http2/server/Http2ServerResponseHandler.java new file mode 100644 index 0000000000..24c66f15bb --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/server/Http2ServerResponseHandler.java @@ -0,0 +1,52 @@ +package com.baeldung.netty.http2.server; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http2.DefaultHttp2DataFrame; +import io.netty.handler.codec.http2.DefaultHttp2Headers; +import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; +import io.netty.handler.codec.http2.Http2Headers; +import io.netty.handler.codec.http2.Http2HeadersFrame; +import io.netty.util.CharsetUtil; + +@Sharable +public class Http2ServerResponseHandler extends ChannelDuplexHandler { + + static final ByteBuf RESPONSE_BYTES = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8)); + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + super.exceptionCaught(ctx, cause); + cause.printStackTrace(); + ctx.close(); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof Http2HeadersFrame) { + Http2HeadersFrame msgHeader = (Http2HeadersFrame) msg; + if (msgHeader.isEndStream()) { + ByteBuf content = ctx.alloc() + .buffer(); + content.writeBytes(RESPONSE_BYTES.duplicate()); + + Http2Headers headers = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText()); + ctx.write(new DefaultHttp2HeadersFrame(headers).stream(msgHeader.stream())); + ctx.write(new DefaultHttp2DataFrame(content, true).stream(msgHeader.stream())); + } + + } else { + super.channelRead(ctx, msg); + } + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + +} diff --git a/java-math/src/main/resources/logback.xml b/netty/src/main/resources/logback.xml similarity index 100% rename from java-math/src/main/resources/logback.xml rename to netty/src/main/resources/logback.xml diff --git a/netty/src/test/java/com/baeldung/netty/Http2ClientLiveTest.java b/netty/src/test/java/com/baeldung/netty/Http2ClientLiveTest.java new file mode 100644 index 0000000000..6b9a53a1b3 --- /dev/null +++ b/netty/src/test/java/com/baeldung/netty/Http2ClientLiveTest.java @@ -0,0 +1,91 @@ +package com.baeldung.netty; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.netty.http2.Http2Util; +import com.baeldung.netty.http2.client.Http2ClientInitializer; +import com.baeldung.netty.http2.client.Http2ClientResponseHandler; +import com.baeldung.netty.http2.client.Http2SettingsHandler; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelOption; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.ssl.SslContext; + +//Ensure the server class - Http2Server.java is already started before running this test +public class Http2ClientLiveTest { + + private static final Logger logger = LoggerFactory.getLogger(Http2ClientLiveTest.class); + + private static final String HOST = "127.0.0.1"; + private static final int PORT = 8443; + private SslContext sslCtx; + private Channel channel; + + @Before + public void setup() throws Exception { + sslCtx = Http2Util.createSSLContext(false); + } + + @Test + public void whenRequestSent_thenHelloWorldReceived() throws Exception { + + EventLoopGroup workerGroup = new NioEventLoopGroup(); + Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE, HOST, PORT); + + try { + Bootstrap b = new Bootstrap(); + b.group(workerGroup); + b.channel(NioSocketChannel.class); + b.option(ChannelOption.SO_KEEPALIVE, true); + b.remoteAddress(HOST, PORT); + b.handler(initializer); + + channel = b.connect() + .syncUninterruptibly() + .channel(); + + logger.info("Connected to [" + HOST + ':' + PORT + ']'); + + Http2SettingsHandler http2SettingsHandler = initializer.getSettingsHandler(); + http2SettingsHandler.awaitSettings(60, TimeUnit.SECONDS); + + logger.info("Sending request(s)..."); + + FullHttpRequest request = Http2Util.createGetRequest(HOST, PORT); + + Http2ClientResponseHandler responseHandler = initializer.getResponseHandler(); + int streamId = 3; + + responseHandler.put(streamId, channel.write(request), channel.newPromise()); + channel.flush(); + String response = responseHandler.awaitResponses(60, TimeUnit.SECONDS); + + assertEquals("Hello World", response); + + logger.info("Finished HTTP/2 request(s)"); + + } finally { + workerGroup.shutdownGracefully(); + } + + } + + @After + public void cleanup() { + channel.close() + .syncUninterruptibly(); + } +} diff --git a/ninja/README.md b/ninja/README.md new file mode 100644 index 0000000000..554d088c1b --- /dev/null +++ b/ninja/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Introduction to Ninja Framework](https://www.baeldung.com/ninja-framework-intro) diff --git a/ninja/pom.xml b/ninja/pom.xml new file mode 100644 index 0000000000..9b80dc26c8 --- /dev/null +++ b/ninja/pom.xml @@ -0,0 +1,194 @@ + + + 4.0.0 + + ninja + jar + com.baeldung + 1.0.0 + + http://www.ninjaframework.org + + + + org.webjars + bootstrap + ${bootstrap.version} + + + org.webjars + jquery + ${jquery.version} + + + com.h2database + h2 + ${h2.version} + + + org.ninjaframework + ninja-standalone + ${ninja.version} + + + org.ninjaframework + ninja-test-utilities + ${ninja.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${compiler.plugin.version} + + ${source.version} + ${target.version} + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${enforcer.plugin.version} + + + enforce-banned-dependencies + + enforce + + + + + + commons-logging + + + + true + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.version} + + + / + + stop + 8889 + 1 + automatic + + + target/classes + + **/* + + + **/*.ftl.html + assets/** + + + + + + ninja.mode + dev + + + + + + + + + org.ninjaframework + ninja-maven-plugin + ${ninja.version} + + + org.apache.maven.plugins + maven-deploy-plugin + ${deploy.plugin.version} + + true + + + + org.apache.maven.plugins + maven-shade-plugin + ${shade.plugin.version} + + true + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + package + + shade + + + + + + ninja.standalone.NinjaJetty + + + + + + + + + + src/main/java + + **/* + + + **/*.java + + + + src/main/resources + + **/* + + + + + + + 6.5.0 + 9.4.18.v20190429 + 3.3.4 + 2.1.3 + 1.4.186 + 3.2 + 1.8 + 1.8 + 1.3.1 + 2.8.2 + 2.2 + + + \ No newline at end of file diff --git a/ninja/src/main/java/META-INF/persistence.xml b/ninja/src/main/java/META-INF/persistence.xml new file mode 100644 index 0000000000..e57cd5ecc0 --- /dev/null +++ b/ninja/src/main/java/META-INF/persistence.xml @@ -0,0 +1,29 @@ + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ninja/src/main/java/assets/css/custom.css b/ninja/src/main/java/assets/css/custom.css new file mode 100644 index 0000000000..41d249d3cb --- /dev/null +++ b/ninja/src/main/java/assets/css/custom.css @@ -0,0 +1,3 @@ +/* Add additional stylesheets below +-------------------------------------------------- */ + diff --git a/ninja/src/main/java/conf/Filters.java b/ninja/src/main/java/conf/Filters.java new file mode 100644 index 0000000000..b201780fa1 --- /dev/null +++ b/ninja/src/main/java/conf/Filters.java @@ -0,0 +1,13 @@ +package conf; + +import java.util.List; +import ninja.Filter; + +public class Filters implements ninja.application.ApplicationFilters { + + @Override + public void addFilters(List> filters) { + // Add your application - wide filters here + // filters.add(MyFilter.class); + } +} diff --git a/ninja/src/main/java/conf/Module.java b/ninja/src/main/java/conf/Module.java new file mode 100644 index 0000000000..f7c03a4b26 --- /dev/null +++ b/ninja/src/main/java/conf/Module.java @@ -0,0 +1,18 @@ +package conf; + +import com.google.inject.AbstractModule; +import com.google.inject.Singleton; + +import services.UserService; +import services.UserServiceImpl; + +@Singleton +public class Module extends AbstractModule { + + protected void configure() { + + bind(UserService.class).to(UserServiceImpl.class); + + } + +} diff --git a/ninja/src/main/java/conf/Routes.java b/ninja/src/main/java/conf/Routes.java new file mode 100644 index 0000000000..a1727d55b0 --- /dev/null +++ b/ninja/src/main/java/conf/Routes.java @@ -0,0 +1,32 @@ +package conf; + +import ninja.AssetsController; +import ninja.Router; +import ninja.application.ApplicationRoutes; +import controllers.ApplicationController; + +public class Routes implements ApplicationRoutes { + + @Override + public void init(Router router) { + + router.GET().route("/index").with(ApplicationController::index); + router.GET().route("/home").with(ApplicationController::home); + router.GET().route("/hello").with(ApplicationController::helloWorld); + router.GET().route("/userJson").with(ApplicationController::userJson); + router.GET().route("/createUser").with(ApplicationController::createUser); + router.GET().route("/flash").with(ApplicationController::showFlashMsg); + + router.GET().route("/users").with(ApplicationController::fetchUsers); + router.POST().route("/users").with(ApplicationController::insertUser); + + //Assets + router.GET().route("/assets/webjars/{fileName: .*}").with(AssetsController::serveWebJars); + router.GET().route("/assets/{fileName: .*}").with(AssetsController::serveStatic); + + //Index + router.GET().route("/.*").with(ApplicationController::index); + + } + +} diff --git a/ninja/src/main/java/conf/application.conf b/ninja/src/main/java/conf/application.conf new file mode 100644 index 0000000000..0ae4c7ec40 --- /dev/null +++ b/ninja/src/main/java/conf/application.conf @@ -0,0 +1,21 @@ +application.name=baeldung ninja dev application +%test.application.name=baeldung ninja test application +%prod.application.name=baeldung ninja application + +application.cookie.prefix=NINJA + +application.languages=fr,en + +application.session.expire_time_in_seconds=3600 +application.session.send_only_if_changed=true +application.session.transferred_over_https_only=false + +ninja.port=8000 +ninja.ssl.port=8001 +application.secret = fxSjSL9Q017BSL7gBnkyo2Prln7uXaXIT35gotXRIED8c46OSa8s4QdoIQdTsEtj + +# h2 jpa configuration +ninja.jpa.persistence_unit_name=dev_unit +db.connection.url=jdbc:h2:./devDb +db.connection.username=sa +db.connection.password= diff --git a/ninja/src/main/java/conf/messages.properties b/ninja/src/main/java/conf/messages.properties new file mode 100644 index 0000000000..3bddfcd8c7 --- /dev/null +++ b/ninja/src/main/java/conf/messages.properties @@ -0,0 +1,2 @@ +header.home=Home! +helloMsg=Hello, welcome to Ninja Framework! \ No newline at end of file diff --git a/ninja/src/main/java/conf/messages_fr.properties b/ninja/src/main/java/conf/messages_fr.properties new file mode 100644 index 0000000000..89264e0cb9 --- /dev/null +++ b/ninja/src/main/java/conf/messages_fr.properties @@ -0,0 +1,2 @@ +header.home=Accueil! +helloMsg=Bonjour, bienvenue dans Ninja Framework! \ No newline at end of file diff --git a/ninja/src/main/java/controllers/ApplicationController.java b/ninja/src/main/java/controllers/ApplicationController.java new file mode 100644 index 0000000000..38dd598694 --- /dev/null +++ b/ninja/src/main/java/controllers/ApplicationController.java @@ -0,0 +1,102 @@ +package controllers; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import javax.inject.Inject; +import javax.persistence.EntityManager; +import javax.persistence.Query; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.google.inject.Provider; +import com.google.inject.Singleton; +import com.google.inject.persist.Transactional; + +import models.User; +import ninja.Context; +import ninja.Result; +import ninja.Results; +import ninja.i18n.Lang; +import ninja.i18n.Messages; +import ninja.jpa.UnitOfWork; +import ninja.session.FlashScope; +import ninja.validation.JSR303Validation; +import ninja.validation.Validation; +import services.UserService; + +@Singleton +public class ApplicationController { + + @Inject + Lang lang; + + @Inject + Messages msg; + + private static Log logger = LogFactory.getLog(ApplicationController.class); + + @Inject + Provider entityManagerProvider; + + @Inject + UserService userService; + + public Result index() { + return Results.html(); + } + + public Result userJson() { + HashMap userMap = userService.getUserMap(); + logger.info(userMap); + return Results.json().render(userMap); + } + + public Result helloWorld(Context context) { + Optional language = Optional.of("fr"); + String helloMsg = msg.get("helloMsg", language).get(); + return Results.text().render(helloMsg); + } + + public Result showFlashMsg(FlashScope flashScope) { + flashScope.success("Success message"); + flashScope.error("Error message"); + return Results.redirect("/home"); + } + + public Result home() { + return Results.html(); + } + + public Result createUser() { + return Results.html(); + } + + @UnitOfWork + public Result fetchUsers() { + EntityManager entityManager = entityManagerProvider.get(); + Query q = entityManager.createQuery("SELECT x FROM User x"); + List users = (List) q.getResultList(); + return Results.json().render(users); + } + + @Transactional + public Result insertUser(FlashScope flashScope, @JSR303Validation User user, Validation validation) { + logger.info("Inserting User : " +user); + + if (validation.getViolations().size() > 0) { + flashScope.error("Validation Error: User can't be created"); + } else { + EntityManager entityManager = entityManagerProvider.get(); + entityManager.persist(user); + entityManager.flush(); + flashScope.success("User '" + user + "' is created successfully"); + } + + return Results.redirect("/home"); + } + +} diff --git a/ninja/src/main/java/ehcache.xml b/ninja/src/main/java/ehcache.xml new file mode 100644 index 0000000000..b401b61a36 --- /dev/null +++ b/ninja/src/main/java/ehcache.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/ninja/src/main/java/logback.xml b/ninja/src/main/java/logback.xml new file mode 100644 index 0000000000..ebdcf56f76 --- /dev/null +++ b/ninja/src/main/java/logback.xml @@ -0,0 +1,33 @@ + + + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + diff --git a/ninja/src/main/java/models/User.java b/ninja/src/main/java/models/User.java new file mode 100644 index 0000000000..e021567bca --- /dev/null +++ b/ninja/src/main/java/models/User.java @@ -0,0 +1,25 @@ +package models; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.validation.constraints.NotNull; + +@Entity +public class User { + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + Long id; + + @NotNull + public String firstName; + + public String email; + + public String toString() { + return firstName + " : " + email; + } + +} diff --git a/ninja/src/main/java/services/UserService.java b/ninja/src/main/java/services/UserService.java new file mode 100644 index 0000000000..10d625c66f --- /dev/null +++ b/ninja/src/main/java/services/UserService.java @@ -0,0 +1,9 @@ +package services; + +import java.util.HashMap; + +public interface UserService { + + HashMap getUserMap(); + +} diff --git a/ninja/src/main/java/services/UserServiceImpl.java b/ninja/src/main/java/services/UserServiceImpl.java new file mode 100644 index 0000000000..0f8c2214cf --- /dev/null +++ b/ninja/src/main/java/services/UserServiceImpl.java @@ -0,0 +1,15 @@ +package services; + +import java.util.HashMap; + +public class UserServiceImpl implements UserService { + + @Override + public HashMap getUserMap() { + HashMap userMap = new HashMap<>(); + userMap.put("name", "Norman Lewis"); + userMap.put("email", "norman@email.com"); + return userMap; + } + +} diff --git a/ninja/src/main/java/views/ApplicationController/createUser.ftl.html b/ninja/src/main/java/views/ApplicationController/createUser.ftl.html new file mode 100644 index 0000000000..9156f7dbf2 --- /dev/null +++ b/ninja/src/main/java/views/ApplicationController/createUser.ftl.html @@ -0,0 +1,12 @@ +<#import "../layout/defaultLayout.ftl.html" as layout> +<@layout.myLayout "Create User"> + +
+ + First Name : +
+ Email : +
+ + + \ No newline at end of file diff --git a/ninja/src/main/java/views/ApplicationController/home.ftl.html b/ninja/src/main/java/views/ApplicationController/home.ftl.html new file mode 100644 index 0000000000..10f6612d54 --- /dev/null +++ b/ninja/src/main/java/views/ApplicationController/home.ftl.html @@ -0,0 +1,9 @@ +<#import "../layout/defaultLayout.ftl.html" as layout> +<@layout.myLayout "Home page"> + + +

${i18n("helloMsg")}

+ +User Json + + \ No newline at end of file diff --git a/ninja/src/main/java/views/ApplicationController/index.ftl.html b/ninja/src/main/java/views/ApplicationController/index.ftl.html new file mode 100644 index 0000000000..25d0a31229 --- /dev/null +++ b/ninja/src/main/java/views/ApplicationController/index.ftl.html @@ -0,0 +1,9 @@ + + + Ninja: Index + + +

${i18n("helloMsg")}

+ User Json + + \ No newline at end of file diff --git a/ninja/src/main/java/views/layout/defaultLayout.ftl.html b/ninja/src/main/java/views/layout/defaultLayout.ftl.html new file mode 100644 index 0000000000..a61edd19e6 --- /dev/null +++ b/ninja/src/main/java/views/layout/defaultLayout.ftl.html @@ -0,0 +1,58 @@ +<#macro myLayout title="Layout example"> + + + + + ${title} + + + + + + + + + + + + + + + + + + +
+ + <#include "header.ftl.html"/> + + <#if (flash.error)??> +
+ ${flash.error} +
+ + + <#if (flash.success)??> +
+ ${flash.success} +
+ + + <#nested/> + + <#include "footer.ftl.html"/> + +
+ + + + + \ No newline at end of file diff --git a/ninja/src/main/java/views/layout/footer.ftl.html b/ninja/src/main/java/views/layout/footer.ftl.html new file mode 100644 index 0000000000..0a2cb2721e --- /dev/null +++ b/ninja/src/main/java/views/layout/footer.ftl.html @@ -0,0 +1,5 @@ +
+ + diff --git a/ninja/src/main/java/views/layout/header.ftl.html b/ninja/src/main/java/views/layout/header.ftl.html new file mode 100644 index 0000000000..af79449bf2 --- /dev/null +++ b/ninja/src/main/java/views/layout/header.ftl.html @@ -0,0 +1,20 @@ + \ No newline at end of file diff --git a/ninja/src/main/java/views/system/403forbidden.ftl.html b/ninja/src/main/java/views/system/403forbidden.ftl.html new file mode 100644 index 0000000000..0f4efd160a --- /dev/null +++ b/ninja/src/main/java/views/system/403forbidden.ftl.html @@ -0,0 +1,18 @@ +<#import "../layout/defaultLayout.ftl.html" as layout> +<@layout.myLayout "Error. Forbidden."> +
+
+
+
+

+ Oops!

+

+ 403 Forbidden

+
+ Sorry, an error has occured. Requested page is forbidden! +
+
+
+
+
+ \ No newline at end of file diff --git a/ninja/src/main/java/views/system/404notFound.ftl.html b/ninja/src/main/java/views/system/404notFound.ftl.html new file mode 100644 index 0000000000..c10e7c3949 --- /dev/null +++ b/ninja/src/main/java/views/system/404notFound.ftl.html @@ -0,0 +1,18 @@ +<#import "../layout/defaultLayout.ftl.html" as layout> +<@layout.myLayout "Error. Not found."> +
+
+
+
+

+ Oops!

+

+ 404 Not Found

+
+ Sorry, an error has occured. Requested page not found! +
+
+
+
+
+ \ No newline at end of file diff --git a/ninja/src/main/webapp/WEB-INF/web.xml b/ninja/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..fe4b2c95bf --- /dev/null +++ b/ninja/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,41 @@ + + + + + + ninja + + + ninja.servlet.NinjaServletListener + + + + guiceFilter + com.google.inject.servlet.GuiceFilter + + + guiceFilter + /* + + + diff --git a/ninja/src/test/java/controllers/ApiControllerDocTesterTest.java b/ninja/src/test/java/controllers/ApiControllerDocTesterTest.java new file mode 100644 index 0000000000..d5f4f1811c --- /dev/null +++ b/ninja/src/test/java/controllers/ApiControllerDocTesterTest.java @@ -0,0 +1,27 @@ +package controllers; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; +import org.doctester.testbrowser.Request; +import org.doctester.testbrowser.Response; +import org.junit.Test; +import ninja.NinjaDocTester; + +public class ApiControllerDocTesterTest extends NinjaDocTester { + + String URL_INDEX = "/"; + String URL_HELLO = "/hello"; + + @Test + public void testGetIndex() { + Response response = makeRequest(Request.GET().url(testServerUrl().path(URL_INDEX))); + assertThat(response.payload, containsString("Hello, welcome to Ninja Framework!")); + } + + @Test + public void testGetHello() { + Response response = makeRequest(Request.GET().url(testServerUrl().path(URL_HELLO))); + assertThat(response.payload, containsString("Bonjour, bienvenue dans Ninja Framework!")); + } + +} diff --git a/ninja/src/test/java/controllers/ApiControllerMockUnitTest.java b/ninja/src/test/java/controllers/ApiControllerMockUnitTest.java new file mode 100644 index 0000000000..cb53965678 --- /dev/null +++ b/ninja/src/test/java/controllers/ApiControllerMockUnitTest.java @@ -0,0 +1,32 @@ +package controllers; + +import static org.junit.Assert.assertEquals; +import javax.inject.Inject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import ninja.NinjaRunner; +import ninja.Result; +import services.UserService; + +@RunWith(NinjaRunner.class) +public class ApiControllerMockUnitTest { + + @Inject private UserService userService; + + ApplicationController applicationController; + + @Before + public void setupTest() { + applicationController = new ApplicationController(); + applicationController.userService = userService; + } + + @Test + public void testThatGetUserJson() { + Result result = applicationController.userJson(); + System.out.println(result.getRenderable()); + assertEquals(userService.getUserMap().toString(), result.getRenderable().toString()); + } + +} diff --git a/oauth2-framework-impl/README.md b/oauth2-framework-impl/README.md index ea9686b451..ae28c1b511 100644 --- a/oauth2-framework-impl/README.md +++ b/oauth2-framework-impl/README.md @@ -4,4 +4,4 @@ This module contains articles about the implementation of OAuth2 with Java EE. ### Relevant Articles -- [Implementing The OAuth 2.0 Authorization Framework Using Java EE](https://www.baeldung.com/java-ee-oauth2-implementation) +- [Implementing The OAuth 2.0 Authorization Framework Using Jakarta EE](https://www.baeldung.com/java-ee-oauth2-implementation) diff --git a/oauth2-framework-impl/oauth2-authorization-server/README.md b/oauth2-framework-impl/oauth2-authorization-server/README.md deleted file mode 100644 index 4bcb9790b1..0000000000 --- a/oauth2-framework-impl/oauth2-authorization-server/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Implementing The OAuth 2.0 Authorization Framework Using Jakarta EE](https://www.baeldung.com/java-ee-oauth2-implementation) diff --git a/oauth2-framework-impl/oauth2-client/README.md b/oauth2-framework-impl/oauth2-client/README.md deleted file mode 100644 index 4bcb9790b1..0000000000 --- a/oauth2-framework-impl/oauth2-client/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Implementing The OAuth 2.0 Authorization Framework Using Jakarta EE](https://www.baeldung.com/java-ee-oauth2-implementation) diff --git a/oauth2-framework-impl/oauth2-resource-server/README.md b/oauth2-framework-impl/oauth2-resource-server/README.md deleted file mode 100644 index 4bcb9790b1..0000000000 --- a/oauth2-framework-impl/oauth2-resource-server/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Implementing The OAuth 2.0 Authorization Framework Using Jakarta EE](https://www.baeldung.com/java-ee-oauth2-implementation) diff --git a/open-liberty/README.md b/open-liberty/README.md new file mode 100644 index 0000000000..6a51d2c486 --- /dev/null +++ b/open-liberty/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Open Liberty](https://www.baeldung.com/java-open-liberty) diff --git a/open-liberty/pom.xml b/open-liberty/pom.xml new file mode 100644 index 0000000000..d6588ce49a --- /dev/null +++ b/open-liberty/pom.xml @@ -0,0 +1,130 @@ + + + 4.0.0 + + com.baeldung + open-liberty + 1.0-SNAPSHOT + war + + + + jakarta.platform + jakarta.jakartaee-web-api + ${version.jakarta.jakartaee-web-api} + provided + + + org.eclipse.microprofile + microprofile + ${version.microprofile} + pom + provided + + + org.apache.derby + derby + ${version.derby} + + + + + junit + junit + ${version.junit} + test + + + org.eclipse + yasson + ${version.yasson} + test + + + org.apache.cxf + cxf-rt-rs-client + ${version.cxf-rt-rs-client} + test + + + org.glassfish + javax.json + ${version.javax.json} + test + + + org.apache.cxf + cxf-rt-rs-mp-client + ${version.cxf-rt-rs-mp-client} + test + + + + + ${project.artifactId} + + + + io.openliberty.tools + liberty-maven-plugin + ${version.liberty-maven-plugin} + + + org.apache.maven.plugins + maven-dependency-plugin + ${version.maven-dependency-plugin} + + + copy-derby-dependency + package + + copy-dependencies + + + derby + ${project.build.directory}/liberty/wlp/usr/shared/resources/ + + ${testServerHttpPort} + + + + + + + org.apache.maven.plugins + maven-war-plugin + ${version.maven-war-plugin} + + + + + + + 1.8 + 1.8 + UTF-8 + UTF-8 + false + + + 8.0.0 + 3.2 + 10.14.2.0 + 3.1 + 2.10 + 3.2.3 + 4.12 + 1.0.5 + 3.2.6 + 1.0.4 + 3.3.1 + + + openliberty + 9080 + 9443 + 7070 + + \ No newline at end of file diff --git a/open-liberty/src/main/java/com/baeldung/openliberty/person/dao/PersonDao.java b/open-liberty/src/main/java/com/baeldung/openliberty/person/dao/PersonDao.java new file mode 100644 index 0000000000..e2d408d8b0 --- /dev/null +++ b/open-liberty/src/main/java/com/baeldung/openliberty/person/dao/PersonDao.java @@ -0,0 +1,24 @@ +package com.baeldung.openliberty.person.dao; + +import javax.enterprise.context.RequestScoped; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import com.baeldung.openliberty.person.model.Person; + +@RequestScoped +public class PersonDao { + + @PersistenceContext(name = "jpa-unit") + private EntityManager em; + + public Person createPerson(Person person) { + em.persist(person); + return person; + } + + public Person readPerson(int personId) { + return em.find(Person.class, personId); + } + +} \ No newline at end of file diff --git a/open-liberty/src/main/java/com/baeldung/openliberty/person/model/Person.java b/open-liberty/src/main/java/com/baeldung/openliberty/person/model/Person.java new file mode 100644 index 0000000000..79e8c16911 --- /dev/null +++ b/open-liberty/src/main/java/com/baeldung/openliberty/person/model/Person.java @@ -0,0 +1,58 @@ +package com.baeldung.openliberty.person.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; + +@Entity +public class Person { + + @GeneratedValue(strategy = GenerationType.AUTO) + @Id + private int id; + + private String username; + private String email; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Person(int id, @NotBlank String username, @Email String email) { + super(); + this.id = id; + this.username = username; + this.email = email; + } + + public Person() { + super(); + } + + public String toString() { + return this.id + ":" +this.username; + } +} diff --git a/open-liberty/src/main/java/com/baeldung/openliberty/person/resource/PersonResource.java b/open-liberty/src/main/java/com/baeldung/openliberty/person/resource/PersonResource.java new file mode 100644 index 0000000000..0fb86860b8 --- /dev/null +++ b/open-liberty/src/main/java/com/baeldung/openliberty/person/resource/PersonResource.java @@ -0,0 +1,52 @@ +package com.baeldung.openliberty.person.resource; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +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 com.baeldung.openliberty.person.dao.PersonDao; +import com.baeldung.openliberty.person.model.Person; + +@RequestScoped +@Path("persons") +public class PersonResource { + + @Inject + private PersonDao personDao; + + @GET + @Produces(MediaType.APPLICATION_JSON) + public List getAllPersons() { + return Arrays.asList(new Person(1, "normanlewis", "normanlewis@email.com")); + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Transactional + public Response addPerson(Person person) { + personDao.createPerson(person); + String respMessage = "Person #" + person.getId() + " created successfully."; + return Response.status(Response.Status.CREATED).entity(respMessage).build(); + } + + @GET + @Path("{id}") + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Person getPerson(@PathParam("id") int id) { + Person person = personDao.readPerson(id); + return person; + } +} diff --git a/open-liberty/src/main/java/com/baeldung/openliberty/rest/ApiApplication.java b/open-liberty/src/main/java/com/baeldung/openliberty/rest/ApiApplication.java new file mode 100644 index 0000000000..176eaccaed --- /dev/null +++ b/open-liberty/src/main/java/com/baeldung/openliberty/rest/ApiApplication.java @@ -0,0 +1,9 @@ +package com.baeldung.openliberty.rest; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/api") +public class ApiApplication extends Application { + +} diff --git a/open-liberty/src/main/java/com/baeldung/openliberty/rest/consumes/RestConsumer.java b/open-liberty/src/main/java/com/baeldung/openliberty/rest/consumes/RestConsumer.java new file mode 100644 index 0000000000..8073c408dd --- /dev/null +++ b/open-liberty/src/main/java/com/baeldung/openliberty/rest/consumes/RestConsumer.java @@ -0,0 +1,18 @@ +package com.baeldung.openliberty.rest.consumes; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.core.Response; + +public class RestConsumer { + + public static String consumeWithJsonb(String targetUrl) { + Client client = ClientBuilder.newClient(); + Response response = client.target(targetUrl).request().get(); + String result = response.readEntity(String.class); + response.close(); + client.close(); + return result; + } + +} diff --git a/open-liberty/src/main/java/com/baeldung/openliberty/servlet/AppServlet.java b/open-liberty/src/main/java/com/baeldung/openliberty/servlet/AppServlet.java new file mode 100644 index 0000000000..d8c8d159c4 --- /dev/null +++ b/open-liberty/src/main/java/com/baeldung/openliberty/servlet/AppServlet.java @@ -0,0 +1,27 @@ +package com.baeldung.openliberty.servlet; + +import java.io.IOException; + +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(urlPatterns="/app") +public class AppServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String htmlOutput = "

Hello! Welcome to Open Liberty

"; + response.getWriter().append(htmlOutput); + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + doGet(request, response); + } +} \ No newline at end of file diff --git a/open-liberty/src/main/liberty/config/server.xml b/open-liberty/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..bc99905058 --- /dev/null +++ b/open-liberty/src/main/liberty/config/server.xml @@ -0,0 +1,28 @@ + + + mpHealth-2.0 + servlet-4.0 + jaxrs-2.1 + jsonp-1.1 + jsonb-1.0 + cdi-2.0 + jpa-2.2 + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/open-liberty/src/main/resources/META-INF/persistence.xml b/open-liberty/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..ca8ad1a5c9 --- /dev/null +++ b/open-liberty/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + + jdbc/jpadatasource + + + + + + \ No newline at end of file diff --git a/open-liberty/src/test/java/com/baeldung/openliberty/RestClientTest.java b/open-liberty/src/test/java/com/baeldung/openliberty/RestClientTest.java new file mode 100644 index 0000000000..4978483ca0 --- /dev/null +++ b/open-liberty/src/test/java/com/baeldung/openliberty/RestClientTest.java @@ -0,0 +1,40 @@ +package com.baeldung.openliberty; + +import static org.junit.Assert.assertEquals; + +import javax.json.bind.JsonbBuilder; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.openliberty.person.model.Person; +import com.baeldung.openliberty.rest.consumes.RestConsumer; + +public class RestClientTest { + + private static String BASE_URL; + + private final String API_PERSON = "api/persons"; + + @BeforeClass + public static void oneTimeSetup() { + BASE_URL = "http://localhost:9080/"; + } + + @Test + public void testSuite() { + //run the test only when liberty server is started + //this.whenConsumeWithJsonb_thenGetPerson(); + } + + public void whenConsumeWithJsonb_thenGetPerson() { + String url = BASE_URL + API_PERSON + "/1"; + String result = RestConsumer.consumeWithJsonb(url); + + Person person = JsonbBuilder.create().fromJson(result, Person.class); + assertEquals(1, person.getId()); + assertEquals("normanlewis", person.getUsername()); + assertEquals("normanlewis@email.com", person.getEmail()); + } + +} diff --git a/osgi/pom.xml b/osgi/pom.xml index ed708e8004..afc980c8bd 100644 --- a/osgi/pom.xml +++ b/osgi/pom.xml @@ -11,7 +11,6 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - .. diff --git a/parent-boot-1/pom.xml b/parent-boot-1/pom.xml index df2a7f8400..2e9c767aa2 100644 --- a/parent-boot-1/pom.xml +++ b/parent-boot-1/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 parent-boot-1 0.0.1-SNAPSHOT diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index 881a0f1d67..c7bb11b1d5 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 parent-boot-2 0.0.1-SNAPSHOT @@ -79,7 +81,7 @@ 3.3.0 1.0.22.RELEASE - 2.1.9.RELEASE + 2.2.6.RELEASE diff --git a/parent-java/pom.xml b/parent-java/pom.xml index 47965fc36d..baad9fecf4 100644 --- a/parent-java/pom.xml +++ b/parent-java/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 parent-java 0.0.1-SNAPSHOT @@ -27,11 +29,25 @@ commons-io ${commons.io.version} + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + 23.0 2.6 + 1.19 + 2.3.7 + 4.12 + 2.2 diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index a180343378..52a753439c 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 parent-kotlin parent-kotlin @@ -16,7 +18,7 @@ jcenter - http://jcenter.bintray.com + https://jcenter.bintray.com kotlin-ktor @@ -29,7 +31,7 @@ spring-milestone Spring Milestone Repository - http://repo.spring.io/milestone + https://repo.spring.io/milestone @@ -45,7 +47,7 @@ org.springframework.boot spring-boot-dependencies - 2.2.0.M4 + ${boot.dependencies.version} pom import @@ -215,6 +217,7 @@ 0.9.5 3.12.0 1.3.2 + 2.2.0.M4 diff --git a/parent-spring-4/pom.xml b/parent-spring-4/pom.xml index 671ca7db6b..3f9a22fb03 100644 --- a/parent-spring-4/pom.xml +++ b/parent-spring-4/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 parent-spring-4 0.0.1-SNAPSHOT @@ -51,7 +53,7 @@ - 4.3.25.RELEASE + 4.3.26.RELEASE 1.6.1 diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 9260f88de5..c75655ebc8 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 parent-spring-5 0.0.1-SNAPSHOT @@ -30,8 +31,8 @@ - 5.1.9.RELEASE - 5.1.6.RELEASE + 5.2.5.RELEASE + 5.2.3.RELEASE \ No newline at end of file diff --git a/patterns/design-patterns-architectural/pom.xml b/patterns/design-patterns-architectural/pom.xml index 81cc55aa21..d1945a1d0a 100644 --- a/patterns/design-patterns-architectural/pom.xml +++ b/patterns/design-patterns-architectural/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -22,11 +21,6 @@ test - - javax - javaee-api - ${javaee.version} - org.hibernate hibernate-core @@ -41,11 +35,7 @@ - UTF-8 - 1.8 - 1.8 3.9.1 - 8.0 5.2.16.Final 6.0.6 diff --git a/patterns/design-patterns-behavioral-2/pom.xml b/patterns/design-patterns-behavioral-2/pom.xml index 4cbe6e32b9..3a6d21353e 100644 --- a/patterns/design-patterns-behavioral-2/pom.xml +++ b/patterns/design-patterns-behavioral-2/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -24,9 +23,6 @@ - UTF-8 - 1.8 - 1.8 3.12.2 diff --git a/patterns/design-patterns-behavioral/pom.xml b/patterns/design-patterns-behavioral/pom.xml index c4ae00435e..aceaabf582 100644 --- a/patterns/design-patterns-behavioral/pom.xml +++ b/patterns/design-patterns-behavioral/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -41,9 +40,6 @@ - UTF-8 - 1.8 - 1.8 16.0.2 3.9.1 diff --git a/patterns/design-patterns-cloud/pom.xml b/patterns/design-patterns-cloud/pom.xml index 51f6a42f76..34defb7eac 100644 --- a/patterns/design-patterns-cloud/pom.xml +++ b/patterns/design-patterns-cloud/pom.xml @@ -9,47 +9,4 @@ design-patterns-cloud pom - - - junit - junit - ${junit.version} - test - - - org.mockito - mockito-core - ${mockito-core.version} - test - - - io.github.resilience4j - resilience4j-retry - ${resilience4j.version} - test - - - org.slf4j - slf4j-api - ${slf4j.version} - test - - - org.slf4j - slf4j-simple - ${slf4j.version} - test - - - - - UTF-8 - 1.8 - 1.8 - 4.12 - 2.27.0 - 1.7.26 - 0.16.0 - - diff --git a/patterns/design-patterns-creational/pom.xml b/patterns/design-patterns-creational/pom.xml index aa20c1c085..7c2742ade4 100644 --- a/patterns/design-patterns-creational/pom.xml +++ b/patterns/design-patterns-creational/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -36,10 +35,6 @@ - UTF-8 - 1.8 - 1.8 - 2.4.1 3.0.2 3.9.1 diff --git a/patterns/design-patterns-creational/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java b/patterns/design-patterns-creational/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java index f05a3baaa3..a602d1c55d 100644 --- a/patterns/design-patterns-creational/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java +++ b/patterns/design-patterns-creational/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java @@ -19,8 +19,8 @@ public class User { } 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); } @@ -53,11 +53,4 @@ public class User { 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/patterns/design-patterns-functional/pom.xml b/patterns/design-patterns-functional/pom.xml index ec37ad1e8d..e5166dc61e 100644 --- a/patterns/design-patterns-functional/pom.xml +++ b/patterns/design-patterns-functional/pom.xml @@ -11,13 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. - - UTF-8 - 1.8 - 1.8 - - diff --git a/patterns/design-patterns-structural/pom.xml b/patterns/design-patterns-structural/pom.xml index 97e0b9b38b..c37b6845be 100644 --- a/patterns/design-patterns-structural/pom.xml +++ b/patterns/design-patterns-structural/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -22,10 +21,4 @@ - - UTF-8 - 1.8 - 1.8 - - diff --git a/patterns/dip/pom.xml b/patterns/dip/pom.xml index 37c980f2e3..7217c4fdcc 100644 --- a/patterns/dip/pom.xml +++ b/patterns/dip/pom.xml @@ -12,16 +12,9 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. - - junit - junit - ${junit.version} - test - org.assertj assertj-core @@ -31,9 +24,6 @@ - UTF-8 - 11 - 11 3.12.1 diff --git a/patterns/front-controller/pom.xml b/patterns/front-controller/pom.xml index 1de3b82fcd..dc10250946 100644 --- a/patterns/front-controller/pom.xml +++ b/patterns/front-controller/pom.xml @@ -10,7 +10,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. diff --git a/patterns/intercepting-filter/pom.xml b/patterns/intercepting-filter/pom.xml index 435c1e13cf..7f2f57b5e1 100644 --- a/patterns/intercepting-filter/pom.xml +++ b/patterns/intercepting-filter/pom.xml @@ -10,7 +10,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -27,15 +26,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - org.apache.maven.plugins maven-war-plugin diff --git a/patterns/pom.xml b/patterns/pom.xml index 8a510769a9..4c17055231 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -10,21 +10,20 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - .. - front-controller - intercepting-filter design-patterns-architectural design-patterns-behavioral design-patterns-behavioral-2 + design-patterns-cloud design-patterns-creational design-patterns-functional design-patterns-structural - solid dip - design-patterns-cloud + front-controller + intercepting-filter + solid diff --git a/patterns/solid/pom.xml b/patterns/solid/pom.xml index 1b0e35339d..ad76ea89fd 100644 --- a/patterns/solid/pom.xml +++ b/patterns/solid/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. diff --git a/patterns/solid/src/main/java/com/baeldung/s/TextManipulator.java b/patterns/solid/src/main/java/com/baeldung/s/TextManipulator.java new file mode 100644 index 0000000000..d084a78815 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/s/TextManipulator.java @@ -0,0 +1,37 @@ +package com.baeldung.s; + +public class TextManipulator { + private String text; + + public TextManipulator(String text) { + this.text = text; + } + + public String getText() { + return text; + } + + public void appendText(String newText) { + text = text.concat(newText); + } + + public String findWordAndReplace(String word, String replacementWord) { + if (text.contains(word)) { + text = text.replace(word, replacementWord); + } + return text; + } + + public String findWordAndDelete(String word) { + if (text.contains(word)) { + text = text.replace(word, ""); + } + return text; + } + + /* + * Bad practice when implementing SRP principle, not in the scope of this class + public void printText() { + System.out.println(textManipulator.getText()); + }*/ +} diff --git a/patterns/solid/src/main/java/com/baeldung/s/TextPrinter.java b/patterns/solid/src/main/java/com/baeldung/s/TextPrinter.java new file mode 100644 index 0000000000..d6a413e7ac --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/s/TextPrinter.java @@ -0,0 +1,23 @@ +package com.baeldung.s; + +import java.util.Arrays; + +public class TextPrinter { + TextManipulator textManipulator; + + public TextPrinter(TextManipulator textManipulator) { + this.textManipulator = textManipulator; + } + + public void printText() { + System.out.println(textManipulator.getText()); + } + + public void printOutEachWordOfText() { + System.out.println(Arrays.toString(textManipulator.getText().split(" "))); + } + + public void printRangeOfCharacters(int startingIndex, int endIndex) { + System.out.println(textManipulator.getText().substring(startingIndex, endIndex)); + } +} diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml index 94588c99d4..c8cebd8a11 100644 --- a/performance-tests/pom.xml +++ b/performance-tests/pom.xml @@ -38,7 +38,7 @@ org.mapstruct mapstruct-processor - 1.2.0.Final + ${mapstruct-jdk8.version} provided @@ -93,6 +93,15 @@ Name of the benchmark Uber-JAR to generate. --> benchmarks + 3.1 + 2.2 + 2.5.1 + 2.4 + 2.9.1 + 2.6 + 3.3 + 2.2.1 + 2.17 @@ -100,7 +109,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.1 + ${compiler.plugin.version} ${javac.target} ${javac.target} @@ -117,7 +126,7 @@ org.apache.maven.plugins maven-shade-plugin - 2.2 + ${shade.plugin.version} package @@ -162,31 +171,31 @@ maven-install-plugin - 2.5.1 + ${install.version} maven-jar-plugin - 2.4 + ${jar.plugin.version} maven-javadoc-plugin - 2.9.1 + ${javadoc.plugin.version} maven-resources-plugin - 2.6 + ${resources.plugin.version} maven-site-plugin - 3.3 + ${site.plugin.version} maven-source-plugin - 2.2.1 + ${source.plugin.version} maven-surefire-plugin - 2.17 + ${surefire.plugin.version} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/MappingFrameworksPerformance.java b/performance-tests/src/main/java/com/baeldung/performancetests/MappingFrameworksPerformance.java index 1c9e4c5dc4..66251eb078 100644 --- a/performance-tests/src/main/java/com/baeldung/performancetests/MappingFrameworksPerformance.java +++ b/performance-tests/src/main/java/com/baeldung/performancetests/MappingFrameworksPerformance.java @@ -1,4 +1,4 @@ -package com.baeldung.performancetests.benchmark; +package com.baeldung.performancetests; import com.baeldung.performancetests.dozer.DozerConverter; import com.baeldung.performancetests.jmapper.JMapperConverter; diff --git a/persistence-modules/activejdbc/pom.xml b/persistence-modules/activejdbc/pom.xml index 47643cd639..84ce1c2b48 100644 --- a/persistence-modules/activejdbc/pom.xml +++ b/persistence-modules/activejdbc/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ @@ -41,16 +40,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - UTF-8 - - org.javalite activejdbc-instrumentation diff --git a/persistence-modules/apache-cayenne/pom.xml b/persistence-modules/apache-cayenne/pom.xml index 7c94c5ba39..d728e18b33 100644 --- a/persistence-modules/apache-cayenne/pom.xml +++ b/persistence-modules/apache-cayenne/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/core-java-persistence/pom.xml b/persistence-modules/core-java-persistence/pom.xml index 80c4053743..1224523ac7 100644 --- a/persistence-modules/core-java-persistence/pom.xml +++ b/persistence-modules/core-java-persistence/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + persistence-modules + 1.0.0-SNAPSHOT @@ -60,19 +59,8 @@ - - core-java-persistence - - - src/main/resources - true - - - - 42.2.5.jre7 - 8.0.15 3.10.0 2.4.0 3.2.0 diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java index 289db18c53..22ef0e5411 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java @@ -14,7 +14,8 @@ public class BasicConnectionPool implements ConnectionPool { 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; + private static final int MAX_POOL_SIZE = 20; + private static final int MAX_TIMEOUT = 5; public static BasicConnectionPool create(String url, String user, String password) throws SQLException { List pool = new ArrayList<>(INITIAL_POOL_SIZE); @@ -42,6 +43,11 @@ public class BasicConnectionPool implements ConnectionPool { } Connection connection = connectionPool.remove(connectionPool.size() - 1); + + if(!connection.isValid(MAX_TIMEOUT)){ + connection = createConnection(url, user, password); + } + usedConnections.add(connection); return connection; } diff --git a/persistence-modules/deltaspike/pom.xml b/persistence-modules/deltaspike/pom.xml index 141412654f..871bacd18b 100644 --- a/persistence-modules/deltaspike/pom.xml +++ b/persistence-modules/deltaspike/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/elasticsearch/pom.xml b/persistence-modules/elasticsearch/pom.xml index 878dd5847b..654d43d622 100644 --- a/persistence-modules/elasticsearch/pom.xml +++ b/persistence-modules/elasticsearch/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/flyway/pom.xml b/persistence-modules/flyway/pom.xml index 01b3dab6ee..f2e393abbf 100644 --- a/persistence-modules/flyway/pom.xml +++ b/persistence-modules/flyway/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -63,7 +63,7 @@ - 5.0.2 + 5.2.3 5.0.2 diff --git a/persistence-modules/flyway/src/main/resources/application.properties b/persistence-modules/flyway/src/main/resources/application.properties index 4d339eca5c..cee75fa4d9 100644 --- a/persistence-modules/flyway/src/main/resources/application.properties +++ b/persistence-modules/flyway/src/main/resources/application.properties @@ -1 +1 @@ -#flyway.enabled=false \ No newline at end of file +#spring.flyway.enabled=false \ No newline at end of file diff --git a/persistence-modules/hbase/README.md b/persistence-modules/hbase/README.md index df2683b27a..ea76c4ec4b 100644 --- a/persistence-modules/hbase/README.md +++ b/persistence-modules/hbase/README.md @@ -1,3 +1,3 @@ ### Relevant articles -- [HBase with Java](http://www.baeldung.com/hbase) +- [HBase with Java](https://www.baeldung.com/hbase) diff --git a/persistence-modules/hbase/pom.xml b/persistence-modules/hbase/pom.xml index 9403239fb2..f54f2d8985 100644 --- a/persistence-modules/hbase/pom.xml +++ b/persistence-modules/hbase/pom.xml @@ -7,9 +7,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/hbase/src/main/java/org/baeldung/hbase/HBaseClientOperations.java b/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HBaseClientOperations.java similarity index 99% rename from persistence-modules/hbase/src/main/java/org/baeldung/hbase/HBaseClientOperations.java rename to persistence-modules/hbase/src/main/java/com/baeldung/hbase/HBaseClientOperations.java index c78eacc834..f889e2eb56 100644 --- a/persistence-modules/hbase/src/main/java/org/baeldung/hbase/HBaseClientOperations.java +++ b/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HBaseClientOperations.java @@ -1,4 +1,4 @@ -package org.baeldung.hbase; +package com.baeldung.hbase; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HColumnDescriptor; diff --git a/persistence-modules/hbase/src/main/java/org/baeldung/hbase/HbaseClientExample.java b/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HbaseClientExample.java similarity index 97% rename from persistence-modules/hbase/src/main/java/org/baeldung/hbase/HbaseClientExample.java rename to persistence-modules/hbase/src/main/java/com/baeldung/hbase/HbaseClientExample.java index 07cb7df480..5546f15e36 100644 --- a/persistence-modules/hbase/src/main/java/org/baeldung/hbase/HbaseClientExample.java +++ b/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HbaseClientExample.java @@ -1,4 +1,4 @@ -package org.baeldung.hbase; +package com.baeldung.hbase; import com.google.protobuf.ServiceException; diff --git a/persistence-modules/hibernate-annotations/README.md b/persistence-modules/hibernate-annotations/README.md new file mode 100644 index 0000000000..393cf82bfd --- /dev/null +++ b/persistence-modules/hibernate-annotations/README.md @@ -0,0 +1,10 @@ +## Hibernate Annotations + +This module contains articles about Annotations used in Hibernate. + +### Relevant Articles: +- [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types) +- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) +- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) +- [Hibernate One to Many Annotation Tutorial](https://www.baeldung.com/hibernate-one-to-many) +- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) diff --git a/persistence-modules/hibernate-annotations/pom.xml b/persistence-modules/hibernate-annotations/pom.xml new file mode 100644 index 0000000000..5367921f31 --- /dev/null +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + hibernate-annotations + 0.1-SNAPSHOT + hibernate-annotations + jar + Hibernate tutorial illustrating the use of named parameters + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate-core.version} + + + + com.h2database + h2 + ${h2.version} + + + + org.apache.commons + commons-lang3 + ${commons.lang3.version} + + + + org.hibernate + hibernate-testing + ${hibernate-core.version} + + + + org.hibernate + hibernate-spatial + ${hibernate-core.version} + + + org.opengeo + geodb + ${geodb.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.4.7.Final + 1.4.200 + 3.8.1 + true + 2.1.7.RELEASE + 5.4.7.Final + 1.4.200 + 3.8.1 + 0.9 + + + diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..afe2aeac89 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,73 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.joincolumn.Email; +import com.baeldung.hibernate.joincolumn.Office; +import com.baeldung.hibernate.joincolumn.OfficeAddress; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); + metadataSources.addAnnotatedClass(Email.class); + metadataSources.addAnnotatedClass(Office.class); + metadataSources.addAnnotatedClass(OfficeAddress.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public 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; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java new file mode 100644 index 0000000000..d923bda5de --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; + +@Entity +public class Phone implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private boolean deleted; + + private String number; + + public Phone() { + } + + public Phone(String number) { + this.number = number; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/Group.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/Group.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/User.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java diff --git a/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-angular/src/main/resources/logback.xml b/persistence-modules/hibernate-annotations/src/main/resources/logback.xml similarity index 100% rename from spring-boot-angular/src/main/resources/logback.xml rename to persistence-modules/hibernate-annotations/src/main/resources/logback.xml diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties rename to persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties diff --git a/persistence-modules/hibernate5-2/src/test/resources/log4j.xml b/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/test/resources/log4j.xml rename to persistence-modules/hibernate-annotations/src/test/resources/log4j.xml diff --git a/persistence-modules/hibernate5-2/src/test/resources/log4j2.xml b/persistence-modules/hibernate-annotations/src/test/resources/log4j2.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/test/resources/log4j2.xml rename to persistence-modules/hibernate-annotations/src/test/resources/log4j2.xml diff --git a/persistence-modules/hibernate5-2/src/test/resources/logback.xml b/persistence-modules/hibernate-annotations/src/test/resources/logback.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/test/resources/logback.xml rename to persistence-modules/hibernate-annotations/src/test/resources/logback.xml diff --git a/persistence-modules/hibernate-annotations/src/test/resources/profile.png b/persistence-modules/hibernate-annotations/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-annotations/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-enterprise/README.md b/persistence-modules/hibernate-enterprise/README.md new file mode 100644 index 0000000000..c5606d0970 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/README.md @@ -0,0 +1,12 @@ +## Hibernate Enterprise + +This module contains articles about enterprise concerns such as Multitenancy, Errors, Exceptions, Logging and more in Hibernate. + +### Relevant articles: + +- [Introduction to Hibernate Spatial](https://www.baeldung.com/hibernate-spatial) +- [A Guide to Multitenancy in Hibernate 5](https://www.baeldung.com/hibernate-5-multitenancy) +- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) +- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) +- [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set) +- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels) \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/pom.xml b/persistence-modules/hibernate-enterprise/pom.xml new file mode 100644 index 0000000000..060cb4c904 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + hibernate-enterprise + 0.0.1-SNAPSHOT + hibernate-enterprise + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + org.opengeo + geodb + ${geodb.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 0.9 + + + diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..ddeb1c42ea --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,72 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(PointEntity.class); + metadataSources.addAnnotatedClass(PolygonEntity.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public 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; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernate/logging/Employee.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernate/logging/Employee.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java new file mode 100644 index 0000000000..736abde866 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -0,0 +1,43 @@ +package com.baeldung.hibernate.pojo; + +import com.vividsolutions.jts.geom.Point; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class PointEntity { + + @Id + @GeneratedValue + private Long id; + + @Column(columnDefinition="BINARY(2048)") + private Point point; + + public PointEntity() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Point getPoint() { + return point; + } + + public void setPoint(Point point) { + this.point = point; + } + + @Override + public String toString() { + return "PointEntity{" + "id=" + id + ", point=" + point + '}'; + } +} diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java new file mode 100644 index 0000000000..69208c8cd4 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo; + +import com.vividsolutions.jts.geom.Polygon; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class PolygonEntity { + + @Id + @GeneratedValue + private Long id; + + private Polygon polygon; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Polygon getPolygon() { + return polygon; + } + + public void setPolygon(Polygon polygon) { + this.polygon = polygon; + } + + @Override + public String toString() { + return "PolygonEntity{" + "id=" + id + ", polygon=" + polygon + '}'; + } +} diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java diff --git a/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml b/persistence-modules/hibernate-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml diff --git a/persistence-modules/hibernate5-2/src/main/resources/hibernate-logging.cfg.xml b/persistence-modules/hibernate-enterprise/src/main/resources/hibernate-logging.cfg.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/main/resources/hibernate-logging.cfg.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/hibernate-logging.cfg.xml diff --git a/persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml b/persistence-modules/hibernate-enterprise/src/main/resources/hibernate.cfg.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/hibernate.cfg.xml diff --git a/persistence-modules/hibernate-enterprise/src/main/resources/init_database.sql b/persistence-modules/hibernate-enterprise/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/spring-boot-artifacts/src/main/resources/logback.xml b/persistence-modules/hibernate-enterprise/src/main/resources/logback.xml similarity index 100% rename from spring-boot-artifacts/src/main/resources/logback.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/logback.xml diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernatelogging/HibernateLoggingIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java similarity index 97% rename from persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernatelogging/HibernateLoggingIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java index 8ec722671d..f609c75834 100644 --- a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernatelogging/HibernateLoggingIntegrationTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.hibernatelogging; +package com.baeldung.hibernate.logging; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java similarity index 100% rename from persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-multitenancy.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-multitenancy.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb1.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb1.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb2.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb2.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-schema-multitenancy.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-schema-multitenancy.properties diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties new file mode 100644 index 0000000000..1657c838e3 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate.properties diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-enterprise/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate-enterprise/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/persistence-modules/hibernate-enterprise/src/test/resources/profile.png b/persistence-modules/hibernate-enterprise/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-enterprise/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-jpa/README.md b/persistence-modules/hibernate-jpa/README.md new file mode 100644 index 0000000000..514fcedb8a --- /dev/null +++ b/persistence-modules/hibernate-jpa/README.md @@ -0,0 +1,17 @@ +## Hibernate JPA + +This module contains articles specific to use of Hibernate as a JPA implementation, such as Locking, Bootstrapping, One-to-One Relationship, Persistence Context, and more. + +### Relevant articles: + +- [JPA Attribute Converters](https://www.baeldung.com/jpa-attribute-converters) +- [Pessimistic Locking in JPA](https://www.baeldung.com/jpa-pessimistic-locking) +- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) +- [Optimistic Locking in JPA](https://www.baeldung.com/jpa-optimistic-locking) +- [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions) +- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) +- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) +- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) +- [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) +- [Quick Guide to EntityManager#getReference()](https://www.baeldung.com/jpa-entity-manager-get-reference) +- [Hibernate Error “No Persistence Provider for EntityManager”](https://www.baeldung.com/hibernate-no-persistence-provider) diff --git a/persistence-modules/hibernate-jpa/pom.xml b/persistence-modules/hibernate-jpa/pom.xml new file mode 100644 index 0000000000..07b1ee1c51 --- /dev/null +++ b/persistence-modules/hibernate-jpa/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + hibernate-jpa + 0.0.1-SNAPSHOT + hibernate-jpa + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-thymeleaf + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + + com.zaxxer + HikariCP + + + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk-jmh.version} + + + org.postgresql + postgresql + ${postgresql.version} + + + + + 5.3.7.Final + 8.0.13 + 42.2.11 + 2.2.3 + 3.8.0 + 1.21 + 2.1.7.RELEASE + + + diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..cf59fe4855 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,89 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +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.Person; +import com.baeldung.hibernate.pojo.Post; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Person.class); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(Individual.class); + metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class); + metadataSources.addAnnotatedClass(PessimisticLockingStudent.class); + metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); + 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); + metadataSources.addAnnotatedClass(Post.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public 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; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(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 List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java new file mode 100644 index 0000000000..1de8de0327 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.entitymanager.getreference; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Game { + + @Id + private Long id; + + private String name; + + public Game() { + } + + public Game(Long id, String name) { + 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; + } + +} diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java new file mode 100644 index 0000000000..459a3a00ad --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.entitymanager.getreference; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Player { + + @Id + private Long id; + + private String name; + + @ManyToOne + private Game game; + + public Player() { + } + + public Player(Long id, String name) { + 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 Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java new file mode 100644 index 0000000000..18fa2a41db --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.onetoone; + +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + + private HibernateUtil() { + } + + public static SessionFactory getSessionFactory(Strategy strategy) { + return buildSessionFactory(strategy); + } + + private static SessionFactory buildSessionFactory(Strategy strategy) { + try { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + for (Class entityClass : strategy.getEntityClasses()) { + metadataSources.addAnnotatedClass(entityClass); + } + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + } catch (IOException ex) { + throw new ExceptionInInitializerError(ex); + } + } + + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource("hibernate.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java new file mode 100644 index 0000000000..5fae7f6a97 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java @@ -0,0 +1,52 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "MOVIE") +public class Movie { + + @Id + private Long id; + + private String movieName; + + private Integer releaseYear; + + private String language; + + public String getMovieName() { + return movieName; + } + + public void setMovieName(String movieName) { + this.movieName = movieName; + } + + public Integer getReleaseYear() { + return releaseYear; + } + + public void setReleaseYear(Integer releaseYear) { + this.releaseYear = releaseYear; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java new file mode 100644 index 0000000000..335fe73f75 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.pojo; + +import java.io.Serializable; + +public class PersonName implements Serializable { + + private static final long serialVersionUID = 7883094644631050150L; + + private String name; + + private String surname; + + 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/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java new file mode 100644 index 0000000000..25e51e35d0 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java @@ -0,0 +1,59 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "posts") +public class Post { + + @Id + @GeneratedValue + private int id; + + private String title; + + private String body; + + public Post() { } + + public Post(String title, String body) { + this.title = title; + this.body = body; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + @Override + public String toString() { + return "Post{" + + "id=" + id + + ", title='" + title + '\'' + + ", body='" + body + '\'' + + '}'; + } +} diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/entity/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/entity/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/create-db.sql b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/create-db.sql new file mode 100644 index 0000000000..7074b603f6 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/create-db.sql @@ -0,0 +1,3 @@ +create table Game (id bigint not null, name varchar(255), primary key (id)); +create table Player (id bigint not null, name varchar(255), game_id bigint, primary key (id)); +alter table Player add constraint FKohr86afuapoujklti79wo27aa foreign key (game_id) references Game(id); \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/data.sql b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/data.sql new file mode 100644 index 0000000000..1e83082801 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/data.sql @@ -0,0 +1,5 @@ +insert into Game (id, name) values (1, 'Game 1'); +insert into Game (id, name) values (2, 'Game 2'); +insert into Player (game_id, name, id) values (null, 'Player 1', 1); +insert into Player (game_id, name, id) values (null, 'Player 2', 2); +insert into Player (game_id, name, id) values (null, 'Player 3', 3); \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/drop-db.sql b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/drop-db.sql new file mode 100644 index 0000000000..275324fcae --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/drop-db.sql @@ -0,0 +1,2 @@ +drop table if exists Player; +drop table if exists Game; \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..c2d5bf59ab --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,103 @@ + + + + Hibernate EntityManager Demo + com.baeldung.hibernate.pojo.Movie + true + + + + + + + + + + + + EntityManager getReference persistence unit + com.baeldung.hibernate.entitymanager.getreference.Game + com.baeldung.hibernate.entitymanager.getreference.Player + true + + + + + + + + + + + + + + + + + + + EntityManager getReference persistence unit + com.baeldung.hibernate.entitymanager.getreference.Game + com.baeldung.hibernate.entitymanager.getreference.Player + true + + + + + + + + + + + + + + + + + + + + + + + + + EntityManager getReference persistence unit + com.baeldung.hibernate.entitymanager.getreference.Game + com.baeldung.hibernate.entitymanager.getreference.Player + true + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/init_database.sql b/persistence-modules/hibernate-jpa/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/spring-boot-autoconfiguration/src/main/resources/logback.xml b/persistence-modules/hibernate-jpa/src/main/resources/logback.xml similarity index 100% rename from spring-boot-autoconfiguration/src/main/resources/logback.xml rename to persistence-modules/hibernate-jpa/src/main/resources/logback.xml diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java new file mode 100644 index 0000000000..e8e6aeed7c --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java @@ -0,0 +1,194 @@ +package com.baeldung.hibernate.entitymanager.getreference; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import org.junit.jupiter.api.*; +import org.slf4j.LoggerFactory; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class GetReferenceH2IntegrationTest { + + private static EntityManagerFactory entityManagerFactory; + private static EntityManager entityManager; + + private static final PrintStream SystemOut = System.out; + private static OutputStream output; + + @BeforeAll + public static void setup() { + // close some specific loggers so that we can clearly see Hibernate: SQL queries + ((Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.type.descriptor.sql")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.stat")).setLevel(Level.OFF); + + entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.entitymanager.game_player_h2"); + entityManager = entityManagerFactory.createEntityManager(); + entityManager.getTransaction().begin(); + + entityManager.persist(new Game(1L, "Game 1")); + entityManager.persist(new Game(2L, "Game 2")); + entityManager.persist(new Player(1L, "Player 1")); + entityManager.persist(new Player(2L, "Player 2")); + entityManager.persist(new Player(3L, "Player 3")); + + entityManager.getTransaction().commit(); + entityManager.clear(); + entityManager.close(); + } + + private void runInTransaction(Runnable task) { + // We create new persistence context for each test method to discard Hibernate first level cache. + // So that we can see the behavior of getReference() method in a non-cached environment. + entityManager = entityManagerFactory.createEntityManager(); + entityManager.getTransaction().begin(); + task.run(); + entityManager.getTransaction().commit(); + // In any case, we use clear() and close() to make all the managed entities detached and cleared. + // So, we can be sure we test always on a clear persistence context. + entityManager.clear(); + entityManager.close(); + } + + @BeforeEach + public void beforeEach() { + // stubbing System.out printStream + output = new ByteArrayOutputStream(); + System.setOut(new PrintStream(output)); + } + + @AfterEach + public void afterEach() { + System.setOut(SystemOut); + // we print to see original output after each test method + System.out.print(output.toString()); + } + + @AfterAll + public static void tearDown() { + entityManagerFactory.close(); + } + + @Test + public void whenUsingFindMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.find(Game.class, 1L); + game1.setName("Game Updated 1"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.getReference(Game.class, 1L); + game1.setName("Game Updated 2"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player2 = entityManager.find(Player.class, 2L); + entityManager.remove(player2); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player3 = entityManager.getReference(Player.class, 3L); + entityManager.remove(player3); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToUpdatePlayersGame_thenExecutesSelectForGame() { + + runInTransaction((() -> { + Game game1 = entityManager.find(Game.class, 1L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game1); + + entityManager.persist(player1); + })); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdatePlayersGame_thenDoesNotExecuteSelectForGame() { + + runInTransaction(() -> { + Game game2 = entityManager.getReference(Game.class, 2L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game2); + + entityManager.persist(player1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + +} diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java new file mode 100644 index 0000000000..2b7c5e8119 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java @@ -0,0 +1,185 @@ +package com.baeldung.hibernate.entitymanager.getreference; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import org.junit.jupiter.api.*; +import org.slf4j.LoggerFactory; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * We need to have a running MySQL instance and a schema named "baeldung" ready in order to execute this integration test + */ +public class GetReferenceMySQLManualTest { + + private static EntityManagerFactory entityManagerFactory; + private static EntityManager entityManager; + + private static final PrintStream SystemOut = System.out; + private static OutputStream output; + + @BeforeAll + public static void setup() { + // close some specific loggers so that we can clearly see Hibernate: SQL queries + ((Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.type.descriptor.sql")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.stat")).setLevel(Level.OFF); + + entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.entitymanager.game_player_mysql"); + } + + private void runInTransaction(Runnable task) { + // We create new persistence context for each test method to discard Hibernate first level cache. + // So that we can see the behavior of getReference() method in a non-cached environment. + entityManager = entityManagerFactory.createEntityManager(); + entityManager.getTransaction().begin(); + task.run(); + entityManager.getTransaction().commit(); + // In any case, we use clear() and close() to make all the managed entities detached and cleared. + // So, we can be sure we test always on a clear persistence context. + entityManager.clear(); + entityManager.close(); + } + + @BeforeEach + public void beforeEach() { + // stubbing System.out printStream + output = new ByteArrayOutputStream(); + System.setOut(new PrintStream(output)); + } + + @AfterEach + public void afterEach() { + System.setOut(SystemOut); + // we print to see original output after each test method + System.out.print(output.toString()); + } + + @AfterAll + public static void tearDown() { + entityManagerFactory.close(); + } + + @Test + public void whenUsingFindMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.find(Game.class, 1L); + game1.setName("Game Updated 1"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.getReference(Game.class, 1L); + game1.setName("Game Updated 2"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player2 = entityManager.find(Player.class, 2L); + entityManager.remove(player2); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player3 = entityManager.getReference(Player.class, 3L); + entityManager.remove(player3); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToUpdatePlayersGame_thenExecutesSelectForGame() { + + runInTransaction((() -> { + Game game1 = entityManager.find(Game.class, 1L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game1); + + entityManager.persist(player1); + })); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdatePlayersGame_thenDoesNotExecuteSelectForGame() { + + runInTransaction(() -> { + Game game2 = entityManager.getReference(Game.class, 2L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game2); + + entityManager.persist(player1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + +} diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java new file mode 100644 index 0000000000..17f6b10b8a --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java @@ -0,0 +1,185 @@ +package com.baeldung.hibernate.entitymanager.getreference; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import org.junit.jupiter.api.*; +import org.slf4j.LoggerFactory; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * We need to have a running PostgreSQL instance in order to execute this integration test + */ +public class GetReferencePostgreSQLManualTest { + + private static EntityManagerFactory entityManagerFactory; + private static EntityManager entityManager; + + private static final PrintStream SystemOut = System.out; + private static OutputStream output; + + @BeforeAll + public static void setup() { + // close some specific loggers so that we can clearly see Hibernate: SQL queries + ((Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.type.descriptor.sql")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.stat")).setLevel(Level.OFF); + + entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.entitymanager.game_player_postgresql"); + } + + private void runInTransaction(Runnable task) { + // We create new persistence context for each test method to discard Hibernate first level cache. + // So that we can see the behavior of getReference() method in a non-cached environment. + entityManager = entityManagerFactory.createEntityManager(); + entityManager.getTransaction().begin(); + task.run(); + entityManager.getTransaction().commit(); + // In any case, we use clear() and close() to make all the managed entities detached and cleared. + // So, we can be sure we test always on a clear persistence context. + entityManager.clear(); + entityManager.close(); + } + + @BeforeEach + public void beforeEach() { + // stubbing System.out printStream + output = new ByteArrayOutputStream(); + System.setOut(new PrintStream(output)); + } + + @AfterEach + public void afterEach() { + System.setOut(SystemOut); + // we print to see original output after each test method + System.out.print(output.toString()); + } + + @AfterAll + public static void tearDown() { + entityManagerFactory.close(); + } + + @Test + public void whenUsingFindMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.find(Game.class, 1L); + game1.setName("Game Updated 1"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.getReference(Game.class, 1L); + game1.setName("Game Updated 2"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player2 = entityManager.find(Player.class, 2L); + entityManager.remove(player2); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player3 = entityManager.getReference(Player.class, 3L); + entityManager.remove(player3); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToUpdatePlayersGame_thenExecutesSelectForGame() { + + runInTransaction((() -> { + Game game1 = entityManager.find(Game.class, 1L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game1); + + entityManager.persist(player1); + })); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdatePlayersGame_thenDoesNotExecuteSelectForGame() { + + runInTransaction(() -> { + Game game2 = entityManager.getReference(Game.class, 2L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game2); + + entityManager.persist(player1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-2/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-namedquery.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-namedquery.properties rename to persistence-modules/hibernate-jpa/src/test/resources/hibernate-namedquery.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties rename to persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties diff --git a/persistence-modules/hibernate-jpa/src/test/resources/hibernate.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-jpa/src/test/resources/profile.png b/persistence-modules/hibernate-jpa/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-jpa/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 5bbdeecbea..b5d0cb2f99 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -7,5 +7,9 @@ This module contains articles about Object-relational Mapping (ORM) with Hiberna - [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) - [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) - [Hibernate Validator Specific Constraints](https://www.baeldung.com/hibernate-validator-constraints) -- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) -- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) +- [Dynamic Mapping with Hibernate](https://www.baeldung.com/hibernate-dynamic-mapping) +- [Hibernate Inheritance Mapping](https://www.baeldung.com/hibernate-inheritance) +- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) +- [Hibernate – Mapping Date and Time](https://www.baeldung.com/hibernate-date-time) +- [Mapping LOB Data in Hibernate](https://www.baeldung.com/hibernate-lob) +- [FetchMode in Hibernate](https://www.baeldung.com/hibernate-fetchmode) diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index a0a2a047e3..4eabc5d298 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -4,14 +4,12 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 hibernate-mapping - 1.0.0-SNAPSHOT hibernate-mapping com.baeldung persistence-modules 1.0.0-SNAPSHOT - .. @@ -53,25 +51,28 @@ ${moneta.version} pom + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + commons-io + commons-io + ${commons-io.version} + + - - hibernate-mapping - - - src/main/resources - true - - - - - 5.3.10.Final + 5.4.12.Final 3.8.0 6.0.16.Final - 3.0.1-b11 + 3.0.1-b11 1.0.3 1.3 + 3.9 + 2.6 diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 7de13db8d3..fbd8bd487b 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,21 +1,48 @@ package com.baeldung.hibernate; -import org.hibernate.SessionFactory; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.service.ServiceRegistry; - import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.util.Properties; -public class HibernateUtil { +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.Phone; +import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.inheritance.Animal; +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.MyProduct; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Pet; +import com.baeldung.hibernate.pojo.inheritance.Vehicle; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; private HibernateUtil() { } + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(""); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + if(propertyFileName.equals("")) propertyFileName = null; + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + public static SessionFactory getSessionFactory(Strategy strategy) { return buildSessionFactory(strategy); } @@ -40,6 +67,35 @@ public class HibernateUtil { } } + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Employee.class); + metadataSources.addAnnotatedClass(Phone.class); + metadataSources.addAnnotatedClass(EntityDescription.class); + metadataSources.addAnnotatedClass(TemporalValues.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(Animal.class); + metadataSources.addAnnotatedClass(Bag.class); + metadataSources.addAnnotatedClass(Book.class); + metadataSources.addAnnotatedClass(Car.class); + metadataSources.addAnnotatedClass(MyEmployee.class); + metadataSources.addAnnotatedClass(MyProduct.class); + metadataSources.addAnnotatedClass(Pen.class); + metadataSources.addAnnotatedClass(Pet.class); + metadataSources.addAnnotatedClass(Vehicle.class); + + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + private static ServiceRegistry configureServiceRegistry() throws IOException { Properties properties = getProperties(); @@ -51,7 +107,7 @@ public class HibernateUtil { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() - .getResource("hibernate.properties"); + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream); } diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(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 List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java index 5997602205..5589601da8 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java @@ -1,4 +1,4 @@ -package com.baeldung.fetchMode; +package com.baeldung.hibernate.fetchMode; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java index c031972830..aa9c517321 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java @@ -1,4 +1,4 @@ -package com.baeldung.fetchMode; +package com.baeldung.hibernate.fetchMode; import javax.persistence.*; diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java new file mode 100644 index 0000000000..e9732b2b67 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java @@ -0,0 +1,87 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.*; + +import javax.persistence.Entity; +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Where(clause = "deleted = false") +@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int")) +@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit") +public class Employee implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private long grossIncome; + + private int taxInPercents; + + private boolean deleted; + + public long getTaxJavaWay() { + return grossIncome * taxInPercents / 100; + } + + @Formula("grossIncome * taxInPercents / 100") + private long tax; + + @OneToMany + @JoinColumn(name = "employee_id") + @Where(clause = "deleted = false") + private Set phones = new HashSet<>(0); + + public Employee() { + } + + public Employee(long grossIncome, int taxInPercents) { + this.grossIncome = grossIncome; + this.taxInPercents = taxInPercents; + } + + public Integer getId() { + return id; + } + + public long getGrossIncome() { + return grossIncome; + } + + public int getTaxInPercents() { + return taxInPercents; + } + + public long getTax() { + return tax; + } + + public void setId(Integer id) { + this.id = id; + } + + public void setGrossIncome(long grossIncome) { + this.grossIncome = grossIncome; + } + + public void setTaxInPercents(int taxInPercents) { + this.taxInPercents = taxInPercents; + } + + public boolean getDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public Set getPhones() { + return phones; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java new file mode 100644 index 0000000000..131bb73a80 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java @@ -0,0 +1,55 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.Any; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class EntityDescription implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private String description; + + @Any( + metaDef = "EntityDescriptionMetaDef", + metaColumn = @Column(name = "entity_type") + ) + @JoinColumn(name = "entity_id") + private Serializable entity; + + public EntityDescription() { + } + + public EntityDescription(String description, Serializable entity) { + this.description = description; + this.entity = entity; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Serializable getEntity() { + return entity; + } + + public void setEntity(Serializable entity) { + this.entity = entity; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java new file mode 100644 index 0000000000..d923bda5de --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; + +@Entity +public class Phone implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private boolean deleted; + + private String number; + + public Phone() { + } + + public Phone(String number) { + this.number = number; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java new file mode 100644 index 0000000000..607269a267 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.pojo; + +public class Result { + private String employeeName; + + private String departmentName; + + public Result(String employeeName, String departmentName) { + this.employeeName = employeeName; + this.departmentName = departmentName; + } + + public Result() { + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } + + public String getDepartmentName() { + return departmentName; + } + + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java new file mode 100644 index 0000000000..f3fe095cae --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java @@ -0,0 +1,195 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.*; +import java.io.Serializable; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.*; +import java.util.Calendar; + +@Entity +public class TemporalValues implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @Basic + private java.sql.Date sqlDate; + + @Basic + private java.sql.Time sqlTime; + + @Basic + private java.sql.Timestamp sqlTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Date utilDate; + + @Basic + @Temporal(TemporalType.TIME) + private java.util.Date utilTime; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Date utilTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Calendar calendarDate; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Calendar calendarTimestamp; + + @Basic + private java.time.LocalDate localDate; + + @Basic + private java.time.LocalTime localTime; + + @Basic + private java.time.OffsetTime offsetTime; + + @Basic + private java.time.Instant instant; + + @Basic + private java.time.LocalDateTime localDateTime; + + @Basic + private java.time.OffsetDateTime offsetDateTime; + + @Basic + private java.time.ZonedDateTime zonedDateTime; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(Date sqlDate) { + this.sqlDate = sqlDate; + } + + public Time getSqlTime() { + return sqlTime; + } + + public void setSqlTime(Time sqlTime) { + this.sqlTime = sqlTime; + } + + public Timestamp getSqlTimestamp() { + return sqlTimestamp; + } + + public void setSqlTimestamp(Timestamp sqlTimestamp) { + this.sqlTimestamp = sqlTimestamp; + } + + public java.util.Date getUtilDate() { + return utilDate; + } + + public void setUtilDate(java.util.Date utilDate) { + this.utilDate = utilDate; + } + + public java.util.Date getUtilTime() { + return utilTime; + } + + public void setUtilTime(java.util.Date utilTime) { + this.utilTime = utilTime; + } + + public java.util.Date getUtilTimestamp() { + return utilTimestamp; + } + + public void setUtilTimestamp(java.util.Date utilTimestamp) { + this.utilTimestamp = utilTimestamp; + } + + public Calendar getCalendarDate() { + return calendarDate; + } + + public void setCalendarDate(Calendar calendarDate) { + this.calendarDate = calendarDate; + } + + public Calendar getCalendarTimestamp() { + return calendarTimestamp; + } + + public void setCalendarTimestamp(Calendar calendarTimestamp) { + this.calendarTimestamp = calendarTimestamp; + } + + public LocalDate getLocalDate() { + return localDate; + } + + public void setLocalDate(LocalDate localDate) { + this.localDate = localDate; + } + + public LocalTime getLocalTime() { + return localTime; + } + + public void setLocalTime(LocalTime localTime) { + this.localTime = localTime; + } + + public OffsetTime getOffsetTime() { + return offsetTime; + } + + public void setOffsetTime(OffsetTime offsetTime) { + this.offsetTime = offsetTime; + } + + public Instant getInstant() { + return instant; + } + + public void setInstant(Instant instant) { + this.instant = instant; + } + + public LocalDateTime getLocalDateTime() { + return localDateTime; + } + + public void setLocalDateTime(LocalDateTime localDateTime) { + this.localDateTime = localDateTime; + } + + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } + + public void setOffsetDateTime(OffsetDateTime offsetDateTime) { + this.offsetDateTime = offsetDateTime; + } + + public ZonedDateTime getZonedDateTime() { + return zonedDateTime; + } + + public void setZonedDateTime(ZonedDateTime zonedDateTime) { + this.zonedDateTime = zonedDateTime; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java new file mode 100644 index 0000000000..17ffe9b7e1 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.pojo.generator; + +import java.io.Serializable; +import java.util.Properties; +import java.util.stream.Stream; + +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.id.Configurable; +import org.hibernate.id.IdentifierGenerator; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.type.Type; + +public class MyGenerator implements IdentifierGenerator, Configurable { + + private String prefix; + + @Override + public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException { + + String query = String.format("select %s from %s", + session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(), + obj.getClass().getSimpleName()); + + Stream ids = session.createQuery(query).stream(); + + Long max = ids.map(o -> o.replace(prefix + "-", "")) + .mapToLong(Long::parseLong) + .max() + .orElse(0L); + + return prefix + "-" + (max + 1); + } + + @Override + public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException { + prefix = properties.getProperty("prefix"); + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java new file mode 100644 index 0000000000..6fe7f915fc --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.JOINED) +public class Animal { + + @Id + private long animalId; + + private String species; + + public Animal() {} + + public Animal(long animalId, String species) { + this.animalId = animalId; + this.species = species; + } + + public long getAnimalId() { + return animalId; + } + + public void setAnimalId(long animalId) { + this.animalId = animalId; + } + + public String getSpecies() { + return species; + } + + public void setSpecies(String species) { + this.species = species; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java new file mode 100644 index 0000000000..fa6e1b4bef --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.hibernate.annotations.Polymorphism; +import org.hibernate.annotations.PolymorphismType; + +@Entity +@Polymorphism(type = PolymorphismType.EXPLICIT) +public class Bag implements Item { + + @Id + private long bagId; + + private String type; + + public Bag(long bagId, String type) { + this.bagId = bagId; + this.type = type; + } + + public long getBagId() { + return bagId; + } + + public void setBagId(long bagId) { + this.bagId = bagId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java new file mode 100644 index 0000000000..36ca8dd77c --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("1") +public class Book extends MyProduct { + private String author; + + public Book() { + } + + public Book(long productId, String name, String author) { + super(productId, name); + this.author = author; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java new file mode 100644 index 0000000000..49d1f7749a --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class Car extends Vehicle { + private String engine; + + public Car() { + } + + public Car(long vehicleId, String manufacturer, String engine) { + super(vehicleId, manufacturer); + this.engine = engine; + } + + public String getEngine() { + return engine; + } + + public void setEngine(String engine) { + this.engine = engine; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java new file mode 100644 index 0000000000..9656030736 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java @@ -0,0 +1,5 @@ +package com.baeldung.hibernate.pojo.inheritance; + +public interface Item { + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java new file mode 100644 index 0000000000..9a6bce16cf --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java @@ -0,0 +1,22 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class MyEmployee extends Person { + private String company; + + public MyEmployee(long personId, String name, String company) { + super(personId, name); + this.company = company; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java new file mode 100644 index 0000000000..13f04d8904 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +import org.hibernate.annotations.DiscriminatorFormula; + +@Entity +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "product_type", discriminatorType = DiscriminatorType.INTEGER) +// @DiscriminatorFormula("case when author is not null then 1 else 2 end") +public class MyProduct { + @Id + private long productId; + + private String name; + + public MyProduct() { + } + + public MyProduct(long productId, String name) { + super(); + this.productId = productId; + this.name = name; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java new file mode 100644 index 0000000000..32b77e52af --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("2") +public class Pen extends MyProduct { + private String color; + + public Pen() { + } + + public Pen(long productId, String name, String color) { + super(productId, name); + this.color = color; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java new file mode 100644 index 0000000000..99084b88af --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; + +@MappedSuperclass +public class Person { + + @Id + private long personId; + + private String name; + + public Person() { + } + + public Person(long personId, String name) { + this.personId = personId; + this.name = name; + } + + public long getPersonId() { + return personId; + } + + public void setPersonId(long personId) { + this.personId = personId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java new file mode 100644 index 0000000000..870b3cd684 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.PrimaryKeyJoinColumn; + +@Entity +@PrimaryKeyJoinColumn(name = "petId") +public class Pet extends Animal { + private String name; + + public Pet() { + } + + public Pet(long animalId, String species, String name) { + super(animalId, species); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java new file mode 100644 index 0000000000..b2a920573e --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) +public class Vehicle { + @Id + private long vehicleId; + + private String manufacturer; + + public Vehicle() { + } + + public Vehicle(long vehicleId, String manufacturer) { + this.vehicleId = vehicleId; + this.manufacturer = manufacturer; + } + + public long getVehicleId() { + return vehicleId; + } + + public void setVehicleId(long vehicleId) { + this.vehicleId = vehicleId; + } + + public String getManufacturer() { + return manufacturer; + } + + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java new file mode 100644 index 0000000000..992cda7c1d --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java @@ -0,0 +1,9 @@ +@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int", + metaValues = { + @MetaValue(value = "Employee", targetEntity = Employee.class), + @MetaValue(value = "Phone", targetEntity = Phone.class) + }) +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.AnyMetaDef; +import org.hibernate.annotations.MetaValue; \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java diff --git a/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties b/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-mapping/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-mapping/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate-mapping/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/persistence-modules/hibernate-mapping/src/test/resources/profile.png b/persistence-modules/hibernate-mapping/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-mapping/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-ogm/pom.xml b/persistence-modules/hibernate-ogm/pom.xml index bb15881788..8f42c28eee 100644 --- a/persistence-modules/hibernate-ogm/pom.xml +++ b/persistence-modules/hibernate-ogm/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ @@ -33,12 +32,6 @@ ${narayana-jta.version} - - junit - junit - ${junit.version} - test - org.easytesting fest-assert @@ -47,16 +40,6 @@ - - hibernate-ogm - - - src/main/resources - true - - - - 5.4.0.Final 1.4 diff --git a/persistence-modules/hibernate-queries/README.md b/persistence-modules/hibernate-queries/README.md new file mode 100644 index 0000000000..61d94e32de --- /dev/null +++ b/persistence-modules/hibernate-queries/README.md @@ -0,0 +1,10 @@ +## Hibernate Queries + +This module contains articles about use of Queries in Hibernate. + +### Relevant articles: + +- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel) +- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) +- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) +- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml new file mode 100644 index 0000000000..a439ded9df --- /dev/null +++ b/persistence-modules/hibernate-queries/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + hibernate-queries + 0.0.1-SNAPSHOT + hibernate-queries + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + org.opengeo + geodb + ${geodb.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk-jmh.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 0.9 + 1.21 + + + diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..58724e690c --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,73 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.customtypes.LocalDateStringType; +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .applyBasicType(LocalDateStringType.INSTANCE) + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public 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; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java new file mode 100644 index 0000000000..56be9e693f --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.type.LocalDateType; +import org.hibernate.type.descriptor.WrapperOptions; +import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; +import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; +import org.hibernate.type.descriptor.java.MutabilityPlan; + +import java.time.LocalDate; + +public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor { + + public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor(); + + public LocalDateStringJavaDescriptor() { + super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE); + } + + @Override + public String toString(LocalDate value) { + return LocalDateType.FORMATTER.format(value); + } + + @Override + public LocalDate fromString(String string) { + return LocalDate.from(LocalDateType.FORMATTER.parse(string)); + } + + @Override + public X unwrap(LocalDate value, Class type, WrapperOptions options) { + + if (value == null) + return null; + + if (String.class.isAssignableFrom(type)) + return (X) LocalDateType.FORMATTER.format(value); + + throw unknownUnwrap(type); + } + + @Override + public LocalDate wrap(X value, WrapperOptions options) { + if (value == null) + return null; + + if(String.class.isInstance(value)) + return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value)); + + throw unknownWrap(value.getClass()); + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java new file mode 100644 index 0000000000..c8d37073e8 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.dialect.Dialect; +import org.hibernate.type.AbstractSingleColumnStandardBasicType; +import org.hibernate.type.DiscriminatorType; +import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor; +import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; + +import java.time.LocalDate; + +public class LocalDateStringType extends AbstractSingleColumnStandardBasicType implements DiscriminatorType { + + public static final LocalDateStringType INSTANCE = new LocalDateStringType(); + + public LocalDateStringType() { + super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); + } + + @Override + public String getName() { + return "LocalDateString"; + } + + @Override + public LocalDate stringToObject(String xml) throws Exception { + return fromString(xml); + } + + @Override + public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception { + return '\'' + toString(value) + '\''; + } + +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(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 List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/main/resources/init_database.sql b/persistence-modules/hibernate-queries/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/logback.xml b/persistence-modules/hibernate-queries/src/main/resources/logback.xml similarity index 100% rename from spring-boot-bootstrap/src/main/resources/logback.xml rename to persistence-modules/hibernate-queries/src/main/resources/logback.xml diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java diff --git a/persistence-modules/hibernate-queries/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate-customtypes.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/hibernate-customtypes.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-queries/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate-namedquery.properties new file mode 100644 index 0000000000..457f965347 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/hibernate-namedquery.properties @@ -0,0 +1,9 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/main/resources/init_database.sql' +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/resources/hibernate.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-queries/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-queries/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate-queries/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/persistence-modules/hibernate-queries/src/test/resources/profile.png b/persistence-modules/hibernate-queries/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-queries/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate5-2/README.md b/persistence-modules/hibernate5-2/README.md deleted file mode 100644 index 0b6be27410..0000000000 --- a/persistence-modules/hibernate5-2/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Hibernate 5 - -This module contains articles about Hibernate 5. - -### Relevant Articles: -- [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set) -- [FetchMode in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-fetchmode) -- [[<-- Prev]](/hibernate5) \ No newline at end of file diff --git a/persistence-modules/hibernate5-2/pom.xml b/persistence-modules/hibernate5-2/pom.xml deleted file mode 100644 index dfee4bb81e..0000000000 --- a/persistence-modules/hibernate5-2/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - 4.0.0 - hibernate5-2 - 0.1-SNAPSHOT - hibernate5-2 - jar - Hibernate tutorial illustrating the use of named parameters - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - - - - - org.hibernate - hibernate-core - 5.4.7.Final - - - org.springframework.boot - spring-boot-starter-web - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-thymeleaf - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-data-jpa - ${spring-boot.version} - - - com.zaxxer - HikariCP - - - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot.version} - - - - com.h2database - h2 - 1.4.200 - - - - org.apache.commons - commons-lang3 - 3.8.1 - - - - - true - 2.1.7.RELEASE - - - diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index d1bfe897f6..bd437c80eb 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -1,41 +1,15 @@ ## Hibernate 5 -This module contains articles about Hibernate 5. +This module contains articles about Hibernate 5. Let's not add more articles here, we should not be creating a -2 out of it. Please add to other existing hibernate-* modules, or create a new one. ### Relevant articles: -- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) -- [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers) -- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time) -- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance) -- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy) -- [Introduction to Hibernate Spatial](http://www.baeldung.com/hibernate-spatial) -- [Hibernate Interceptors](http://www.baeldung.com/hibernate-interceptor) -- [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) +- [An Overview of Identifiers in Hibernate](https://www.baeldung.com/hibernate-identifiers) +- [Hibernate Interceptors](https://www.baeldung.com/hibernate-interceptor) - [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle) -- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) -- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) - [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy) - [Proxy in Hibernate load() Method](https://www.baeldung.com/hibernate-proxy-load-method) -- [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types) -- [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions) -- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) - [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api) -- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel) - [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager) -- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) -- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) -- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) - [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) -- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) -- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) -- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) -- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) -- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) -- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) -- [[Next -->]](/hibernate5-2) \ No newline at end of file +- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) \ No newline at end of file diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index ec06136f9c..7f04abc09f 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ @@ -41,11 +40,6 @@ geodb ${geodb.version} - - org.hibernate - hibernate-c3p0 - ${hibernate.version} - mysql mysql-connector-java @@ -66,44 +60,14 @@ jackson-databind ${jackson.version} - - net.bytebuddy - byte-buddy - ${byte-buddy.version} - - - org.hibernate - hibernate-jpamodelgen - ${hibernate.version} - - - org.openjdk.jmh - jmh-core - ${openjdk-jmh.version} - org.openjdk.jmh jmh-generator-annprocess ${openjdk-jmh.version} - - javax.xml.bind - jaxb-api - ${jaxb-api.version} - - - hibernate5 - - - src/test/resources - true - - - - geodb-repo @@ -113,14 +77,12 @@ - 5.3.7.Final + 5.4.12.Final 6.0.6 2.2.3 3.8.0 1.21 0.9 - 1.9.5 - 2.3.0 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 137fc4f0bd..11a59c9cf0 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -12,25 +12,13 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; -import com.baeldung.hibernate.customtypes.LocalDateStringType; -import com.baeldung.hibernate.customtypes.OfficeEmployee; import com.baeldung.hibernate.entities.DeptEmployee; -import com.baeldung.hibernate.joincolumn.Email; -import com.baeldung.hibernate.joincolumn.Office; -import com.baeldung.hibernate.joincolumn.OfficeAddress; -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.Course; import com.baeldung.hibernate.pojo.Employee; import com.baeldung.hibernate.pojo.EntityDescription; import com.baeldung.hibernate.pojo.OrderEntry; import com.baeldung.hibernate.pojo.OrderEntryIdClass; import com.baeldung.hibernate.pojo.OrderEntryPK; -import com.baeldung.hibernate.pojo.Person; import com.baeldung.hibernate.pojo.Phone; import com.baeldung.hibernate.pojo.PointEntity; import com.baeldung.hibernate.pojo.PolygonEntity; @@ -88,7 +76,6 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(MyEmployee.class); metadataSources.addAnnotatedClass(MyProduct.class); metadataSources.addAnnotatedClass(Pen.class); - metadataSources.addAnnotatedClass(Person.class); metadataSources.addAnnotatedClass(Animal.class); metadataSources.addAnnotatedClass(Pet.class); metadataSources.addAnnotatedClass(Vehicle.class); @@ -96,26 +83,11 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Bag.class); metadataSources.addAnnotatedClass(PointEntity.class); metadataSources.addAnnotatedClass(PolygonEntity.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class); - metadataSources.addAnnotatedClass(Individual.class); - metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class); - metadataSources.addAnnotatedClass(PessimisticLockingStudent.class); - metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); - 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); - metadataSources.addAnnotatedClass(OfficeEmployee.class); metadataSources.addAnnotatedClass(Post.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); - metadataSources.addAnnotatedClass(Email.class); - metadataSources.addAnnotatedClass(Office.class); - metadataSources.addAnnotatedClass(OfficeAddress.class); Metadata metadata = metadataSources.getMetadataBuilder() - .applyBasicType(LocalDateStringType.INSTANCE) .build(); return metadata.getSessionFactoryBuilder() diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java deleted file mode 100644 index c2f276472e..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.hibernate.onetoone; - -import com.baeldung.hibernate.customtypes.LocalDateStringType; -import org.hibernate.SessionFactory; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.service.ServiceRegistry; - -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URL; -import java.util.Properties; - -public class HibernateUtil { - private static SessionFactory sessionFactory; - - private HibernateUtil() { - } - - public static SessionFactory getSessionFactory(Strategy strategy) { - return buildSessionFactory(strategy); - } - - private static SessionFactory buildSessionFactory(Strategy strategy) { - try { - ServiceRegistry serviceRegistry = configureServiceRegistry(); - - MetadataSources metadataSources = new MetadataSources(serviceRegistry); - - for (Class entityClass : strategy.getEntityClasses()) { - metadataSources.addAnnotatedClass(entityClass); - } - - Metadata metadata = metadataSources.getMetadataBuilder() - .applyBasicType(LocalDateStringType.INSTANCE) - .build(); - - return metadata.getSessionFactoryBuilder() - .build(); - } catch (IOException ex) { - throw new ExceptionInInitializerError(ex); - } - } - - - private static ServiceRegistry configureServiceRegistry() throws IOException { - Properties properties = getProperties(); - return new StandardServiceRegistryBuilder().applySettings(properties) - .build(); - } - - private static Properties getProperties() throws IOException { - Properties properties = new Properties(); - URL propertiesURL = Thread.currentThread() - .getContextClassLoader() - .getResource("hibernate.properties"); - try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { - properties.load(inputStream); - } - return properties; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java index 736abde866..7a88a8bedc 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -1,12 +1,13 @@ package com.baeldung.hibernate.pojo; -import com.vividsolutions.jts.geom.Point; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import org.locationtech.jts.geom.Point; + @Entity public class PointEntity { diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java index 69208c8cd4..3144a88a16 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -1,11 +1,11 @@ package com.baeldung.hibernate.pojo; -import com.vividsolutions.jts.geom.Polygon; - import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import org.locationtech.jts.geom.Polygon; + @Entity public class PolygonEntity { diff --git a/persistence-modules/influxdb/pom.xml b/persistence-modules/influxdb/pom.xml index 7531ad8217..23ae64dca1 100644 --- a/persistence-modules/influxdb/pom.xml +++ b/persistence-modules/influxdb/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index 6628a393fa..091efaeff4 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -3,14 +3,12 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 java-cassandra - 1.0.0-SNAPSHOT java-cassandra com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + persistence-modules + 1.0.0-SNAPSHOT @@ -20,6 +18,12 @@ cassandra-driver-core ${cassandra-driver-core.version} true + + + com.google.guava + guava + + @@ -40,26 +44,13 @@ java-driver-query-builder ${datastax-cassandra.version} - - - io.netty - netty-handler - ${io-netty.version} - - - - java-cassandra - - 3.1.2 3.1.1.0 4.1.0 - 4.1.34.Final - 18.0 diff --git a/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml b/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml new file mode 100644 index 0000000000..59687444d0 --- /dev/null +++ b/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml @@ -0,0 +1,51 @@ +cluster_name: 'Test Cluster' +hinted_handoff_enabled: true +max_hint_window_in_ms: 10800000 +hinted_handoff_throttle_in_kb: 1024 +max_hints_delivery_threads: 2 +hints_directory: target/embeddedCassandra/hints +authenticator: AllowAllAuthenticator +authorizer: AllowAllAuthorizer +permissions_validity_in_ms: 2000 +partitioner: RandomPartitioner +data_file_directories: + - target/embeddedCassandra/data +commitlog_directory: target/embeddedCassandra/commitlog +cdc_raw_directory: target/embeddedCassandra/cdc +disk_failure_policy: stop +key_cache_size_in_mb: +key_cache_save_period: 14400 +row_cache_size_in_mb: 0 +row_cache_save_period: 0 +saved_caches_directory: target/embeddedCassandra/saved_caches +commitlog_sync: periodic +commitlog_sync_period_in_ms: 10000 +commitlog_segment_size_in_mb: 32 +concurrent_reads: 32 +concurrent_writes: 32 +trickle_fsync: false +trickle_fsync_interval_in_kb: 10240 +thrift_framed_transport_size_in_mb: 15 +thrift_max_message_length_in_mb: 16 +incremental_backups: false +snapshot_before_compaction: false +auto_snapshot: false +column_index_size_in_kb: 64 +compaction_throughput_mb_per_sec: 16 +read_request_timeout_in_ms: 5000 +range_request_timeout_in_ms: 10000 +write_request_timeout_in_ms: 2000 +cas_contention_timeout_in_ms: 1000 +truncate_request_timeout_in_ms: 60000 +request_timeout_in_ms: 10000 +cross_node_timeout: false +endpoint_snitch: SimpleSnitch +dynamic_snitch_update_interval_in_ms: 100 +dynamic_snitch_reset_interval_in_ms: 600000 +dynamic_snitch_badness_threshold: 0.1 +request_scheduler: org.apache.cassandra.scheduler.NoScheduler +index_interval: 128 +seed_provider: + - class_name: org.apache.cassandra.locator.SimpleSeedProvider + parameters: + - seeds: "127.0.0.1" diff --git a/persistence-modules/java-cockroachdb/pom.xml b/persistence-modules/java-cockroachdb/pom.xml index 750cbfce4c..e8c6365ca3 100644 --- a/persistence-modules/java-cockroachdb/pom.xml +++ b/persistence-modules/java-cockroachdb/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/java-jdbi/pom.xml b/persistence-modules/java-jdbi/pom.xml index 0d978dc164..eb0de45593 100644 --- a/persistence-modules/java-jdbi/pom.xml +++ b/persistence-modules/java-jdbi/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/java-jpa-2/README.md b/persistence-modules/java-jpa-2/README.md index 1c34ef2999..9d46c0d814 100644 --- a/persistence-modules/java-jpa-2/README.md +++ b/persistence-modules/java-jpa-2/README.md @@ -5,7 +5,7 @@ This module contains articles about the Java Persistence API (JPA) in Java. ### Relevant Articles - [JPA Query Parameters Usage](https://www.baeldung.com/jpa-query-parameters) -- [Mapping Entitiy Class Names to SQL Table Names with JPA](https://www.baeldung.com/jpa-entity-table-names) +- [Mapping Entity Class Names to SQL Table Names with JPA](https://www.baeldung.com/jpa-entity-table-names) - [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values) - [Types of JPA Queries](https://www.baeldung.com/jpa-queries) - [JPA/Hibernate Projections](https://www.baeldung.com/jpa-hibernate-projections) diff --git a/persistence-modules/java-jpa-2/pom.xml b/persistence-modules/java-jpa-2/pom.xml index cc9e69fcaa..ab5bb39dfc 100644 --- a/persistence-modules/java-jpa-2/pom.xml +++ b/persistence-modules/java-jpa-2/pom.xml @@ -7,9 +7,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../pom.xml @@ -49,6 +48,17 @@ ${postgres.version} runtime + + com.querydsl + querydsl-apt + ${querydsl.version} + provided + + + com.querydsl + querydsl-jpa + ${querydsl.version} + org.assertj @@ -63,7 +73,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.5.1 + ${maven-compiler-plugin.version} -proc:none @@ -71,7 +81,7 @@ org.bsc.maven maven-processor-plugin - 3.3.3 + ${maven-processor-plugin.version} process @@ -91,7 +101,7 @@ org.codehaus.mojo build-helper-maven-plugin - 3.0.0 + ${build-helper-maven-plugin.version} add-source @@ -102,20 +112,41 @@ target/metamodel + ${project.build.directory}/generated-sources/java/ + + com.mysema.maven + apt-maven-plugin + 1.1.3 + + + + process + + + target/generated-sources/java + com.querydsl.apt.jpa.JPAAnnotationProcessor + + + + - 5.4.0.Final - 2.7.4-RC1 + 5.4.14.Final + 2.7.4 42.2.5 2.2 3.11.1 + 3.5.1 + 3.3.3 + 3.0.0 + 4.3.1 - \ No newline at end of file + diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Cocktail.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Cocktail.java new file mode 100644 index 0000000000..96310c1cc5 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Cocktail.java @@ -0,0 +1,90 @@ +package com.baeldung.jpa.unrelated.entities; + +import org.hibernate.annotations.Fetch; +import org.hibernate.annotations.FetchMode; +import org.hibernate.annotations.NotFound; +import org.hibernate.annotations.NotFoundAction; + +import javax.persistence.*; +import java.util.List; +import java.util.Objects; + +@Entity +@Table(name = "menu") +public class Cocktail { + @Id + @Column(name = "cocktail_name") + private String name; + + @Column + private double price; + + @Column(name = "category") + private String category; + + @OneToOne + @NotFound(action = NotFoundAction.IGNORE) + @JoinColumn(name = "cocktail_name", + referencedColumnName = "cocktail", + insertable = false, updatable = false, + foreignKey = @javax.persistence + .ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) + private Recipe recipe; + + @OneToMany(fetch = FetchType.LAZY) + @NotFound(action = NotFoundAction.IGNORE) + @JoinColumn( + name = "cocktail", + referencedColumnName = "cocktail_name", + insertable = false, + updatable = false, + foreignKey = @javax.persistence + .ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) + private List recipeList; + + public Cocktail() { + } + + public Cocktail(String name, double price, String baseIngredient) { + this.name = name; + this.price = price; + this.category = baseIngredient; + } + + public String getName() { + return name; + } + + public double getPrice() { + return price; + } + + public String getCategory() { + return category; + } + + public Recipe getRecipe() { + return recipe; + } + + public List getRecipeList() { + return recipeList; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Cocktail cocktail = (Cocktail) o; + return Double.compare(cocktail.price, price) == 0 && + Objects.equals(name, cocktail.name) && + Objects.equals(category, cocktail.category); + } + + @Override + public int hashCode() { + return Objects.hash(name, price, category); + } +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/MultipleRecipe.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/MultipleRecipe.java new file mode 100644 index 0000000000..8664d6fd7f --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/MultipleRecipe.java @@ -0,0 +1,71 @@ +package com.baeldung.jpa.unrelated.entities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.util.Objects; + +@Entity +@Table(name = "multiple_recipes") +public class MultipleRecipe { + @Id + @Column(name = "id") + private Long id; + + @Column(name = "cocktail") + private String cocktail; + + @Column(name = "instructions") + private String instructions; + + @Column(name = "base_ingredient") + private String baseIngredient; + + public MultipleRecipe() { + } + + public MultipleRecipe(Long id, String cocktail, + String instructions, String baseIngredient) { + this.id = id; + this.cocktail = cocktail; + this.instructions = instructions; + this.baseIngredient = baseIngredient; + } + + public Long getId() { + return id; + } + + public String getCocktail() { + return cocktail; + } + + public String getInstructions() { + return instructions; + } + + public String getBaseIngredient() { + return baseIngredient; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + MultipleRecipe that = (MultipleRecipe) o; + + return Objects.equals(id, that.id) && + Objects.equals(cocktail, that.cocktail) && + Objects.equals(instructions, that.instructions) && + Objects.equals(baseIngredient, that.baseIngredient); + } + + @Override + public int hashCode() { + return Objects.hash(id, cocktail, + instructions, baseIngredient); + } +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Recipe.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Recipe.java new file mode 100644 index 0000000000..4b3d200b60 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Recipe.java @@ -0,0 +1,50 @@ +package com.baeldung.jpa.unrelated.entities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.util.Objects; + +@Entity +@Table(name="recipes") +public class Recipe { + @Id + @Column(name = "cocktail") + private String cocktail; + + @Column + private String instructions; + + public Recipe() { + } + + public Recipe(String cocktail, String instructions) { + this.cocktail = cocktail; + this.instructions = instructions; + } + + public String getCocktail() { + return cocktail; + } + + public String getInstructions() { + return instructions; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Recipe recipe = (Recipe) o; + return Objects.equals(cocktail, recipe.cocktail) + && Objects.equals(instructions, recipe.instructions); + } + + @Override + public int hashCode() { + return Objects.hash(cocktail, instructions); + } +} diff --git a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml index 11e007973f..eec7f7cf6e 100644 --- a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml @@ -162,5 +162,26 @@ value="false" /> - - \ No newline at end of file + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.unrelated.entities.Cocktail + com.baeldung.jpa.unrelated.entities.Recipe + com.baeldung.jpa.unrelated.entities.MultipleRecipe + true + + + + + + + + + + + + diff --git a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/unrelated/entities/UnrelatedEntitiesUnitTest.java b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/unrelated/entities/UnrelatedEntitiesUnitTest.java new file mode 100644 index 0000000000..044e59b16e --- /dev/null +++ b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/unrelated/entities/UnrelatedEntitiesUnitTest.java @@ -0,0 +1,189 @@ +package com.baeldung.jpa.unrelated.entities; + +import javax.persistence.*; + +import com.querydsl.jpa.impl.JPAQuery; +import org.junit.jupiter.api.*; + +import java.util.List; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.*; + +public class UnrelatedEntitiesUnitTest { + private static EntityManagerFactory entityManagerFactory; + private static EntityManager entityManager; + private static Cocktail mojito; + private static Cocktail ginTonic; + + @BeforeAll + public static void setup() { + entityManagerFactory = Persistence.createEntityManagerFactory("jpa-h2-unrelated-entities"); + entityManager = entityManagerFactory.createEntityManager(); + mojito = new Cocktail("Mojito", 11, "Rum"); + ginTonic = new Cocktail("Gin tonic", 8.50, "Gin"); + entityManager.getTransaction().begin(); + entityManager.persist(mojito); + entityManager.persist(ginTonic); + entityManager.persist(new Recipe(mojito.getName(), "Some instructions")); + entityManager.persist(new MultipleRecipe(1L, mojito.getName(), + "some instructions", mojito.getCategory())); + entityManager.persist(new MultipleRecipe(2L, mojito.getName(), + "some other instructions", mojito.getCategory())); + entityManager.getTransaction().commit(); + } + + @AfterAll + public static void closeSession() { + entityManager.close(); + } + + + @Test + public void givenCocktailsWithRecipe_whenQuerying_thenTheExpectedCocktailsReturned() { + // JPA + Cocktail cocktail = entityManager.createQuery("select c " + + "from Cocktail c join c.recipe", Cocktail.class) + .getSingleResult(); + verifyResult(mojito, cocktail); + + cocktail = entityManager.createQuery("select c " + + "from Cocktail c join Recipe r " + + "on c.name = r.cocktail", Cocktail.class) + .getSingleResult(); + verifyResult(mojito, cocktail); + + // QueryDSL + cocktail = new JPAQuery(entityManager).from(QCocktail.cocktail) + .join(QCocktail.cocktail.recipe) + .fetchOne(); + verifyResult(mojito, cocktail); + + cocktail = new JPAQuery(entityManager).from(QCocktail.cocktail) + .join(QRecipe.recipe) + .on(QCocktail.cocktail.name.eq(QRecipe.recipe.cocktail)) + .fetchOne(); + verifyResult(mojito, cocktail); + } + + @Test + public void givenCocktailsWithoutRecipe_whenQuerying_thenTheExpectedCocktailsReturned() { + Cocktail cocktail = entityManager.createQuery("select c " + + "from Cocktail c left join c.recipe r " + + "where r is null", Cocktail.class) + .getSingleResult(); + verifyResult(ginTonic, cocktail); + + cocktail = entityManager.createQuery("select c " + + "from Cocktail c left join Recipe r " + + "on c.name = r.cocktail " + + "where r is null", Cocktail.class) + .getSingleResult(); + verifyResult(ginTonic, cocktail); + + QRecipe recipe = new QRecipe("alias"); + cocktail = new JPAQuery(entityManager).from(QCocktail.cocktail) + .leftJoin(QCocktail.cocktail.recipe, recipe) + .where(recipe.isNull()) + .fetchOne(); + verifyResult(ginTonic, cocktail); + + cocktail = new JPAQuery(entityManager).from(QCocktail.cocktail) + .leftJoin(QRecipe.recipe) + .on(QCocktail.cocktail.name.eq(QRecipe.recipe.cocktail)) + .where(QRecipe.recipe.isNull()) + .fetchOne(); + verifyResult(ginTonic, cocktail); + } + + @Test + public void givenCocktailsWithMultipleRecipes_whenQuerying_thenTheExpectedCocktailsReturned() { + // JPQL + Cocktail cocktail = entityManager.createQuery("select c " + + "from Cocktail c join c.recipeList", Cocktail.class) + .getSingleResult(); + verifyResult(mojito, cocktail); + + cocktail = entityManager.createQuery("select c " + + "from Cocktail c join MultipleRecipe mr " + + "on mr.cocktail = c.name", Cocktail.class) + .getSingleResult(); + verifyResult(mojito, cocktail); + + // QueryDSL + cocktail = new JPAQuery(entityManager).from(QCocktail.cocktail) + .join(QCocktail.cocktail.recipeList) + .fetchOne(); + verifyResult(mojito, cocktail); + + cocktail = new JPAQuery(entityManager).from(QCocktail.cocktail) + .join(QMultipleRecipe.multipleRecipe) + .on(QCocktail.cocktail.name.eq(QMultipleRecipe.multipleRecipe.cocktail)) + .fetchOne(); + verifyResult(mojito, cocktail); + } + + @Test + public void givenCocktailsWithoutMultipleRecipes_whenQuerying_thenTheExpectedCocktailsReturned() { + // JPQL + Cocktail cocktail = entityManager.createQuery("select c " + + "from Cocktail c left join c.recipeList r " + + "where r is null", Cocktail.class) + .getSingleResult(); + verifyResult(ginTonic, cocktail); + + cocktail = entityManager.createQuery("select c " + + "from Cocktail c left join MultipleRecipe r " + + "on c.name = r.cocktail " + + "where r is null", Cocktail.class) + .getSingleResult(); + verifyResult(ginTonic, cocktail); + + // QueryDSL + QMultipleRecipe multipleRecipe = new QMultipleRecipe("alias"); + cocktail = new JPAQuery(entityManager).from(QCocktail.cocktail) + .leftJoin(QCocktail.cocktail.recipeList, multipleRecipe) + .where(multipleRecipe.isNull()) + .fetchOne(); + verifyResult(ginTonic, cocktail); + + cocktail = new JPAQuery(entityManager).from(QCocktail.cocktail) + .leftJoin(QMultipleRecipe.multipleRecipe) + .on(QCocktail.cocktail.name.eq(QMultipleRecipe.multipleRecipe.cocktail)) + .where(QMultipleRecipe.multipleRecipe.isNull()) + .fetchOne(); + verifyResult(ginTonic, cocktail); + } + + @Test + public void givenMultipleRecipesWithCocktails_whenQuerying_thenTheExpectedMultipleRecipesReturned() { + Consumer> verifyResult = recipes -> { + assertEquals(2, recipes.size()); + recipes.forEach(r -> assertEquals(mojito.getName(), r.getCocktail())); + }; + + // JPQL + List recipes = entityManager.createQuery("select distinct r " + + "from MultipleRecipe r " + + "join Cocktail c " + + "on r.baseIngredient = c.category", + MultipleRecipe.class).getResultList(); + + verifyResult.accept(recipes); + + // QueryDSL + QCocktail cocktail = QCocktail.cocktail; + QMultipleRecipe multipleRecipe = QMultipleRecipe.multipleRecipe; + recipes = new JPAQuery(entityManager).from(multipleRecipe) + .join(cocktail) + .on(multipleRecipe.baseIngredient.eq(cocktail.category)) + .fetch(); + + verifyResult.accept(recipes); + } + + private void verifyResult(Cocktail expectedCocktail, Cocktail queryResult) { + assertNotNull(queryResult); + assertEquals(expectedCocktail, queryResult); + } +} diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index a979cf7e65..3601721dac 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../pom.xml @@ -107,7 +106,7 @@ 5.4.0.Final - 2.7.4-RC1 + 2.7.4 42.2.5 2.2 3.3.3 diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md index 41d0ad63f8..b79cea6781 100644 --- a/persistence-modules/java-mongodb/README.md +++ b/persistence-modules/java-mongodb/README.md @@ -9,3 +9,6 @@ This module contains articles about MongoDB in Java. - [MongoDB BSON Guide](https://www.baeldung.com/mongodb-bson) - [Geospatial Support in MongoDB](https://www.baeldung.com/mongodb-geospatial-support) - [Introduction to Morphia – Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia) +- [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations) +- [MongoDB BSON to JSON](https://www.baeldung.com/bson-to-json) +- [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json) diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml index 1e59bd9064..d62240927a 100644 --- a/persistence-modules/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ @@ -35,8 +34,6 @@ - 1.8 - 1.8 3.10.1 1.11 1.5.3 diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java index 172c916ad9..4ed2ab8580 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java @@ -1,5 +1,7 @@ package com.baeldung.morphia.domain; +import java.time.LocalDate; +import java.time.LocalDateTime; import java.util.HashSet; import java.util.Set; @@ -29,28 +31,13 @@ public class Book { private double cost; @Reference private Set companionBooks; + @Property + private LocalDateTime publishDate; public Book() { } - public String getTitle() { - return title; - } - - public String getAuthor() { - return author; - } - - public double getCost() { - return cost; - } - - public void addCompanionBooks(Book book) { - if (companionBooks != null) - this.companionBooks.add(book); - } - public Book(String isbn, String title, String author, double cost, Publisher publisher) { this.isbn = isbn; this.title = title; @@ -60,6 +47,71 @@ public class Book { this.companionBooks = new HashSet<>(); } + // Getters and setters ... + public String getIsbn() { + return isbn; + } + + public Book setIsbn(String isbn) { + this.isbn = isbn; + return this; + } + + public String getTitle() { + return title; + } + + public Book setTitle(String title) { + this.title = title; + return this; + } + + public String getAuthor() { + return author; + } + + public Book setAuthor(String author) { + this.author = author; + return this; + } + + public Publisher getPublisher() { + return publisher; + } + + public Book setPublisher(Publisher publisher) { + this.publisher = publisher; + return this; + } + + public double getCost() { + return cost; + } + + public Book setCost(double cost) { + this.cost = cost; + return this; + } + + public LocalDateTime getPublishDate() { + return publishDate; + } + + public Book setPublishDate(LocalDateTime publishDate) { + this.publishDate = publishDate; + return this; + } + + public Set getCompanionBooks() { + return companionBooks; + } + + public Book addCompanionBooks(Book book) { + if (companionBooks != null) + this.companionBooks.add(book); + return this; + } + @Override public String toString() { return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]"; @@ -113,4 +165,4 @@ public class Book { return true; } -} \ No newline at end of file +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/aggregation/AggregationLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/aggregation/AggregationLiveTest.java new file mode 100644 index 0000000000..62ab13563a --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/aggregation/AggregationLiveTest.java @@ -0,0 +1,111 @@ +package com.baeldung.aggregation; + +import static com.mongodb.client.model.Aggregates.count; +import static com.mongodb.client.model.Aggregates.group; +import static com.mongodb.client.model.Aggregates.limit; +import static com.mongodb.client.model.Aggregates.match; +import static com.mongodb.client.model.Aggregates.out; +import static com.mongodb.client.model.Aggregates.project; +import static com.mongodb.client.model.Aggregates.sort; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Arrays; + +import org.bson.Document; +import org.bson.conversions.Bson; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.Accumulators; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.Projections; +import com.mongodb.client.model.Sorts; + +public class AggregationLiveTest { + + private static final String DATABASE = "world"; + private static final String COLLECTION = "countries"; + private static final String DATASET_JSON = "/countrydata.json"; + private static MongoClient mongoClient; + private static MongoDatabase database; + private static MongoCollection collection; + + @BeforeClass + public static void setUpDB() throws IOException { + mongoClient = MongoClients.create(); + database = mongoClient.getDatabase(DATABASE); + collection = database.getCollection(COLLECTION); + + collection.drop(); + + InputStream is = AggregationLiveTest.class.getResourceAsStream(DATASET_JSON); + BufferedReader reader = new BufferedReader(new InputStreamReader(is)); + reader.lines() + .forEach(line -> collection.insertOne(Document.parse(line))); + reader.close(); + } + + @Test + public void givenCountryCollection_whenEnglishSpeakingCountriesCounted_thenNinetyOne() { + Document englishSpeakingCountries = collection.aggregate(Arrays.asList(match(Filters.eq("languages.name", "English")), count())) + .first(); + + assertEquals(91, englishSpeakingCountries.get("count")); + } + + @Test + public void givenCountryCollection_whenAreaSortedDescending_thenSuccess() { + + collection.aggregate(Arrays.asList(sort(Sorts.descending("area")), limit(7), out("largest_seven"))) + .toCollection(); + + MongoCollection largestSeven = database.getCollection("largest_seven"); + + assertEquals(7, largestSeven.countDocuments()); + + Document usa = largestSeven.find(Filters.eq("alpha3Code", "USA")) + .first(); + + assertNotNull(usa); + } + + @Test + public void givenCountryCollection_whenCountedRegionWise_thenMaxInAfrica() { + Document maxCountriedRegion = collection.aggregate(Arrays.asList(group("$region", Accumulators.sum("tally", 1)), sort(Sorts.descending("tally")))) + .first(); + assertTrue(maxCountriedRegion.containsValue("Africa")); + } + + @Test + public void givenCountryCollection_whenNeighborsCalculated_thenMaxIsFifteenInChina() { + Bson borderingCountriesCollection = project(Projections.fields(Projections.excludeId(), Projections.include("name"), Projections.computed("borderingCountries", Projections.computed("$size", "$borders")))); + + int maxValue = collection.aggregate(Arrays.asList(borderingCountriesCollection, group(null, Accumulators.max("max", "$borderingCountries")))) + .first() + .getInteger("max"); + + assertEquals(15, maxValue); + + Document maxNeighboredCountry = collection.aggregate(Arrays.asList(borderingCountriesCollection, match(Filters.eq("borderingCountries", maxValue)))) + .first(); + assertTrue(maxNeighboredCountry.containsValue("China")); + + } + + @AfterClass + public static void cleanUp() { + mongoClient.close(); + } + +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java new file mode 100644 index 0000000000..4e70394069 --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java @@ -0,0 +1,142 @@ +package com.baeldung.bsontojson; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.bson.Document; +import org.bson.json.Converter; +import org.bson.json.JsonMode; +import org.bson.json.JsonWriterSettings; +import org.bson.json.StrictJsonWriter; +import org.bson.types.ObjectId; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.morphia.domain.Book; +import com.baeldung.morphia.domain.Publisher; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoDatabase; + +import dev.morphia.Datastore; +import dev.morphia.Morphia; + +public class BsonToJsonLiveTest { + + private static final String DB_NAME = "library"; + private static Datastore datastore; + + @BeforeClass + public static void setUp() { + Morphia morphia = new Morphia(); + morphia.mapPackage("com.baeldung.morphia"); + datastore = morphia.createDatastore(new MongoClient(), DB_NAME); + datastore.ensureIndexes(); + + datastore.save(new Book() + .setIsbn("isbn") + .setTitle("title") + .setAuthor("author") + .setCost(3.95) + .setPublisher(new Publisher(new ObjectId("fffffffffffffffffffffffa"),"publisher")) + .setPublishDate(LocalDateTime.parse("2020-01-01T18:13:32Z", DateTimeFormatter.ISO_DATE_TIME)) + .addCompanionBooks(new Book().setIsbn("isbn2"))); + } + + @AfterClass + public static void tearDown() { + datastore.delete(datastore.createQuery(Book.class)); + } + + @Test + public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": {\"$date\": 1577898812000}}"; + + assertNotNull(json); + + assertEquals(expectedJson, json); + } + + + @Test + public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(JsonWriterSettings + .builder() + .outputMode(JsonMode.RELAXED) + .build()); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}"; + + assertNotNull(json); + + assertEquals(expectedJson, json); + } + + @Test + public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(JsonWriterSettings + .builder() + .dateTimeConverter(new JsonDateTimeConverter()) + .build()); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": \"2020-01-01T17:13:32Z\"}"; + + assertEquals(expectedJson, json); + + } + +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java new file mode 100644 index 0000000000..46023e363f --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java @@ -0,0 +1,30 @@ +package com.baeldung.bsontojson; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.TimeZone; + +import org.bson.json.Converter; +import org.bson.json.StrictJsonWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JsonDateTimeConverter implements Converter { + + private static final Logger LOGGER = LoggerFactory.getLogger(JsonDateTimeConverter.class); + static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT + .withZone(ZoneId.of("UTC")); + + @Override + public void convert(Long value, StrictJsonWriter writer) { + try { + Instant instant = new Date(value).toInstant(); + String s = DATE_TIME_FORMATTER.format(instant); + writer.writeString(s); + } catch (Exception e) { + LOGGER.error(String.format("Fail to convert offset %d to JSON date", value), e); + } + } +} diff --git a/persistence-modules/java-mongodb/src/test/resources/countrydata.json b/persistence-modules/java-mongodb/src/test/resources/countrydata.json new file mode 100644 index 0000000000..81213c31e7 --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/resources/countrydata.json @@ -0,0 +1,250 @@ +{"name":"Afghanistan","topLevelDomain":[".af"],"alpha2Code":"AF","alpha3Code":"AFG","callingCodes":["93"],"capital":"Kabul","altSpellings":["AF","Afġānistān"],"region":"Asia","subregion":"Southern Asia","population":27657145,"latlng":[33.0,65.0],"demonym":"Afghan","area":652230.0,"gini":27.8,"timezones":["UTC+04:30"],"borders":["IRN","PAK","TKM","UZB","TJK","CHN"],"nativeName":"افغانستان","numericCode":"004","currencies":[{"code":"AFN","name":"Afghan afghani","symbol":"؋"}],"languages":[{"iso639_1":"ps","iso639_2":"pus","name":"Pashto","nativeName":"پښتو"},{"iso639_1":"uz","iso639_2":"uzb","name":"Uzbek","nativeName":"Oʻzbek"},{"iso639_1":"tk","iso639_2":"tuk","name":"Turkmen","nativeName":"Türkmen"}],"translations":{"de":"Afghanistan","es":"Afganistán","fr":"Afghanistan","ja":"アフガニスタン","it":"Afghanistan","br":"Afeganistão","pt":"Afeganistão","nl":"Afghanistan","hr":"Afganistan","fa":"افغانستان"},"flag":"https://restcountries.eu/data/afg.svg","regionalBlocs":[{"acronym":"SAARC","name":"South Asian Association for Regional Cooperation","otherAcronyms":[],"otherNames":[]}],"cioc":"AFG"} +{"name":"Åland Islands","topLevelDomain":[".ax"],"alpha2Code":"AX","alpha3Code":"ALA","callingCodes":["358"],"capital":"Mariehamn","altSpellings":["AX","Aaland","Aland","Ahvenanmaa"],"region":"Europe","subregion":"Northern Europe","population":28875,"latlng":[60.116667,19.9],"demonym":"Ålandish","area":1580.0,"gini":null,"timezones":["UTC+02:00"],"borders":[],"nativeName":"Åland","numericCode":"248","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"sv","iso639_2":"swe","name":"Swedish","nativeName":"svenska"}],"translations":{"de":"Åland","es":"Alandia","fr":"Åland","ja":"オーランド諸島","it":"Isole Aland","br":"Ilhas de Aland","pt":"Ilhas de Aland","nl":"Ålandeilanden","hr":"Ålandski otoci","fa":"جزایر الند"},"flag":"https://restcountries.eu/data/ala.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":""} +{"name":"Albania","topLevelDomain":[".al"],"alpha2Code":"AL","alpha3Code":"ALB","callingCodes":["355"],"capital":"Tirana","altSpellings":["AL","Shqipëri","Shqipëria","Shqipnia"],"region":"Europe","subregion":"Southern Europe","population":2886026,"latlng":[41.0,20.0],"demonym":"Albanian","area":28748.0,"gini":34.5,"timezones":["UTC+01:00"],"borders":["MNE","GRC","MKD","KOS"],"nativeName":"Shqipëria","numericCode":"008","currencies":[{"code":"ALL","name":"Albanian lek","symbol":"L"}],"languages":[{"iso639_1":"sq","iso639_2":"sqi","name":"Albanian","nativeName":"Shqip"}],"translations":{"de":"Albanien","es":"Albania","fr":"Albanie","ja":"アルバニア","it":"Albania","br":"Albânia","pt":"Albânia","nl":"Albanië","hr":"Albanija","fa":"آلبانی"},"flag":"https://restcountries.eu/data/alb.svg","regionalBlocs":[{"acronym":"CEFTA","name":"Central European Free Trade Agreement","otherAcronyms":[],"otherNames":[]}],"cioc":"ALB"} +{"name":"Algeria","topLevelDomain":[".dz"],"alpha2Code":"DZ","alpha3Code":"DZA","callingCodes":["213"],"capital":"Algiers","altSpellings":["DZ","Dzayer","Algérie"],"region":"Africa","subregion":"Northern Africa","population":40400000,"latlng":[28.0,3.0],"demonym":"Algerian","area":2381741.0,"gini":35.3,"timezones":["UTC+01:00"],"borders":["TUN","LBY","NER","ESH","MRT","MLI","MAR"],"nativeName":"الجزائر","numericCode":"012","currencies":[{"code":"DZD","name":"Algerian dinar","symbol":"د.ج"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Algerien","es":"Argelia","fr":"Algérie","ja":"アルジェリア","it":"Algeria","br":"Argélia","pt":"Argélia","nl":"Algerije","hr":"Alžir","fa":"الجزایر"},"flag":"https://restcountries.eu/data/dza.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]},{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"ALG"} +{"name":"American Samoa","topLevelDomain":[".as"],"alpha2Code":"AS","alpha3Code":"ASM","callingCodes":["1684"],"capital":"Pago Pago","altSpellings":["AS","Amerika Sāmoa","Amelika Sāmoa","Sāmoa Amelika"],"region":"Oceania","subregion":"Polynesia","population":57100,"latlng":[-14.33333333,-170.0],"demonym":"American Samoan","area":199.0,"gini":null,"timezones":["UTC-11:00"],"borders":[],"nativeName":"American Samoa","numericCode":"016","currencies":[{"code":"USD","name":"United State Dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"sm","iso639_2":"smo","name":"Samoan","nativeName":"gagana fa'a Samoa"}],"translations":{"de":"Amerikanisch-Samoa","es":"Samoa Americana","fr":"Samoa américaines","ja":"アメリカ領サモア","it":"Samoa Americane","br":"Samoa Americana","pt":"Samoa Americana","nl":"Amerikaans Samoa","hr":"Američka Samoa","fa":"ساموآی آمریکا"},"flag":"https://restcountries.eu/data/asm.svg","regionalBlocs":[],"cioc":"ASA"} +{"name":"Andorra","topLevelDomain":[".ad"],"alpha2Code":"AD","alpha3Code":"AND","callingCodes":["376"],"capital":"Andorra la Vella","altSpellings":["AD","Principality of Andorra","Principat d'Andorra"],"region":"Europe","subregion":"Southern Europe","population":78014,"latlng":[42.5,1.5],"demonym":"Andorran","area":468.0,"gini":null,"timezones":["UTC+01:00"],"borders":["FRA","ESP"],"nativeName":"Andorra","numericCode":"020","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"ca","iso639_2":"cat","name":"Catalan","nativeName":"català"}],"translations":{"de":"Andorra","es":"Andorra","fr":"Andorre","ja":"アンドラ","it":"Andorra","br":"Andorra","pt":"Andorra","nl":"Andorra","hr":"Andora","fa":"آندورا"},"flag":"https://restcountries.eu/data/and.svg","regionalBlocs":[],"cioc":"AND"} +{"name":"Angola","topLevelDomain":[".ao"],"alpha2Code":"AO","alpha3Code":"AGO","callingCodes":["244"],"capital":"Luanda","altSpellings":["AO","República de Angola","ʁɛpublika de an'ɡɔla"],"region":"Africa","subregion":"Middle Africa","population":25868000,"latlng":[-12.5,18.5],"demonym":"Angolan","area":1246700.0,"gini":58.6,"timezones":["UTC+01:00"],"borders":["COG","COD","ZMB","NAM"],"nativeName":"Angola","numericCode":"024","currencies":[{"code":"AOA","name":"Angolan kwanza","symbol":"Kz"}],"languages":[{"iso639_1":"pt","iso639_2":"por","name":"Portuguese","nativeName":"Português"}],"translations":{"de":"Angola","es":"Angola","fr":"Angola","ja":"アンゴラ","it":"Angola","br":"Angola","pt":"Angola","nl":"Angola","hr":"Angola","fa":"آنگولا"},"flag":"https://restcountries.eu/data/ago.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"ANG"} +{"name":"Anguilla","topLevelDomain":[".ai"],"alpha2Code":"AI","alpha3Code":"AIA","callingCodes":["1264"],"capital":"The Valley","altSpellings":["AI"],"region":"Americas","subregion":"Caribbean","population":13452,"latlng":[18.25,-63.16666666],"demonym":"Anguillian","area":91.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Anguilla","numericCode":"660","currencies":[{"code":"XCD","name":"East Caribbean dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Anguilla","es":"Anguilla","fr":"Anguilla","ja":"アンギラ","it":"Anguilla","br":"Anguila","pt":"Anguila","nl":"Anguilla","hr":"Angvila","fa":"آنگویلا"},"flag":"https://restcountries.eu/data/aia.svg","regionalBlocs":[],"cioc":""} +{"name":"Antarctica","topLevelDomain":[".aq"],"alpha2Code":"AQ","alpha3Code":"ATA","callingCodes":["672"],"capital":"","altSpellings":[],"region":"Polar","subregion":"","population":1000,"latlng":[-74.65,4.48],"demonym":"","area":1.4E7,"gini":null,"timezones":["UTC-03:00","UTC+03:00","UTC+05:00","UTC+06:00","UTC+07:00","UTC+08:00","UTC+10:00","UTC+12:00"],"borders":[],"nativeName":"Antarctica","numericCode":"010","currencies":[{"code":"AUD","name":"Australian dollar","symbol":"$"},{"code":"GBP","name":"British pound","symbol":"£"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"ru","iso639_2":"rus","name":"Russian","nativeName":"Русский"}],"translations":{"de":"Antarktika","es":"Antártida","fr":"Antarctique","ja":"南極大陸","it":"Antartide","br":"Antártida","pt":"Antárctida","nl":"Antarctica","hr":"Antarktika","fa":"جنوبگان"},"flag":"https://restcountries.eu/data/ata.svg","regionalBlocs":[],"cioc":""} +{"name":"Antigua and Barbuda","topLevelDomain":[".ag"],"alpha2Code":"AG","alpha3Code":"ATG","callingCodes":["1268"],"capital":"Saint John's","altSpellings":["AG"],"region":"Americas","subregion":"Caribbean","population":86295,"latlng":[17.05,-61.8],"demonym":"Antiguan, Barbudan","area":442.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Antigua and Barbuda","numericCode":"028","currencies":[{"code":"XCD","name":"East Caribbean dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Antigua und Barbuda","es":"Antigua y Barbuda","fr":"Antigua-et-Barbuda","ja":"アンティグア・バーブーダ","it":"Antigua e Barbuda","br":"Antígua e Barbuda","pt":"Antígua e Barbuda","nl":"Antigua en Barbuda","hr":"Antigva i Barbuda","fa":"آنتیگوا و باربودا"},"flag":"https://restcountries.eu/data/atg.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]}],"cioc":"ANT"} +{"name":"Argentina","topLevelDomain":[".ar"],"alpha2Code":"AR","alpha3Code":"ARG","callingCodes":["54"],"capital":"Buenos Aires","altSpellings":["AR","Argentine Republic","República Argentina"],"region":"Americas","subregion":"South America","population":43590400,"latlng":[-34.0,-64.0],"demonym":"Argentinean","area":2780400.0,"gini":44.5,"timezones":["UTC-03:00"],"borders":["BOL","BRA","CHL","PRY","URY"],"nativeName":"Argentina","numericCode":"032","currencies":[{"code":"ARS","name":"Argentine peso","symbol":"$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"},{"iso639_1":"gn","iso639_2":"grn","name":"Guaraní","nativeName":"Avañe'ẽ"}],"translations":{"de":"Argentinien","es":"Argentina","fr":"Argentine","ja":"アルゼンチン","it":"Argentina","br":"Argentina","pt":"Argentina","nl":"Argentinië","hr":"Argentina","fa":"آرژانتین"},"flag":"https://restcountries.eu/data/arg.svg","regionalBlocs":[{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"ARG"} +{"name":"Armenia","topLevelDomain":[".am"],"alpha2Code":"AM","alpha3Code":"ARM","callingCodes":["374"],"capital":"Yerevan","altSpellings":["AM","Hayastan","Republic of Armenia","Հայաստանի Հանրապետություն"],"region":"Asia","subregion":"Western Asia","population":2994400,"latlng":[40.0,45.0],"demonym":"Armenian","area":29743.0,"gini":30.9,"timezones":["UTC+04:00"],"borders":["AZE","GEO","IRN","TUR"],"nativeName":"Հայաստան","numericCode":"051","currencies":[{"code":"AMD","name":"Armenian dram","symbol":null}],"languages":[{"iso639_1":"hy","iso639_2":"hye","name":"Armenian","nativeName":"Հայերեն"},{"iso639_1":"ru","iso639_2":"rus","name":"Russian","nativeName":"Русский"}],"translations":{"de":"Armenien","es":"Armenia","fr":"Arménie","ja":"アルメニア","it":"Armenia","br":"Armênia","pt":"Arménia","nl":"Armenië","hr":"Armenija","fa":"ارمنستان"},"flag":"https://restcountries.eu/data/arm.svg","regionalBlocs":[{"acronym":"EEU","name":"Eurasian Economic Union","otherAcronyms":["EAEU"],"otherNames":[]}],"cioc":"ARM"} +{"name":"Aruba","topLevelDomain":[".aw"],"alpha2Code":"AW","alpha3Code":"ABW","callingCodes":["297"],"capital":"Oranjestad","altSpellings":["AW"],"region":"Americas","subregion":"Caribbean","population":107394,"latlng":[12.5,-69.96666666],"demonym":"Aruban","area":180.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Aruba","numericCode":"533","currencies":[{"code":"AWG","name":"Aruban florin","symbol":"ƒ"}],"languages":[{"iso639_1":"nl","iso639_2":"nld","name":"Dutch","nativeName":"Nederlands"},{"iso639_1":"pa","iso639_2":"pan","name":"(Eastern) Punjabi","nativeName":"ਪੰਜਾਬੀ"}],"translations":{"de":"Aruba","es":"Aruba","fr":"Aruba","ja":"アルバ","it":"Aruba","br":"Aruba","pt":"Aruba","nl":"Aruba","hr":"Aruba","fa":"آروبا"},"flag":"https://restcountries.eu/data/abw.svg","regionalBlocs":[],"cioc":"ARU"} +{"name":"Australia","topLevelDomain":[".au"],"alpha2Code":"AU","alpha3Code":"AUS","callingCodes":["61"],"capital":"Canberra","altSpellings":["AU"],"region":"Oceania","subregion":"Australia and New Zealand","population":24117360,"latlng":[-27.0,133.0],"demonym":"Australian","area":7692024.0,"gini":30.5,"timezones":["UTC+05:00","UTC+06:30","UTC+07:00","UTC+08:00","UTC+09:30","UTC+10:00","UTC+10:30","UTC+11:30"],"borders":[],"nativeName":"Australia","numericCode":"036","currencies":[{"code":"AUD","name":"Australian dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Australien","es":"Australia","fr":"Australie","ja":"オーストラリア","it":"Australia","br":"Austrália","pt":"Austrália","nl":"Australië","hr":"Australija","fa":"استرالیا"},"flag":"https://restcountries.eu/data/aus.svg","regionalBlocs":[],"cioc":"AUS"} +{"name":"Austria","topLevelDomain":[".at"],"alpha2Code":"AT","alpha3Code":"AUT","callingCodes":["43"],"capital":"Vienna","altSpellings":["AT","Österreich","Osterreich","Oesterreich"],"region":"Europe","subregion":"Western Europe","population":8725931,"latlng":[47.33333333,13.33333333],"demonym":"Austrian","area":83871.0,"gini":26.0,"timezones":["UTC+01:00"],"borders":["CZE","DEU","HUN","ITA","LIE","SVK","SVN","CHE"],"nativeName":"Österreich","numericCode":"040","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"de","iso639_2":"deu","name":"German","nativeName":"Deutsch"}],"translations":{"de":"Österreich","es":"Austria","fr":"Autriche","ja":"オーストリア","it":"Austria","br":"áustria","pt":"áustria","nl":"Oostenrijk","hr":"Austrija","fa":"اتریش"},"flag":"https://restcountries.eu/data/aut.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"AUT"} +{"name":"Azerbaijan","topLevelDomain":[".az"],"alpha2Code":"AZ","alpha3Code":"AZE","callingCodes":["994"],"capital":"Baku","altSpellings":["AZ","Republic of Azerbaijan","Azərbaycan Respublikası"],"region":"Asia","subregion":"Western Asia","population":9730500,"latlng":[40.5,47.5],"demonym":"Azerbaijani","area":86600.0,"gini":33.7,"timezones":["UTC+04:00"],"borders":["ARM","GEO","IRN","RUS","TUR"],"nativeName":"Azərbaycan","numericCode":"031","currencies":[{"code":"AZN","name":"Azerbaijani manat","symbol":null}],"languages":[{"iso639_1":"az","iso639_2":"aze","name":"Azerbaijani","nativeName":"azərbaycan dili"}],"translations":{"de":"Aserbaidschan","es":"Azerbaiyán","fr":"Azerbaïdjan","ja":"アゼルバイジャン","it":"Azerbaijan","br":"Azerbaijão","pt":"Azerbaijão","nl":"Azerbeidzjan","hr":"Azerbajdžan","fa":"آذربایجان"},"flag":"https://restcountries.eu/data/aze.svg","regionalBlocs":[],"cioc":"AZE"} +{"name":"Bahamas","topLevelDomain":[".bs"],"alpha2Code":"BS","alpha3Code":"BHS","callingCodes":["1242"],"capital":"Nassau","altSpellings":["BS","Commonwealth of the Bahamas"],"region":"Americas","subregion":"Caribbean","population":378040,"latlng":[24.25,-76.0],"demonym":"Bahamian","area":13943.0,"gini":null,"timezones":["UTC-05:00"],"borders":[],"nativeName":"Bahamas","numericCode":"044","currencies":[{"code":"BSD","name":"Bahamian dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Bahamas","es":"Bahamas","fr":"Bahamas","ja":"バハマ","it":"Bahamas","br":"Bahamas","pt":"Baamas","nl":"Bahama’s","hr":"Bahami","fa":"باهاما"},"flag":"https://restcountries.eu/data/bhs.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]}],"cioc":"BAH"} +{"name":"Bahrain","topLevelDomain":[".bh"],"alpha2Code":"BH","alpha3Code":"BHR","callingCodes":["973"],"capital":"Manama","altSpellings":["BH","Kingdom of Bahrain","Mamlakat al-Baḥrayn"],"region":"Asia","subregion":"Western Asia","population":1404900,"latlng":[26.0,50.55],"demonym":"Bahraini","area":765.0,"gini":null,"timezones":["UTC+03:00"],"borders":[],"nativeName":"‏البحرين","numericCode":"048","currencies":[{"code":"BHD","name":"Bahraini dinar","symbol":".د.ب"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Bahrain","es":"Bahrein","fr":"Bahreïn","ja":"バーレーン","it":"Bahrein","br":"Bahrein","pt":"Barém","nl":"Bahrein","hr":"Bahrein","fa":"بحرین"},"flag":"https://restcountries.eu/data/bhr.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"BRN"} +{"name":"Bangladesh","topLevelDomain":[".bd"],"alpha2Code":"BD","alpha3Code":"BGD","callingCodes":["880"],"capital":"Dhaka","altSpellings":["BD","People's Republic of Bangladesh","Gônôprôjatôntri Bangladesh"],"region":"Asia","subregion":"Southern Asia","population":161006790,"latlng":[24.0,90.0],"demonym":"Bangladeshi","area":147570.0,"gini":32.1,"timezones":["UTC+06:00"],"borders":["MMR","IND"],"nativeName":"Bangladesh","numericCode":"050","currencies":[{"code":"BDT","name":"Bangladeshi taka","symbol":"৳"}],"languages":[{"iso639_1":"bn","iso639_2":"ben","name":"Bengali","nativeName":"বাংলা"}],"translations":{"de":"Bangladesch","es":"Bangladesh","fr":"Bangladesh","ja":"バングラデシュ","it":"Bangladesh","br":"Bangladesh","pt":"Bangladeche","nl":"Bangladesh","hr":"Bangladeš","fa":"بنگلادش"},"flag":"https://restcountries.eu/data/bgd.svg","regionalBlocs":[{"acronym":"SAARC","name":"South Asian Association for Regional Cooperation","otherAcronyms":[],"otherNames":[]}],"cioc":"BAN"} +{"name":"Barbados","topLevelDomain":[".bb"],"alpha2Code":"BB","alpha3Code":"BRB","callingCodes":["1246"],"capital":"Bridgetown","altSpellings":["BB"],"region":"Americas","subregion":"Caribbean","population":285000,"latlng":[13.16666666,-59.53333333],"demonym":"Barbadian","area":430.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Barbados","numericCode":"052","currencies":[{"code":"BBD","name":"Barbadian dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Barbados","es":"Barbados","fr":"Barbade","ja":"バルバドス","it":"Barbados","br":"Barbados","pt":"Barbados","nl":"Barbados","hr":"Barbados","fa":"باربادوس"},"flag":"https://restcountries.eu/data/brb.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]}],"cioc":"BAR"} +{"name":"Belarus","topLevelDomain":[".by"],"alpha2Code":"BY","alpha3Code":"BLR","callingCodes":["375"],"capital":"Minsk","altSpellings":["BY","Bielaruś","Republic of Belarus","Белоруссия","Республика Беларусь","Belorussiya","Respublika Belarus’"],"region":"Europe","subregion":"Eastern Europe","population":9498700,"latlng":[53.0,28.0],"demonym":"Belarusian","area":207600.0,"gini":26.5,"timezones":["UTC+03:00"],"borders":["LVA","LTU","POL","RUS","UKR"],"nativeName":"Белару́сь","numericCode":"112","currencies":[{"code":"BYN","name":"New Belarusian ruble","symbol":"Br"},{"code":"BYR","name":"Old Belarusian ruble","symbol":"Br"}],"languages":[{"iso639_1":"be","iso639_2":"bel","name":"Belarusian","nativeName":"беларуская мова"},{"iso639_1":"ru","iso639_2":"rus","name":"Russian","nativeName":"Русский"}],"translations":{"de":"Weißrussland","es":"Bielorrusia","fr":"Biélorussie","ja":"ベラルーシ","it":"Bielorussia","br":"Bielorrússia","pt":"Bielorrússia","nl":"Wit-Rusland","hr":"Bjelorusija","fa":"بلاروس"},"flag":"https://restcountries.eu/data/blr.svg","regionalBlocs":[{"acronym":"EEU","name":"Eurasian Economic Union","otherAcronyms":["EAEU"],"otherNames":[]}],"cioc":"BLR"} +{"name":"Belgium","topLevelDomain":[".be"],"alpha2Code":"BE","alpha3Code":"BEL","callingCodes":["32"],"capital":"Brussels","altSpellings":["BE","België","Belgie","Belgien","Belgique","Kingdom of Belgium","Koninkrijk België","Royaume de Belgique","Königreich Belgien"],"region":"Europe","subregion":"Western Europe","population":11319511,"latlng":[50.83333333,4.0],"demonym":"Belgian","area":30528.0,"gini":33.0,"timezones":["UTC+01:00"],"borders":["FRA","DEU","LUX","NLD"],"nativeName":"België","numericCode":"056","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"nl","iso639_2":"nld","name":"Dutch","nativeName":"Nederlands"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"de","iso639_2":"deu","name":"German","nativeName":"Deutsch"}],"translations":{"de":"Belgien","es":"Bélgica","fr":"Belgique","ja":"ベルギー","it":"Belgio","br":"Bélgica","pt":"Bélgica","nl":"België","hr":"Belgija","fa":"بلژیک"},"flag":"https://restcountries.eu/data/bel.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"BEL"} +{"name":"Belize","topLevelDomain":[".bz"],"alpha2Code":"BZ","alpha3Code":"BLZ","callingCodes":["501"],"capital":"Belmopan","altSpellings":["BZ"],"region":"Americas","subregion":"Central America","population":370300,"latlng":[17.25,-88.75],"demonym":"Belizean","area":22966.0,"gini":53.1,"timezones":["UTC-06:00"],"borders":["GTM","MEX"],"nativeName":"Belize","numericCode":"084","currencies":[{"code":"BZD","name":"Belize dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Belize","es":"Belice","fr":"Belize","ja":"ベリーズ","it":"Belize","br":"Belize","pt":"Belize","nl":"Belize","hr":"Belize","fa":"بلیز"},"flag":"https://restcountries.eu/data/blz.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]},{"acronym":"CAIS","name":"Central American Integration System","otherAcronyms":["SICA"],"otherNames":["Sistema de la Integración Centroamericana,"]}],"cioc":"BIZ"} +{"name":"Benin","topLevelDomain":[".bj"],"alpha2Code":"BJ","alpha3Code":"BEN","callingCodes":["229"],"capital":"Porto-Novo","altSpellings":["BJ","Republic of Benin","République du Bénin"],"region":"Africa","subregion":"Western Africa","population":10653654,"latlng":[9.5,2.25],"demonym":"Beninese","area":112622.0,"gini":38.6,"timezones":["UTC+01:00"],"borders":["BFA","NER","NGA","TGO"],"nativeName":"Bénin","numericCode":"204","currencies":[{"code":"XOF","name":"West African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Benin","es":"Benín","fr":"Bénin","ja":"ベナン","it":"Benin","br":"Benin","pt":"Benim","nl":"Benin","hr":"Benin","fa":"بنین"},"flag":"https://restcountries.eu/data/ben.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"BEN"} +{"name":"Bermuda","topLevelDomain":[".bm"],"alpha2Code":"BM","alpha3Code":"BMU","callingCodes":["1441"],"capital":"Hamilton","altSpellings":["BM","The Islands of Bermuda","The Bermudas","Somers Isles"],"region":"Americas","subregion":"Northern America","population":61954,"latlng":[32.33333333,-64.75],"demonym":"Bermudian","area":54.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Bermuda","numericCode":"060","currencies":[{"code":"BMD","name":"Bermudian dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Bermuda","es":"Bermudas","fr":"Bermudes","ja":"バミューダ","it":"Bermuda","br":"Bermudas","pt":"Bermudas","nl":"Bermuda","hr":"Bermudi","fa":"برمودا"},"flag":"https://restcountries.eu/data/bmu.svg","regionalBlocs":[],"cioc":"BER"} +{"name":"Bhutan","topLevelDomain":[".bt"],"alpha2Code":"BT","alpha3Code":"BTN","callingCodes":["975"],"capital":"Thimphu","altSpellings":["BT","Kingdom of Bhutan"],"region":"Asia","subregion":"Southern Asia","population":775620,"latlng":[27.5,90.5],"demonym":"Bhutanese","area":38394.0,"gini":38.1,"timezones":["UTC+06:00"],"borders":["CHN","IND"],"nativeName":"ʼbrug-yul","numericCode":"064","currencies":[{"code":"BTN","name":"Bhutanese ngultrum","symbol":"Nu."},{"code":"INR","name":"Indian rupee","symbol":"₹"}],"languages":[{"iso639_1":"dz","iso639_2":"dzo","name":"Dzongkha","nativeName":"རྫོང་ཁ"}],"translations":{"de":"Bhutan","es":"Bután","fr":"Bhoutan","ja":"ブータン","it":"Bhutan","br":"Butão","pt":"Butão","nl":"Bhutan","hr":"Butan","fa":"بوتان"},"flag":"https://restcountries.eu/data/btn.svg","regionalBlocs":[{"acronym":"SAARC","name":"South Asian Association for Regional Cooperation","otherAcronyms":[],"otherNames":[]}],"cioc":"BHU"} +{"name":"Bolivia (Plurinational State of)","topLevelDomain":[".bo"],"alpha2Code":"BO","alpha3Code":"BOL","callingCodes":["591"],"capital":"Sucre","altSpellings":["BO","Buliwya","Wuliwya","Plurinational State of Bolivia","Estado Plurinacional de Bolivia","Buliwya Mamallaqta","Wuliwya Suyu","Tetã Volívia"],"region":"Americas","subregion":"South America","population":10985059,"latlng":[-17.0,-65.0],"demonym":"Bolivian","area":1098581.0,"gini":56.3,"timezones":["UTC-04:00"],"borders":["ARG","BRA","CHL","PRY","PER"],"nativeName":"Bolivia","numericCode":"068","currencies":[{"code":"BOB","name":"Bolivian boliviano","symbol":"Bs."}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"},{"iso639_1":"ay","iso639_2":"aym","name":"Aymara","nativeName":"aymar aru"},{"iso639_1":"qu","iso639_2":"que","name":"Quechua","nativeName":"Runa Simi"}],"translations":{"de":"Bolivien","es":"Bolivia","fr":"Bolivie","ja":"ボリビア多民族国","it":"Bolivia","br":"Bolívia","pt":"Bolívia","nl":"Bolivia","hr":"Bolivija","fa":"بولیوی"},"flag":"https://restcountries.eu/data/bol.svg","regionalBlocs":[{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"BOL"} +{"name":"Bonaire, Sint Eustatius and Saba","topLevelDomain":[".an",".nl"],"alpha2Code":"BQ","alpha3Code":"BES","callingCodes":["5997"],"capital":"Kralendijk","altSpellings":["BQ","Boneiru"],"region":"Americas","subregion":"Caribbean","population":17408,"latlng":[12.15,-68.266667],"demonym":"Dutch","area":294.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Bonaire","numericCode":"535","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"nl","iso639_2":"nld","name":"Dutch","nativeName":"Nederlands"}],"translations":{"de":"Bonaire, Sint Eustatius und Saba","es":null,"fr":"Bonaire, Saint-Eustache et Saba","ja":null,"it":"Bonaire, Saint-Eustache e Saba","br":"Bonaire","pt":"Bonaire","nl":null,"hr":null,"fa":"بونیر"},"flag":"https://restcountries.eu/data/bes.svg","regionalBlocs":[],"cioc":null} +{"name":"Bosnia and Herzegovina","topLevelDomain":[".ba"],"alpha2Code":"BA","alpha3Code":"BIH","callingCodes":["387"],"capital":"Sarajevo","altSpellings":["BA","Bosnia-Herzegovina","Босна и Херцеговина"],"region":"Europe","subregion":"Southern Europe","population":3531159,"latlng":[44.0,18.0],"demonym":"Bosnian, Herzegovinian","area":51209.0,"gini":36.2,"timezones":["UTC+01:00"],"borders":["HRV","MNE","SRB"],"nativeName":"Bosna i Hercegovina","numericCode":"070","currencies":[{"code":"BAM","name":"Bosnia and Herzegovina convertible mark","symbol":null}],"languages":[{"iso639_1":"bs","iso639_2":"bos","name":"Bosnian","nativeName":"bosanski jezik"},{"iso639_1":"hr","iso639_2":"hrv","name":"Croatian","nativeName":"hrvatski jezik"},{"iso639_1":"sr","iso639_2":"srp","name":"Serbian","nativeName":"српски језик"}],"translations":{"de":"Bosnien und Herzegowina","es":"Bosnia y Herzegovina","fr":"Bosnie-Herzégovine","ja":"ボスニア・ヘルツェゴビナ","it":"Bosnia ed Erzegovina","br":"Bósnia e Herzegovina","pt":"Bósnia e Herzegovina","nl":"Bosnië en Herzegovina","hr":"Bosna i Hercegovina","fa":"بوسنی و هرزگوین"},"flag":"https://restcountries.eu/data/bih.svg","regionalBlocs":[{"acronym":"CEFTA","name":"Central European Free Trade Agreement","otherAcronyms":[],"otherNames":[]}],"cioc":"BIH"} +{"name":"Botswana","topLevelDomain":[".bw"],"alpha2Code":"BW","alpha3Code":"BWA","callingCodes":["267"],"capital":"Gaborone","altSpellings":["BW","Republic of Botswana","Lefatshe la Botswana"],"region":"Africa","subregion":"Southern Africa","population":2141206,"latlng":[-22.0,24.0],"demonym":"Motswana","area":582000.0,"gini":61.0,"timezones":["UTC+02:00"],"borders":["NAM","ZAF","ZMB","ZWE"],"nativeName":"Botswana","numericCode":"072","currencies":[{"code":"BWP","name":"Botswana pula","symbol":"P"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"tn","iso639_2":"tsn","name":"Tswana","nativeName":"Setswana"}],"translations":{"de":"Botswana","es":"Botswana","fr":"Botswana","ja":"ボツワナ","it":"Botswana","br":"Botsuana","pt":"Botsuana","nl":"Botswana","hr":"Bocvana","fa":"بوتسوانا"},"flag":"https://restcountries.eu/data/bwa.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"BOT"} +{"name":"Bouvet Island","topLevelDomain":[".bv"],"alpha2Code":"BV","alpha3Code":"BVT","callingCodes":[""],"capital":"","altSpellings":["BV","Bouvetøya","Bouvet-øya"],"region":"","subregion":"","population":0,"latlng":[-54.43333333,3.4],"demonym":"","area":49.0,"gini":null,"timezones":["UTC+01:00"],"borders":[],"nativeName":"Bouvetøya","numericCode":"074","currencies":[{"code":"NOK","name":"Norwegian krone","symbol":"kr"}],"languages":[{"iso639_1":"no","iso639_2":"nor","name":"Norwegian","nativeName":"Norsk"},{"iso639_1":"nb","iso639_2":"nob","name":"Norwegian Bokmål","nativeName":"Norsk bokmål"},{"iso639_1":"nn","iso639_2":"nno","name":"Norwegian Nynorsk","nativeName":"Norsk nynorsk"}],"translations":{"de":"Bouvetinsel","es":"Isla Bouvet","fr":"Île Bouvet","ja":"ブーベ島","it":"Isola Bouvet","br":"Ilha Bouvet","pt":"Ilha Bouvet","nl":"Bouveteiland","hr":"Otok Bouvet","fa":"جزیره بووه"},"flag":"https://restcountries.eu/data/bvt.svg","regionalBlocs":[],"cioc":""} +{"name":"Brazil","topLevelDomain":[".br"],"alpha2Code":"BR","alpha3Code":"BRA","callingCodes":["55"],"capital":"Brasília","altSpellings":["BR","Brasil","Federative Republic of Brazil","República Federativa do Brasil"],"region":"Americas","subregion":"South America","population":206135893,"latlng":[-10.0,-55.0],"demonym":"Brazilian","area":8515767.0,"gini":54.7,"timezones":["UTC-05:00","UTC-04:00","UTC-03:00","UTC-02:00"],"borders":["ARG","BOL","COL","GUF","GUY","PRY","PER","SUR","URY","VEN"],"nativeName":"Brasil","numericCode":"076","currencies":[{"code":"BRL","name":"Brazilian real","symbol":"R$"}],"languages":[{"iso639_1":"pt","iso639_2":"por","name":"Portuguese","nativeName":"Português"}],"translations":{"de":"Brasilien","es":"Brasil","fr":"Brésil","ja":"ブラジル","it":"Brasile","br":"Brasil","pt":"Brasil","nl":"Brazilië","hr":"Brazil","fa":"برزیل"},"flag":"https://restcountries.eu/data/bra.svg","regionalBlocs":[{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"BRA"} +{"name":"British Indian Ocean Territory","topLevelDomain":[".io"],"alpha2Code":"IO","alpha3Code":"IOT","callingCodes":["246"],"capital":"Diego Garcia","altSpellings":["IO"],"region":"Africa","subregion":"Eastern Africa","population":3000,"latlng":[-6.0,71.5],"demonym":"Indian","area":60.0,"gini":null,"timezones":["UTC+06:00"],"borders":[],"nativeName":"British Indian Ocean Territory","numericCode":"086","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Britisches Territorium im Indischen Ozean","es":"Territorio Británico del Océano Índico","fr":"Territoire britannique de l'océan Indien","ja":"イギリス領インド洋地域","it":"Territorio britannico dell'oceano indiano","br":"Território Britânico do Oceano íÍdico","pt":"Território Britânico do Oceano Índico","nl":"Britse Gebieden in de Indische Oceaan","hr":"Britanski Indijskooceanski teritorij","fa":"قلمرو بریتانیا در اقیانوس هند"},"flag":"https://restcountries.eu/data/iot.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":""} +{"name":"United States Minor Outlying Islands","topLevelDomain":[".us"],"alpha2Code":"UM","alpha3Code":"UMI","callingCodes":[""],"capital":"","altSpellings":["UM"],"region":"Americas","subregion":"Northern America","population":300,"latlng":[],"demonym":"American","area":null,"gini":null,"timezones":["UTC-11:00","UTC-10:00","UTC+12:00"],"borders":[],"nativeName":"United States Minor Outlying Islands","numericCode":"581","currencies":[{"code":"USD","name":"United States Dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Kleinere Inselbesitzungen der Vereinigten Staaten","es":"Islas Ultramarinas Menores de Estados Unidos","fr":"Îles mineures éloignées des États-Unis","ja":"合衆国領有小離島","it":"Isole minori esterne degli Stati Uniti d'America","br":"Ilhas Menores Distantes dos Estados Unidos","pt":"Ilhas Menores Distantes dos Estados Unidos","nl":"Kleine afgelegen eilanden van de Verenigde Staten","hr":"Mali udaljeni otoci SAD-a","fa":"جزایر کوچک حاشیه‌ای ایالات متحده آمریکا"},"flag":"https://restcountries.eu/data/umi.svg","regionalBlocs":[],"cioc":""} +{"name":"Virgin Islands (British)","topLevelDomain":[".vg"],"alpha2Code":"VG","alpha3Code":"VGB","callingCodes":["1284"],"capital":"Road Town","altSpellings":["VG"],"region":"Americas","subregion":"Caribbean","population":28514,"latlng":[18.431383,-64.62305],"demonym":"Virgin Islander","area":151.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"British Virgin Islands","numericCode":"092","currencies":[{"code":null,"name":"[D]","symbol":"$"},{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Britische Jungferninseln","es":"Islas Vírgenes del Reino Unido","fr":"Îles Vierges britanniques","ja":"イギリス領ヴァージン諸島","it":"Isole Vergini Britanniche","br":"Ilhas Virgens Britânicas","pt":"Ilhas Virgens Britânicas","nl":"Britse Maagdeneilanden","hr":"Britanski Djevičanski Otoci","fa":"جزایر ویرجین بریتانیا"},"flag":"https://restcountries.eu/data/vgb.svg","regionalBlocs":[],"cioc":"IVB"} +{"name":"Virgin Islands (U.S.)","topLevelDomain":[".vi"],"alpha2Code":"VI","alpha3Code":"VIR","callingCodes":["1 340"],"capital":"Charlotte Amalie","altSpellings":["VI","USVI","American Virgin Islands","U.S. Virgin Islands"],"region":"Americas","subregion":"Caribbean","population":114743,"latlng":[18.34,-64.93],"demonym":"Virgin Islander","area":346.36,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Virgin Islands of the United States","numericCode":"850","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Amerikanische Jungferninseln","es":"Islas Vírgenes de los Estados Unidos","fr":"Îles Vierges des États-Unis","ja":"アメリカ領ヴァージン諸島","it":"Isole Vergini americane","br":"Ilhas Virgens Americanas","pt":"Ilhas Virgens Americanas","nl":"Verenigde Staten Maagdeneilanden","hr":null,"fa":"جزایر ویرجین آمریکا"},"flag":"https://restcountries.eu/data/vir.svg","regionalBlocs":[],"cioc":"ISV"} +{"name":"Brunei Darussalam","topLevelDomain":[".bn"],"alpha2Code":"BN","alpha3Code":"BRN","callingCodes":["673"],"capital":"Bandar Seri Begawan","altSpellings":["BN","Nation of Brunei"," the Abode of Peace"],"region":"Asia","subregion":"South-Eastern Asia","population":411900,"latlng":[4.5,114.66666666],"demonym":"Bruneian","area":5765.0,"gini":null,"timezones":["UTC+08:00"],"borders":["MYS"],"nativeName":"Negara Brunei Darussalam","numericCode":"096","currencies":[{"code":"BND","name":"Brunei dollar","symbol":"$"},{"code":"SGD","name":"Singapore dollar","symbol":"$"}],"languages":[{"iso639_1":"ms","iso639_2":"msa","name":"Malay","nativeName":"bahasa Melayu"}],"translations":{"de":"Brunei","es":"Brunei","fr":"Brunei","ja":"ブルネイ・ダルサラーム","it":"Brunei","br":"Brunei","pt":"Brunei","nl":"Brunei","hr":"Brunej","fa":"برونئی"},"flag":"https://restcountries.eu/data/brn.svg","regionalBlocs":[{"acronym":"ASEAN","name":"Association of Southeast Asian Nations","otherAcronyms":[],"otherNames":[]}],"cioc":"BRU"} +{"name":"Bulgaria","topLevelDomain":[".bg"],"alpha2Code":"BG","alpha3Code":"BGR","callingCodes":["359"],"capital":"Sofia","altSpellings":["BG","Republic of Bulgaria","Република България"],"region":"Europe","subregion":"Eastern Europe","population":7153784,"latlng":[43.0,25.0],"demonym":"Bulgarian","area":110879.0,"gini":28.2,"timezones":["UTC+02:00"],"borders":["GRC","MKD","ROU","SRB","TUR"],"nativeName":"България","numericCode":"100","currencies":[{"code":"BGN","name":"Bulgarian lev","symbol":"лв"}],"languages":[{"iso639_1":"bg","iso639_2":"bul","name":"Bulgarian","nativeName":"български език"}],"translations":{"de":"Bulgarien","es":"Bulgaria","fr":"Bulgarie","ja":"ブルガリア","it":"Bulgaria","br":"Bulgária","pt":"Bulgária","nl":"Bulgarije","hr":"Bugarska","fa":"بلغارستان"},"flag":"https://restcountries.eu/data/bgr.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"BUL"} +{"name":"Burkina Faso","topLevelDomain":[".bf"],"alpha2Code":"BF","alpha3Code":"BFA","callingCodes":["226"],"capital":"Ouagadougou","altSpellings":["BF"],"region":"Africa","subregion":"Western Africa","population":19034397,"latlng":[13.0,-2.0],"demonym":"Burkinabe","area":272967.0,"gini":39.8,"timezones":["UTC"],"borders":["BEN","CIV","GHA","MLI","NER","TGO"],"nativeName":"Burkina Faso","numericCode":"854","currencies":[{"code":"XOF","name":"West African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"ff","iso639_2":"ful","name":"Fula","nativeName":"Fulfulde"}],"translations":{"de":"Burkina Faso","es":"Burkina Faso","fr":"Burkina Faso","ja":"ブルキナファソ","it":"Burkina Faso","br":"Burkina Faso","pt":"Burquina Faso","nl":"Burkina Faso","hr":"Burkina Faso","fa":"بورکینافاسو"},"flag":"https://restcountries.eu/data/bfa.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"BUR"} +{"name":"Burundi","topLevelDomain":[".bi"],"alpha2Code":"BI","alpha3Code":"BDI","callingCodes":["257"],"capital":"Bujumbura","altSpellings":["BI","Republic of Burundi","Republika y'Uburundi","République du Burundi"],"region":"Africa","subregion":"Eastern Africa","population":10114505,"latlng":[-3.5,30.0],"demonym":"Burundian","area":27834.0,"gini":33.3,"timezones":["UTC+02:00"],"borders":["COD","RWA","TZA"],"nativeName":"Burundi","numericCode":"108","currencies":[{"code":"BIF","name":"Burundian franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"rn","iso639_2":"run","name":"Kirundi","nativeName":"Ikirundi"}],"translations":{"de":"Burundi","es":"Burundi","fr":"Burundi","ja":"ブルンジ","it":"Burundi","br":"Burundi","pt":"Burúndi","nl":"Burundi","hr":"Burundi","fa":"بوروندی"},"flag":"https://restcountries.eu/data/bdi.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"BDI"} +{"name":"Cambodia","topLevelDomain":[".kh"],"alpha2Code":"KH","alpha3Code":"KHM","callingCodes":["855"],"capital":"Phnom Penh","altSpellings":["KH","Kingdom of Cambodia"],"region":"Asia","subregion":"South-Eastern Asia","population":15626444,"latlng":[13.0,105.0],"demonym":"Cambodian","area":181035.0,"gini":37.9,"timezones":["UTC+07:00"],"borders":["LAO","THA","VNM"],"nativeName":"Kâmpŭchéa","numericCode":"116","currencies":[{"code":"KHR","name":"Cambodian riel","symbol":"៛"},{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"km","iso639_2":"khm","name":"Khmer","nativeName":"ខ្មែរ"}],"translations":{"de":"Kambodscha","es":"Camboya","fr":"Cambodge","ja":"カンボジア","it":"Cambogia","br":"Camboja","pt":"Camboja","nl":"Cambodja","hr":"Kambodža","fa":"کامبوج"},"flag":"https://restcountries.eu/data/khm.svg","regionalBlocs":[{"acronym":"ASEAN","name":"Association of Southeast Asian Nations","otherAcronyms":[],"otherNames":[]}],"cioc":"CAM"} +{"name":"Cameroon","topLevelDomain":[".cm"],"alpha2Code":"CM","alpha3Code":"CMR","callingCodes":["237"],"capital":"Yaoundé","altSpellings":["CM","Republic of Cameroon","République du Cameroun"],"region":"Africa","subregion":"Middle Africa","population":22709892,"latlng":[6.0,12.0],"demonym":"Cameroonian","area":475442.0,"gini":38.9,"timezones":["UTC+01:00"],"borders":["CAF","TCD","COG","GNQ","GAB","NGA"],"nativeName":"Cameroon","numericCode":"120","currencies":[{"code":"XAF","name":"Central African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Kamerun","es":"Camerún","fr":"Cameroun","ja":"カメルーン","it":"Camerun","br":"Camarões","pt":"Camarões","nl":"Kameroen","hr":"Kamerun","fa":"کامرون"},"flag":"https://restcountries.eu/data/cmr.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"CMR"} +{"name":"Canada","topLevelDomain":[".ca"],"alpha2Code":"CA","alpha3Code":"CAN","callingCodes":["1"],"capital":"Ottawa","altSpellings":["CA"],"region":"Americas","subregion":"Northern America","population":36155487,"latlng":[60.0,-95.0],"demonym":"Canadian","area":9984670.0,"gini":32.6,"timezones":["UTC-08:00","UTC-07:00","UTC-06:00","UTC-05:00","UTC-04:00","UTC-03:30"],"borders":["USA"],"nativeName":"Canada","numericCode":"124","currencies":[{"code":"CAD","name":"Canadian dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Kanada","es":"Canadá","fr":"Canada","ja":"カナダ","it":"Canada","br":"Canadá","pt":"Canadá","nl":"Canada","hr":"Kanada","fa":"کانادا"},"flag":"https://restcountries.eu/data/can.svg","regionalBlocs":[{"acronym":"NAFTA","name":"North American Free Trade Agreement","otherAcronyms":[],"otherNames":["Tratado de Libre Comercio de América del Norte","Accord de Libre-échange Nord-Américain"]}],"cioc":"CAN"} +{"name":"Cabo Verde","topLevelDomain":[".cv"],"alpha2Code":"CV","alpha3Code":"CPV","callingCodes":["238"],"capital":"Praia","altSpellings":["CV","Republic of Cabo Verde","República de Cabo Verde"],"region":"Africa","subregion":"Western Africa","population":531239,"latlng":[16.0,-24.0],"demonym":"Cape Verdian","area":4033.0,"gini":50.5,"timezones":["UTC-01:00"],"borders":[],"nativeName":"Cabo Verde","numericCode":"132","currencies":[{"code":"CVE","name":"Cape Verdean escudo","symbol":"Esc"}],"languages":[{"iso639_1":"pt","iso639_2":"por","name":"Portuguese","nativeName":"Português"}],"translations":{"de":"Kap Verde","es":"Cabo Verde","fr":"Cap Vert","ja":"カーボベルデ","it":"Capo Verde","br":"Cabo Verde","pt":"Cabo Verde","nl":"Kaapverdië","hr":"Zelenortska Republika","fa":"کیپ ورد"},"flag":"https://restcountries.eu/data/cpv.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"CPV"} +{"name":"Cayman Islands","topLevelDomain":[".ky"],"alpha2Code":"KY","alpha3Code":"CYM","callingCodes":["1345"],"capital":"George Town","altSpellings":["KY"],"region":"Americas","subregion":"Caribbean","population":58238,"latlng":[19.5,-80.5],"demonym":"Caymanian","area":264.0,"gini":null,"timezones":["UTC-05:00"],"borders":[],"nativeName":"Cayman Islands","numericCode":"136","currencies":[{"code":"KYD","name":"Cayman Islands dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Kaimaninseln","es":"Islas Caimán","fr":"Îles Caïmans","ja":"ケイマン諸島","it":"Isole Cayman","br":"Ilhas Cayman","pt":"Ilhas Caimão","nl":"Caymaneilanden","hr":"Kajmanski otoci","fa":"جزایر کیمن"},"flag":"https://restcountries.eu/data/cym.svg","regionalBlocs":[],"cioc":"CAY"} +{"name":"Central African Republic","topLevelDomain":[".cf"],"alpha2Code":"CF","alpha3Code":"CAF","callingCodes":["236"],"capital":"Bangui","altSpellings":["CF","Central African Republic","République centrafricaine"],"region":"Africa","subregion":"Middle Africa","population":4998000,"latlng":[7.0,21.0],"demonym":"Central African","area":622984.0,"gini":56.3,"timezones":["UTC+01:00"],"borders":["CMR","TCD","COD","COG","SSD","SDN"],"nativeName":"Ködörösêse tî Bêafrîka","numericCode":"140","currencies":[{"code":"XAF","name":"Central African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"sg","iso639_2":"sag","name":"Sango","nativeName":"yângâ tî sängö"}],"translations":{"de":"Zentralafrikanische Republik","es":"República Centroafricana","fr":"République centrafricaine","ja":"中央アフリカ共和国","it":"Repubblica Centrafricana","br":"República Centro-Africana","pt":"República Centro-Africana","nl":"Centraal-Afrikaanse Republiek","hr":"Srednjoafrička Republika","fa":"جمهوری آفریقای مرکزی"},"flag":"https://restcountries.eu/data/caf.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"CAF"} +{"name":"Chad","topLevelDomain":[".td"],"alpha2Code":"TD","alpha3Code":"TCD","callingCodes":["235"],"capital":"N'Djamena","altSpellings":["TD","Tchad","Republic of Chad","République du Tchad"],"region":"Africa","subregion":"Middle Africa","population":14497000,"latlng":[15.0,19.0],"demonym":"Chadian","area":1284000.0,"gini":39.8,"timezones":["UTC+01:00"],"borders":["CMR","CAF","LBY","NER","NGA","SSD"],"nativeName":"Tchad","numericCode":"148","currencies":[{"code":"XAF","name":"Central African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Tschad","es":"Chad","fr":"Tchad","ja":"チャド","it":"Ciad","br":"Chade","pt":"Chade","nl":"Tsjaad","hr":"Čad","fa":"چاد"},"flag":"https://restcountries.eu/data/tcd.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"CHA"} +{"name":"Chile","topLevelDomain":[".cl"],"alpha2Code":"CL","alpha3Code":"CHL","callingCodes":["56"],"capital":"Santiago","altSpellings":["CL","Republic of Chile","República de Chile"],"region":"Americas","subregion":"South America","population":18191900,"latlng":[-30.0,-71.0],"demonym":"Chilean","area":756102.0,"gini":52.1,"timezones":["UTC-06:00","UTC-04:00"],"borders":["ARG","BOL","PER"],"nativeName":"Chile","numericCode":"152","currencies":[{"code":"CLP","name":"Chilean peso","symbol":"$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Chile","es":"Chile","fr":"Chili","ja":"チリ","it":"Cile","br":"Chile","pt":"Chile","nl":"Chili","hr":"Čile","fa":"شیلی"},"flag":"https://restcountries.eu/data/chl.svg","regionalBlocs":[{"acronym":"PA","name":"Pacific Alliance","otherAcronyms":[],"otherNames":["Alianza del Pacífico"]},{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"CHI"} +{"name":"China","topLevelDomain":[".cn"],"alpha2Code":"CN","alpha3Code":"CHN","callingCodes":["86"],"capital":"Beijing","altSpellings":["CN","Zhōngguó","Zhongguo","Zhonghua","People's Republic of China","中华人民共和国","Zhōnghuá Rénmín Gònghéguó"],"region":"Asia","subregion":"Eastern Asia","population":1377422166,"latlng":[35.0,105.0],"demonym":"Chinese","area":9640011.0,"gini":47.0,"timezones":["UTC+08:00"],"borders":["AFG","BTN","MMR","HKG","IND","KAZ","PRK","KGZ","LAO","MAC","MNG","PAK","RUS","TJK","VNM"],"nativeName":"中国","numericCode":"156","currencies":[{"code":"CNY","name":"Chinese yuan","symbol":"¥"}],"languages":[{"iso639_1":"zh","iso639_2":"zho","name":"Chinese","nativeName":"中文 (Zhōngwén)"}],"translations":{"de":"China","es":"China","fr":"Chine","ja":"中国","it":"Cina","br":"China","pt":"China","nl":"China","hr":"Kina","fa":"چین"},"flag":"https://restcountries.eu/data/chn.svg","regionalBlocs":[],"cioc":"CHN"} +{"name":"Christmas Island","topLevelDomain":[".cx"],"alpha2Code":"CX","alpha3Code":"CXR","callingCodes":["61"],"capital":"Flying Fish Cove","altSpellings":["CX","Territory of Christmas Island"],"region":"Oceania","subregion":"Australia and New Zealand","population":2072,"latlng":[-10.5,105.66666666],"demonym":"Christmas Island","area":135.0,"gini":null,"timezones":["UTC+07:00"],"borders":[],"nativeName":"Christmas Island","numericCode":"162","currencies":[{"code":"AUD","name":"Australian dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Weihnachtsinsel","es":"Isla de Navidad","fr":"Île Christmas","ja":"クリスマス島","it":"Isola di Natale","br":"Ilha Christmas","pt":"Ilha do Natal","nl":"Christmaseiland","hr":"Božićni otok","fa":"جزیره کریسمس"},"flag":"https://restcountries.eu/data/cxr.svg","regionalBlocs":[],"cioc":""} +{"name":"Cocos (Keeling) Islands","topLevelDomain":[".cc"],"alpha2Code":"CC","alpha3Code":"CCK","callingCodes":["61"],"capital":"West Island","altSpellings":["CC","Territory of the Cocos (Keeling) Islands","Keeling Islands"],"region":"Oceania","subregion":"Australia and New Zealand","population":550,"latlng":[-12.5,96.83333333],"demonym":"Cocos Islander","area":14.0,"gini":null,"timezones":["UTC+06:30"],"borders":[],"nativeName":"Cocos (Keeling) Islands","numericCode":"166","currencies":[{"code":"AUD","name":"Australian dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Kokosinseln","es":"Islas Cocos o Islas Keeling","fr":"Îles Cocos","ja":"ココス(キーリング)諸島","it":"Isole Cocos e Keeling","br":"Ilhas Cocos","pt":"Ilhas dos Cocos","nl":"Cocoseilanden","hr":"Kokosovi Otoci","fa":"جزایر کوکوس"},"flag":"https://restcountries.eu/data/cck.svg","regionalBlocs":[],"cioc":""} +{"name":"Colombia","topLevelDomain":[".co"],"alpha2Code":"CO","alpha3Code":"COL","callingCodes":["57"],"capital":"Bogotá","altSpellings":["CO","Republic of Colombia","República de Colombia"],"region":"Americas","subregion":"South America","population":48759958,"latlng":[4.0,-72.0],"demonym":"Colombian","area":1141748.0,"gini":55.9,"timezones":["UTC-05:00"],"borders":["BRA","ECU","PAN","PER","VEN"],"nativeName":"Colombia","numericCode":"170","currencies":[{"code":"COP","name":"Colombian peso","symbol":"$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Kolumbien","es":"Colombia","fr":"Colombie","ja":"コロンビア","it":"Colombia","br":"Colômbia","pt":"Colômbia","nl":"Colombia","hr":"Kolumbija","fa":"کلمبیا"},"flag":"https://restcountries.eu/data/col.svg","regionalBlocs":[{"acronym":"PA","name":"Pacific Alliance","otherAcronyms":[],"otherNames":["Alianza del Pacífico"]},{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"COL"} +{"name":"Comoros","topLevelDomain":[".km"],"alpha2Code":"KM","alpha3Code":"COM","callingCodes":["269"],"capital":"Moroni","altSpellings":["KM","Union of the Comoros","Union des Comores","Udzima wa Komori","al-Ittiḥād al-Qumurī"],"region":"Africa","subregion":"Eastern Africa","population":806153,"latlng":[-12.16666666,44.25],"demonym":"Comoran","area":1862.0,"gini":64.3,"timezones":["UTC+03:00"],"borders":[],"nativeName":"Komori","numericCode":"174","currencies":[{"code":"KMF","name":"Comorian franc","symbol":"Fr"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Union der Komoren","es":"Comoras","fr":"Comores","ja":"コモロ","it":"Comore","br":"Comores","pt":"Comores","nl":"Comoren","hr":"Komori","fa":"کومور"},"flag":"https://restcountries.eu/data/com.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]},{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"COM"} +{"name":"Congo","topLevelDomain":[".cg"],"alpha2Code":"CG","alpha3Code":"COG","callingCodes":["242"],"capital":"Brazzaville","altSpellings":["CG","Congo-Brazzaville"],"region":"Africa","subregion":"Middle Africa","population":4741000,"latlng":[-1.0,15.0],"demonym":"Congolese","area":342000.0,"gini":47.3,"timezones":["UTC+01:00"],"borders":["AGO","CMR","CAF","COD","GAB"],"nativeName":"République du Congo","numericCode":"178","currencies":[{"code":"XAF","name":"Central African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"ln","iso639_2":"lin","name":"Lingala","nativeName":"Lingála"}],"translations":{"de":"Kongo","es":"Congo","fr":"Congo","ja":"コンゴ共和国","it":"Congo","br":"Congo","pt":"Congo","nl":"Congo [Republiek]","hr":"Kongo","fa":"کنگو"},"flag":"https://restcountries.eu/data/cog.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"CGO"} +{"name":"Congo (Democratic Republic of the)","topLevelDomain":[".cd"],"alpha2Code":"CD","alpha3Code":"COD","callingCodes":["243"],"capital":"Kinshasa","altSpellings":["CD","DR Congo","Congo-Kinshasa","DRC"],"region":"Africa","subregion":"Middle Africa","population":85026000,"latlng":[0.0,25.0],"demonym":"Congolese","area":2344858.0,"gini":null,"timezones":["UTC+01:00","UTC+02:00"],"borders":["AGO","BDI","CAF","COG","RWA","SSD","TZA","UGA","ZMB"],"nativeName":"République démocratique du Congo","numericCode":"180","currencies":[{"code":"CDF","name":"Congolese franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"ln","iso639_2":"lin","name":"Lingala","nativeName":"Lingála"},{"iso639_1":"kg","iso639_2":"kon","name":"Kongo","nativeName":"Kikongo"},{"iso639_1":"sw","iso639_2":"swa","name":"Swahili","nativeName":"Kiswahili"},{"iso639_1":"lu","iso639_2":"lub","name":"Luba-Katanga","nativeName":"Tshiluba"}],"translations":{"de":"Kongo (Dem. Rep.)","es":"Congo (Rep. Dem.)","fr":"Congo (Rép. dém.)","ja":"コンゴ民主共和国","it":"Congo (Rep. Dem.)","br":"RD Congo","pt":"RD Congo","nl":"Congo [DRC]","hr":"Kongo, Demokratska Republika","fa":"جمهوری کنگو"},"flag":"https://restcountries.eu/data/cod.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"COD"} +{"name":"Cook Islands","topLevelDomain":[".ck"],"alpha2Code":"CK","alpha3Code":"COK","callingCodes":["682"],"capital":"Avarua","altSpellings":["CK","Kūki 'Āirani"],"region":"Oceania","subregion":"Polynesia","population":18100,"latlng":[-21.23333333,-159.76666666],"demonym":"Cook Islander","area":236.0,"gini":null,"timezones":["UTC-10:00"],"borders":[],"nativeName":"Cook Islands","numericCode":"184","currencies":[{"code":"NZD","name":"New Zealand dollar","symbol":"$"},{"code":"CKD","name":"Cook Islands dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Cookinseln","es":"Islas Cook","fr":"Îles Cook","ja":"クック諸島","it":"Isole Cook","br":"Ilhas Cook","pt":"Ilhas Cook","nl":"Cookeilanden","hr":"Cookovo Otočje","fa":"جزایر کوک"},"flag":"https://restcountries.eu/data/cok.svg","regionalBlocs":[],"cioc":"COK"} +{"name":"Costa Rica","topLevelDomain":[".cr"],"alpha2Code":"CR","alpha3Code":"CRI","callingCodes":["506"],"capital":"San José","altSpellings":["CR","Republic of Costa Rica","República de Costa Rica"],"region":"Americas","subregion":"Central America","population":4890379,"latlng":[10.0,-84.0],"demonym":"Costa Rican","area":51100.0,"gini":50.7,"timezones":["UTC-06:00"],"borders":["NIC","PAN"],"nativeName":"Costa Rica","numericCode":"188","currencies":[{"code":"CRC","name":"Costa Rican colón","symbol":"₡"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Costa Rica","es":"Costa Rica","fr":"Costa Rica","ja":"コスタリカ","it":"Costa Rica","br":"Costa Rica","pt":"Costa Rica","nl":"Costa Rica","hr":"Kostarika","fa":"کاستاریکا"},"flag":"https://restcountries.eu/data/cri.svg","regionalBlocs":[{"acronym":"CAIS","name":"Central American Integration System","otherAcronyms":["SICA"],"otherNames":["Sistema de la Integración Centroamericana,"]}],"cioc":"CRC"} +{"name":"Croatia","topLevelDomain":[".hr"],"alpha2Code":"HR","alpha3Code":"HRV","callingCodes":["385"],"capital":"Zagreb","altSpellings":["HR","Hrvatska","Republic of Croatia","Republika Hrvatska"],"region":"Europe","subregion":"Southern Europe","population":4190669,"latlng":[45.16666666,15.5],"demonym":"Croatian","area":56594.0,"gini":33.7,"timezones":["UTC+01:00"],"borders":["BIH","HUN","MNE","SRB","SVN"],"nativeName":"Hrvatska","numericCode":"191","currencies":[{"code":"HRK","name":"Croatian kuna","symbol":"kn"}],"languages":[{"iso639_1":"hr","iso639_2":"hrv","name":"Croatian","nativeName":"hrvatski jezik"}],"translations":{"de":"Kroatien","es":"Croacia","fr":"Croatie","ja":"クロアチア","it":"Croazia","br":"Croácia","pt":"Croácia","nl":"Kroatië","hr":"Hrvatska","fa":"کرواسی"},"flag":"https://restcountries.eu/data/hrv.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"CRO"} +{"name":"Cuba","topLevelDomain":[".cu"],"alpha2Code":"CU","alpha3Code":"CUB","callingCodes":["53"],"capital":"Havana","altSpellings":["CU","Republic of Cuba","República de Cuba"],"region":"Americas","subregion":"Caribbean","population":11239004,"latlng":[21.5,-80.0],"demonym":"Cuban","area":109884.0,"gini":null,"timezones":["UTC-05:00"],"borders":[],"nativeName":"Cuba","numericCode":"192","currencies":[{"code":"CUC","name":"Cuban convertible peso","symbol":"$"},{"code":"CUP","name":"Cuban peso","symbol":"$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Kuba","es":"Cuba","fr":"Cuba","ja":"キューバ","it":"Cuba","br":"Cuba","pt":"Cuba","nl":"Cuba","hr":"Kuba","fa":"کوبا"},"flag":"https://restcountries.eu/data/cub.svg","regionalBlocs":[],"cioc":"CUB"} +{"name":"Curaçao","topLevelDomain":[".cw"],"alpha2Code":"CW","alpha3Code":"CUW","callingCodes":["599"],"capital":"Willemstad","altSpellings":["CW","Curacao","Kòrsou","Country of Curaçao","Land Curaçao","Pais Kòrsou"],"region":"Americas","subregion":"Caribbean","population":154843,"latlng":[12.116667,-68.933333],"demonym":"Dutch","area":444.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Curaçao","numericCode":"531","currencies":[{"code":"ANG","name":"Netherlands Antillean guilder","symbol":"ƒ"}],"languages":[{"iso639_1":"nl","iso639_2":"nld","name":"Dutch","nativeName":"Nederlands"},{"iso639_1":"pa","iso639_2":"pan","name":"(Eastern) Punjabi","nativeName":"ਪੰਜਾਬੀ"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Curaçao","es":null,"fr":"Curaçao","ja":null,"it":"Curaçao","br":"Curaçao","pt":"Curaçao","nl":"Curaçao","hr":null,"fa":"کوراسائو"},"flag":"https://restcountries.eu/data/cuw.svg","regionalBlocs":[],"cioc":""} +{"name":"Cyprus","topLevelDomain":[".cy"],"alpha2Code":"CY","alpha3Code":"CYP","callingCodes":["357"],"capital":"Nicosia","altSpellings":["CY","Kýpros","Kıbrıs","Republic of Cyprus","Κυπριακή Δημοκρατία","Kıbrıs Cumhuriyeti"],"region":"Europe","subregion":"Southern Europe","population":847000,"latlng":[35.0,33.0],"demonym":"Cypriot","area":9251.0,"gini":null,"timezones":["UTC+02:00"],"borders":["GBR"],"nativeName":"Κύπρος","numericCode":"196","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"el","iso639_2":"ell","name":"Greek (modern)","nativeName":"ελληνικά"},{"iso639_1":"tr","iso639_2":"tur","name":"Turkish","nativeName":"Türkçe"},{"iso639_1":"hy","iso639_2":"hye","name":"Armenian","nativeName":"Հայերեն"}],"translations":{"de":"Zypern","es":"Chipre","fr":"Chypre","ja":"キプロス","it":"Cipro","br":"Chipre","pt":"Chipre","nl":"Cyprus","hr":"Cipar","fa":"قبرس"},"flag":"https://restcountries.eu/data/cyp.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"CYP"} +{"name":"Czech Republic","topLevelDomain":[".cz"],"alpha2Code":"CZ","alpha3Code":"CZE","callingCodes":["420"],"capital":"Prague","altSpellings":["CZ","Česká republika","Česko"],"region":"Europe","subregion":"Eastern Europe","population":10558524,"latlng":[49.75,15.5],"demonym":"Czech","area":78865.0,"gini":26.0,"timezones":["UTC+01:00"],"borders":["AUT","DEU","POL","SVK"],"nativeName":"Česká republika","numericCode":"203","currencies":[{"code":"CZK","name":"Czech koruna","symbol":"Kč"}],"languages":[{"iso639_1":"cs","iso639_2":"ces","name":"Czech","nativeName":"čeština"},{"iso639_1":"sk","iso639_2":"slk","name":"Slovak","nativeName":"slovenčina"}],"translations":{"de":"Tschechische Republik","es":"República Checa","fr":"République tchèque","ja":"チェコ","it":"Repubblica Ceca","br":"República Tcheca","pt":"República Checa","nl":"Tsjechië","hr":"Češka","fa":"جمهوری چک"},"flag":"https://restcountries.eu/data/cze.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"CZE"} +{"name":"Denmark","topLevelDomain":[".dk"],"alpha2Code":"DK","alpha3Code":"DNK","callingCodes":["45"],"capital":"Copenhagen","altSpellings":["DK","Danmark","Kingdom of Denmark","Kongeriget Danmark"],"region":"Europe","subregion":"Northern Europe","population":5717014,"latlng":[56.0,10.0],"demonym":"Danish","area":43094.0,"gini":24.0,"timezones":["UTC-04:00","UTC-03:00","UTC-01:00","UTC","UTC+01:00"],"borders":["DEU"],"nativeName":"Danmark","numericCode":"208","currencies":[{"code":"DKK","name":"Danish krone","symbol":"kr"}],"languages":[{"iso639_1":"da","iso639_2":"dan","name":"Danish","nativeName":"dansk"}],"translations":{"de":"Dänemark","es":"Dinamarca","fr":"Danemark","ja":"デンマーク","it":"Danimarca","br":"Dinamarca","pt":"Dinamarca","nl":"Denemarken","hr":"Danska","fa":"دانمارک"},"flag":"https://restcountries.eu/data/dnk.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"DEN"} +{"name":"Djibouti","topLevelDomain":[".dj"],"alpha2Code":"DJ","alpha3Code":"DJI","callingCodes":["253"],"capital":"Djibouti","altSpellings":["DJ","Jabuuti","Gabuuti","Republic of Djibouti","République de Djibouti","Gabuutih Ummuuno","Jamhuuriyadda Jabuuti"],"region":"Africa","subregion":"Eastern Africa","population":900000,"latlng":[11.5,43.0],"demonym":"Djibouti","area":23200.0,"gini":40.0,"timezones":["UTC+03:00"],"borders":["ERI","ETH","SOM"],"nativeName":"Djibouti","numericCode":"262","currencies":[{"code":"DJF","name":"Djiboutian franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Dschibuti","es":"Yibuti","fr":"Djibouti","ja":"ジブチ","it":"Gibuti","br":"Djibuti","pt":"Djibuti","nl":"Djibouti","hr":"Džibuti","fa":"جیبوتی"},"flag":"https://restcountries.eu/data/dji.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]},{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"DJI"} +{"name":"Dominica","topLevelDomain":[".dm"],"alpha2Code":"DM","alpha3Code":"DMA","callingCodes":["1767"],"capital":"Roseau","altSpellings":["DM","Dominique","Wai‘tu kubuli","Commonwealth of Dominica"],"region":"Americas","subregion":"Caribbean","population":71293,"latlng":[15.41666666,-61.33333333],"demonym":"Dominican","area":751.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Dominica","numericCode":"212","currencies":[{"code":"XCD","name":"East Caribbean dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Dominica","es":"Dominica","fr":"Dominique","ja":"ドミニカ国","it":"Dominica","br":"Dominica","pt":"Dominica","nl":"Dominica","hr":"Dominika","fa":"دومینیکا"},"flag":"https://restcountries.eu/data/dma.svg","regionalBlocs":[],"cioc":"DMA"} +{"name":"Dominican Republic","topLevelDomain":[".do"],"alpha2Code":"DO","alpha3Code":"DOM","callingCodes":["1809","1829","1849"],"capital":"Santo Domingo","altSpellings":["DO"],"region":"Americas","subregion":"Caribbean","population":10075045,"latlng":[19.0,-70.66666666],"demonym":"Dominican","area":48671.0,"gini":47.2,"timezones":["UTC-04:00"],"borders":["HTI"],"nativeName":"República Dominicana","numericCode":"214","currencies":[{"code":"DOP","name":"Dominican peso","symbol":"$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Dominikanische Republik","es":"República Dominicana","fr":"République dominicaine","ja":"ドミニカ共和国","it":"Repubblica Dominicana","br":"República Dominicana","pt":"República Dominicana","nl":"Dominicaanse Republiek","hr":"Dominikanska Republika","fa":"جمهوری دومینیکن"},"flag":"https://restcountries.eu/data/dom.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]},{"acronym":"CAIS","name":"Central American Integration System","otherAcronyms":["SICA"],"otherNames":["Sistema de la Integración Centroamericana,"]}],"cioc":"DOM"} +{"name":"Ecuador","topLevelDomain":[".ec"],"alpha2Code":"EC","alpha3Code":"ECU","callingCodes":["593"],"capital":"Quito","altSpellings":["EC","Republic of Ecuador","República del Ecuador"],"region":"Americas","subregion":"South America","population":16545799,"latlng":[-2.0,-77.5],"demonym":"Ecuadorean","area":276841.0,"gini":49.3,"timezones":["UTC-06:00","UTC-05:00"],"borders":["COL","PER"],"nativeName":"Ecuador","numericCode":"218","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Ecuador","es":"Ecuador","fr":"Équateur","ja":"エクアドル","it":"Ecuador","br":"Equador","pt":"Equador","nl":"Ecuador","hr":"Ekvador","fa":"اکوادور"},"flag":"https://restcountries.eu/data/ecu.svg","regionalBlocs":[{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"ECU"} +{"name":"Egypt","topLevelDomain":[".eg"],"alpha2Code":"EG","alpha3Code":"EGY","callingCodes":["20"],"capital":"Cairo","altSpellings":["EG","Arab Republic of Egypt"],"region":"Africa","subregion":"Northern Africa","population":91290000,"latlng":[27.0,30.0],"demonym":"Egyptian","area":1002450.0,"gini":30.8,"timezones":["UTC+02:00"],"borders":["ISR","LBY","SDN"],"nativeName":"مصر‎","numericCode":"818","currencies":[{"code":"EGP","name":"Egyptian pound","symbol":"£"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Ägypten","es":"Egipto","fr":"Égypte","ja":"エジプト","it":"Egitto","br":"Egito","pt":"Egipto","nl":"Egypte","hr":"Egipat","fa":"مصر"},"flag":"https://restcountries.eu/data/egy.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]},{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"EGY"} +{"name":"El Salvador","topLevelDomain":[".sv"],"alpha2Code":"SV","alpha3Code":"SLV","callingCodes":["503"],"capital":"San Salvador","altSpellings":["SV","Republic of El Salvador","República de El Salvador"],"region":"Americas","subregion":"Central America","population":6520675,"latlng":[13.83333333,-88.91666666],"demonym":"Salvadoran","area":21041.0,"gini":48.3,"timezones":["UTC-06:00"],"borders":["GTM","HND"],"nativeName":"El Salvador","numericCode":"222","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"El Salvador","es":"El Salvador","fr":"Salvador","ja":"エルサルバドル","it":"El Salvador","br":"El Salvador","pt":"El Salvador","nl":"El Salvador","hr":"Salvador","fa":"السالوادور"},"flag":"https://restcountries.eu/data/slv.svg","regionalBlocs":[{"acronym":"CAIS","name":"Central American Integration System","otherAcronyms":["SICA"],"otherNames":["Sistema de la Integración Centroamericana,"]}],"cioc":"ESA"} +{"name":"Equatorial Guinea","topLevelDomain":[".gq"],"alpha2Code":"GQ","alpha3Code":"GNQ","callingCodes":["240"],"capital":"Malabo","altSpellings":["GQ","Republic of Equatorial Guinea","República de Guinea Ecuatorial","République de Guinée équatoriale","República da Guiné Equatorial"],"region":"Africa","subregion":"Middle Africa","population":1222442,"latlng":[2.0,10.0],"demonym":"Equatorial Guinean","area":28051.0,"gini":null,"timezones":["UTC+01:00"],"borders":["CMR","GAB"],"nativeName":"Guinea Ecuatorial","numericCode":"226","currencies":[{"code":"XAF","name":"Central African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Äquatorial-Guinea","es":"Guinea Ecuatorial","fr":"Guinée-Équatoriale","ja":"赤道ギニア","it":"Guinea Equatoriale","br":"Guiné Equatorial","pt":"Guiné Equatorial","nl":"Equatoriaal-Guinea","hr":"Ekvatorijalna Gvineja","fa":"گینه استوایی"},"flag":"https://restcountries.eu/data/gnq.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"GEQ"} +{"name":"Eritrea","topLevelDomain":[".er"],"alpha2Code":"ER","alpha3Code":"ERI","callingCodes":["291"],"capital":"Asmara","altSpellings":["ER","State of Eritrea","ሃገረ ኤርትራ","Dawlat Iritriyá","ʾErtrā","Iritriyā",""],"region":"Africa","subregion":"Eastern Africa","population":5352000,"latlng":[15.0,39.0],"demonym":"Eritrean","area":117600.0,"gini":null,"timezones":["UTC+03:00"],"borders":["DJI","ETH","SDN"],"nativeName":"ኤርትራ","numericCode":"232","currencies":[{"code":"ERN","name":"Eritrean nakfa","symbol":"Nfk"}],"languages":[{"iso639_1":"ti","iso639_2":"tir","name":"Tigrinya","nativeName":"ትግርኛ"},{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Eritrea","es":"Eritrea","fr":"Érythrée","ja":"エリトリア","it":"Eritrea","br":"Eritreia","pt":"Eritreia","nl":"Eritrea","hr":"Eritreja","fa":"اریتره"},"flag":"https://restcountries.eu/data/eri.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"ERI"} +{"name":"Estonia","topLevelDomain":[".ee"],"alpha2Code":"EE","alpha3Code":"EST","callingCodes":["372"],"capital":"Tallinn","altSpellings":["EE","Eesti","Republic of Estonia","Eesti Vabariik"],"region":"Europe","subregion":"Northern Europe","population":1315944,"latlng":[59.0,26.0],"demonym":"Estonian","area":45227.0,"gini":36.0,"timezones":["UTC+02:00"],"borders":["LVA","RUS"],"nativeName":"Eesti","numericCode":"233","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"et","iso639_2":"est","name":"Estonian","nativeName":"eesti"}],"translations":{"de":"Estland","es":"Estonia","fr":"Estonie","ja":"エストニア","it":"Estonia","br":"Estônia","pt":"Estónia","nl":"Estland","hr":"Estonija","fa":"استونی"},"flag":"https://restcountries.eu/data/est.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"EST"} +{"name":"Ethiopia","topLevelDomain":[".et"],"alpha2Code":"ET","alpha3Code":"ETH","callingCodes":["251"],"capital":"Addis Ababa","altSpellings":["ET","ʾĪtyōṗṗyā","Federal Democratic Republic of Ethiopia","የኢትዮጵያ ፌዴራላዊ ዲሞክራሲያዊ ሪፐብሊክ"],"region":"Africa","subregion":"Eastern Africa","population":92206005,"latlng":[8.0,38.0],"demonym":"Ethiopian","area":1104300.0,"gini":29.8,"timezones":["UTC+03:00"],"borders":["DJI","ERI","KEN","SOM","SSD","SDN"],"nativeName":"ኢትዮጵያ","numericCode":"231","currencies":[{"code":"ETB","name":"Ethiopian birr","symbol":"Br"}],"languages":[{"iso639_1":"am","iso639_2":"amh","name":"Amharic","nativeName":"አማርኛ"}],"translations":{"de":"Äthiopien","es":"Etiopía","fr":"Éthiopie","ja":"エチオピア","it":"Etiopia","br":"Etiópia","pt":"Etiópia","nl":"Ethiopië","hr":"Etiopija","fa":"اتیوپی"},"flag":"https://restcountries.eu/data/eth.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"ETH"} +{"name":"Falkland Islands (Malvinas)","topLevelDomain":[".fk"],"alpha2Code":"FK","alpha3Code":"FLK","callingCodes":["500"],"capital":"Stanley","altSpellings":["FK","Islas Malvinas"],"region":"Americas","subregion":"South America","population":2563,"latlng":[-51.75,-59.0],"demonym":"Falkland Islander","area":12173.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Falkland Islands","numericCode":"238","currencies":[{"code":"FKP","name":"Falkland Islands pound","symbol":"£"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Falklandinseln","es":"Islas Malvinas","fr":"Îles Malouines","ja":"フォークランド(マルビナス)諸島","it":"Isole Falkland o Isole Malvine","br":"Ilhas Malvinas","pt":"Ilhas Falkland","nl":"Falklandeilanden [Islas Malvinas]","hr":"Falklandski Otoci","fa":"جزایر فالکلند"},"flag":"https://restcountries.eu/data/flk.svg","regionalBlocs":[{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":""} +{"name":"Faroe Islands","topLevelDomain":[".fo"],"alpha2Code":"FO","alpha3Code":"FRO","callingCodes":["298"],"capital":"Tórshavn","altSpellings":["FO","Føroyar","Færøerne"],"region":"Europe","subregion":"Northern Europe","population":49376,"latlng":[62.0,-7.0],"demonym":"Faroese","area":1393.0,"gini":null,"timezones":["UTC+00:00"],"borders":[],"nativeName":"Føroyar","numericCode":"234","currencies":[{"code":"DKK","name":"Danish krone","symbol":"kr"},{"code":"(none)","name":"Faroese króna","symbol":"kr"}],"languages":[{"iso639_1":"fo","iso639_2":"fao","name":"Faroese","nativeName":"føroyskt"}],"translations":{"de":"Färöer-Inseln","es":"Islas Faroe","fr":"Îles Féroé","ja":"フェロー諸島","it":"Isole Far Oer","br":"Ilhas Faroé","pt":"Ilhas Faroé","nl":"Faeröer","hr":"Farski Otoci","fa":"جزایر فارو"},"flag":"https://restcountries.eu/data/fro.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":""} +{"name":"Fiji","topLevelDomain":[".fj"],"alpha2Code":"FJ","alpha3Code":"FJI","callingCodes":["679"],"capital":"Suva","altSpellings":["FJ","Viti","Republic of Fiji","Matanitu ko Viti","Fijī Gaṇarājya"],"region":"Oceania","subregion":"Melanesia","population":867000,"latlng":[-18.0,175.0],"demonym":"Fijian","area":18272.0,"gini":42.8,"timezones":["UTC+12:00"],"borders":[],"nativeName":"Fiji","numericCode":"242","currencies":[{"code":"FJD","name":"Fijian dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"fj","iso639_2":"fij","name":"Fijian","nativeName":"vosa Vakaviti"},{"iso639_1":"hi","iso639_2":"hin","name":"Hindi","nativeName":"हिन्दी"},{"iso639_1":"ur","iso639_2":"urd","name":"Urdu","nativeName":"اردو"}],"translations":{"de":"Fidschi","es":"Fiyi","fr":"Fidji","ja":"フィジー","it":"Figi","br":"Fiji","pt":"Fiji","nl":"Fiji","hr":"Fiđi","fa":"فیجی"},"flag":"https://restcountries.eu/data/fji.svg","regionalBlocs":[],"cioc":"FIJ"} +{"name":"Finland","topLevelDomain":[".fi"],"alpha2Code":"FI","alpha3Code":"FIN","callingCodes":["358"],"capital":"Helsinki","altSpellings":["FI","Suomi","Republic of Finland","Suomen tasavalta","Republiken Finland"],"region":"Europe","subregion":"Northern Europe","population":5491817,"latlng":[64.0,26.0],"demonym":"Finnish","area":338424.0,"gini":26.9,"timezones":["UTC+02:00"],"borders":["NOR","SWE","RUS"],"nativeName":"Suomi","numericCode":"246","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fi","iso639_2":"fin","name":"Finnish","nativeName":"suomi"},{"iso639_1":"sv","iso639_2":"swe","name":"Swedish","nativeName":"svenska"}],"translations":{"de":"Finnland","es":"Finlandia","fr":"Finlande","ja":"フィンランド","it":"Finlandia","br":"Finlândia","pt":"Finlândia","nl":"Finland","hr":"Finska","fa":"فنلاند"},"flag":"https://restcountries.eu/data/fin.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"FIN"} +{"name":"France","topLevelDomain":[".fr"],"alpha2Code":"FR","alpha3Code":"FRA","callingCodes":["33"],"capital":"Paris","altSpellings":["FR","French Republic","République française"],"region":"Europe","subregion":"Western Europe","population":66710000,"latlng":[46.0,2.0],"demonym":"French","area":640679.0,"gini":32.7,"timezones":["UTC-10:00","UTC-09:30","UTC-09:00","UTC-08:00","UTC-04:00","UTC-03:00","UTC+01:00","UTC+03:00","UTC+04:00","UTC+05:00","UTC+11:00","UTC+12:00"],"borders":["AND","BEL","DEU","ITA","LUX","MCO","ESP","CHE"],"nativeName":"France","numericCode":"250","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Frankreich","es":"Francia","fr":"France","ja":"フランス","it":"Francia","br":"França","pt":"França","nl":"Frankrijk","hr":"Francuska","fa":"فرانسه"},"flag":"https://restcountries.eu/data/fra.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"FRA"} +{"name":"French Guiana","topLevelDomain":[".gf"],"alpha2Code":"GF","alpha3Code":"GUF","callingCodes":["594"],"capital":"Cayenne","altSpellings":["GF","Guiana","Guyane"],"region":"Americas","subregion":"South America","population":254541,"latlng":[4.0,-53.0],"demonym":"","area":null,"gini":null,"timezones":["UTC-03:00"],"borders":["BRA","SUR"],"nativeName":"Guyane française","numericCode":"254","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Französisch Guyana","es":"Guayana Francesa","fr":"Guayane","ja":"フランス領ギアナ","it":"Guyana francese","br":"Guiana Francesa","pt":"Guiana Francesa","nl":"Frans-Guyana","hr":"Francuska Gvajana","fa":"گویان فرانسه"},"flag":"https://restcountries.eu/data/guf.svg","regionalBlocs":[{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]},{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":""} +{"name":"French Polynesia","topLevelDomain":[".pf"],"alpha2Code":"PF","alpha3Code":"PYF","callingCodes":["689"],"capital":"Papeetē","altSpellings":["PF","Polynésie française","French Polynesia","Pōrīnetia Farāni"],"region":"Oceania","subregion":"Polynesia","population":271800,"latlng":[-15.0,-140.0],"demonym":"French Polynesian","area":4167.0,"gini":null,"timezones":["UTC-10:00","UTC-09:30","UTC-09:00"],"borders":[],"nativeName":"Polynésie française","numericCode":"258","currencies":[{"code":"XPF","name":"CFP franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Französisch-Polynesien","es":"Polinesia Francesa","fr":"Polynésie française","ja":"フランス領ポリネシア","it":"Polinesia Francese","br":"Polinésia Francesa","pt":"Polinésia Francesa","nl":"Frans-Polynesië","hr":"Francuska Polinezija","fa":"پلی‌نزی فرانسه"},"flag":"https://restcountries.eu/data/pyf.svg","regionalBlocs":[],"cioc":""} +{"name":"French Southern Territories","topLevelDomain":[".tf"],"alpha2Code":"TF","alpha3Code":"ATF","callingCodes":[""],"capital":"Port-aux-Français","altSpellings":["TF"],"region":"Africa","subregion":"Southern Africa","population":140,"latlng":[-49.25,69.167],"demonym":"French","area":7747.0,"gini":null,"timezones":["UTC+05:00"],"borders":[],"nativeName":"Territoire des Terres australes et antarctiques françaises","numericCode":"260","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Französische Süd- und Antarktisgebiete","es":"Tierras Australes y Antárticas Francesas","fr":"Terres australes et antarctiques françaises","ja":"フランス領南方・南極地域","it":"Territori Francesi del Sud","br":"Terras Austrais e Antárticas Francesas","pt":"Terras Austrais e Antárticas Francesas","nl":"Franse Gebieden in de zuidelijke Indische Oceaan","hr":"Francuski južni i antarktički teritoriji","fa":"سرزمین‌های جنوبی و جنوبگانی فرانسه"},"flag":"https://restcountries.eu/data/atf.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":""} +{"name":"Gabon","topLevelDomain":[".ga"],"alpha2Code":"GA","alpha3Code":"GAB","callingCodes":["241"],"capital":"Libreville","altSpellings":["GA","Gabonese Republic","République Gabonaise"],"region":"Africa","subregion":"Middle Africa","population":1802278,"latlng":[-1.0,11.75],"demonym":"Gabonese","area":267668.0,"gini":41.5,"timezones":["UTC+01:00"],"borders":["CMR","COG","GNQ"],"nativeName":"Gabon","numericCode":"266","currencies":[{"code":"XAF","name":"Central African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Gabun","es":"Gabón","fr":"Gabon","ja":"ガボン","it":"Gabon","br":"Gabão","pt":"Gabão","nl":"Gabon","hr":"Gabon","fa":"گابن"},"flag":"https://restcountries.eu/data/gab.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"GAB"} +{"name":"Gambia","topLevelDomain":[".gm"],"alpha2Code":"GM","alpha3Code":"GMB","callingCodes":["220"],"capital":"Banjul","altSpellings":["GM","Republic of the Gambia"],"region":"Africa","subregion":"Western Africa","population":1882450,"latlng":[13.46666666,-16.56666666],"demonym":"Gambian","area":11295.0,"gini":null,"timezones":["UTC+00:00"],"borders":["SEN"],"nativeName":"Gambia","numericCode":"270","currencies":[{"code":"GMD","name":"Gambian dalasi","symbol":"D"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Gambia","es":"Gambia","fr":"Gambie","ja":"ガンビア","it":"Gambia","br":"Gâmbia","pt":"Gâmbia","nl":"Gambia","hr":"Gambija","fa":"گامبیا"},"flag":"https://restcountries.eu/data/gmb.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"GAM"} +{"name":"Georgia","topLevelDomain":[".ge"],"alpha2Code":"GE","alpha3Code":"GEO","callingCodes":["995"],"capital":"Tbilisi","altSpellings":["GE","Sakartvelo"],"region":"Asia","subregion":"Western Asia","population":3720400,"latlng":[42.0,43.5],"demonym":"Georgian","area":69700.0,"gini":41.3,"timezones":["UTC-05:00"],"borders":["ARM","AZE","RUS","TUR"],"nativeName":"საქართველო","numericCode":"268","currencies":[{"code":"GEL","name":"Georgian Lari","symbol":"ლ"}],"languages":[{"iso639_1":"ka","iso639_2":"kat","name":"Georgian","nativeName":"ქართული"}],"translations":{"de":"Georgien","es":"Georgia","fr":"Géorgie","ja":"グルジア","it":"Georgia","br":"Geórgia","pt":"Geórgia","nl":"Georgië","hr":"Gruzija","fa":"گرجستان"},"flag":"https://restcountries.eu/data/geo.svg","regionalBlocs":[],"cioc":"GEO"} +{"name":"Germany","topLevelDomain":[".de"],"alpha2Code":"DE","alpha3Code":"DEU","callingCodes":["49"],"capital":"Berlin","altSpellings":["DE","Federal Republic of Germany","Bundesrepublik Deutschland"],"region":"Europe","subregion":"Western Europe","population":81770900,"latlng":[51.0,9.0],"demonym":"German","area":357114.0,"gini":28.3,"timezones":["UTC+01:00"],"borders":["AUT","BEL","CZE","DNK","FRA","LUX","NLD","POL","CHE"],"nativeName":"Deutschland","numericCode":"276","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"de","iso639_2":"deu","name":"German","nativeName":"Deutsch"}],"translations":{"de":"Deutschland","es":"Alemania","fr":"Allemagne","ja":"ドイツ","it":"Germania","br":"Alemanha","pt":"Alemanha","nl":"Duitsland","hr":"Njemačka","fa":"آلمان"},"flag":"https://restcountries.eu/data/deu.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"GER"} +{"name":"Ghana","topLevelDomain":[".gh"],"alpha2Code":"GH","alpha3Code":"GHA","callingCodes":["233"],"capital":"Accra","altSpellings":["GH"],"region":"Africa","subregion":"Western Africa","population":27670174,"latlng":[8.0,-2.0],"demonym":"Ghanaian","area":238533.0,"gini":42.8,"timezones":["UTC"],"borders":["BFA","CIV","TGO"],"nativeName":"Ghana","numericCode":"288","currencies":[{"code":"GHS","name":"Ghanaian cedi","symbol":"₵"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Ghana","es":"Ghana","fr":"Ghana","ja":"ガーナ","it":"Ghana","br":"Gana","pt":"Gana","nl":"Ghana","hr":"Gana","fa":"غنا"},"flag":"https://restcountries.eu/data/gha.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"GHA"} +{"name":"Gibraltar","topLevelDomain":[".gi"],"alpha2Code":"GI","alpha3Code":"GIB","callingCodes":["350"],"capital":"Gibraltar","altSpellings":["GI"],"region":"Europe","subregion":"Southern Europe","population":33140,"latlng":[36.13333333,-5.35],"demonym":"Gibraltar","area":6.0,"gini":null,"timezones":["UTC+01:00"],"borders":["ESP"],"nativeName":"Gibraltar","numericCode":"292","currencies":[{"code":"GIP","name":"Gibraltar pound","symbol":"£"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Gibraltar","es":"Gibraltar","fr":"Gibraltar","ja":"ジブラルタル","it":"Gibilterra","br":"Gibraltar","pt":"Gibraltar","nl":"Gibraltar","hr":"Gibraltar","fa":"جبل‌طارق"},"flag":"https://restcountries.eu/data/gib.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":""} +{"name":"Greece","topLevelDomain":[".gr"],"alpha2Code":"GR","alpha3Code":"GRC","callingCodes":["30"],"capital":"Athens","altSpellings":["GR","Elláda","Hellenic Republic","Ελληνική Δημοκρατία"],"region":"Europe","subregion":"Southern Europe","population":10858018,"latlng":[39.0,22.0],"demonym":"Greek","area":131990.0,"gini":34.3,"timezones":["UTC+02:00"],"borders":["ALB","BGR","TUR","MKD"],"nativeName":"Ελλάδα","numericCode":"300","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"el","iso639_2":"ell","name":"Greek (modern)","nativeName":"ελληνικά"}],"translations":{"de":"Griechenland","es":"Grecia","fr":"Grèce","ja":"ギリシャ","it":"Grecia","br":"Grécia","pt":"Grécia","nl":"Griekenland","hr":"Grčka","fa":"یونان"},"flag":"https://restcountries.eu/data/grc.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"GRE"} +{"name":"Greenland","topLevelDomain":[".gl"],"alpha2Code":"GL","alpha3Code":"GRL","callingCodes":["299"],"capital":"Nuuk","altSpellings":["GL","Grønland"],"region":"Americas","subregion":"Northern America","population":55847,"latlng":[72.0,-40.0],"demonym":"Greenlandic","area":2166086.0,"gini":null,"timezones":["UTC-04:00","UTC-03:00","UTC-01:00","UTC+00:00"],"borders":[],"nativeName":"Kalaallit Nunaat","numericCode":"304","currencies":[{"code":"DKK","name":"Danish krone","symbol":"kr"}],"languages":[{"iso639_1":"kl","iso639_2":"kal","name":"Kalaallisut","nativeName":"kalaallisut"}],"translations":{"de":"Grönland","es":"Groenlandia","fr":"Groenland","ja":"グリーンランド","it":"Groenlandia","br":"Groelândia","pt":"Gronelândia","nl":"Groenland","hr":"Grenland","fa":"گرینلند"},"flag":"https://restcountries.eu/data/grl.svg","regionalBlocs":[],"cioc":""} +{"name":"Grenada","topLevelDomain":[".gd"],"alpha2Code":"GD","alpha3Code":"GRD","callingCodes":["1473"],"capital":"St. George's","altSpellings":["GD"],"region":"Americas","subregion":"Caribbean","population":103328,"latlng":[12.11666666,-61.66666666],"demonym":"Grenadian","area":344.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Grenada","numericCode":"308","currencies":[{"code":"XCD","name":"East Caribbean dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Grenada","es":"Grenada","fr":"Grenade","ja":"グレナダ","it":"Grenada","br":"Granada","pt":"Granada","nl":"Grenada","hr":"Grenada","fa":"گرنادا"},"flag":"https://restcountries.eu/data/grd.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]}],"cioc":"GRN"} +{"name":"Guadeloupe","topLevelDomain":[".gp"],"alpha2Code":"GP","alpha3Code":"GLP","callingCodes":["590"],"capital":"Basse-Terre","altSpellings":["GP","Gwadloup"],"region":"Americas","subregion":"Caribbean","population":400132,"latlng":[16.25,-61.583333],"demonym":"Guadeloupian","area":null,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Guadeloupe","numericCode":"312","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Guadeloupe","es":"Guadalupe","fr":"Guadeloupe","ja":"グアドループ","it":"Guadeloupa","br":"Guadalupe","pt":"Guadalupe","nl":"Guadeloupe","hr":"Gvadalupa","fa":"جزیره گوادلوپ"},"flag":"https://restcountries.eu/data/glp.svg","regionalBlocs":[],"cioc":""} +{"name":"Guam","topLevelDomain":[".gu"],"alpha2Code":"GU","alpha3Code":"GUM","callingCodes":["1671"],"capital":"Hagåtña","altSpellings":["GU","Guåhån"],"region":"Oceania","subregion":"Micronesia","population":184200,"latlng":[13.46666666,144.78333333],"demonym":"Guamanian","area":549.0,"gini":null,"timezones":["UTC+10:00"],"borders":[],"nativeName":"Guam","numericCode":"316","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"ch","iso639_2":"cha","name":"Chamorro","nativeName":"Chamoru"},{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Guam","es":"Guam","fr":"Guam","ja":"グアム","it":"Guam","br":"Guam","pt":"Guame","nl":"Guam","hr":"Guam","fa":"گوام"},"flag":"https://restcountries.eu/data/gum.svg","regionalBlocs":[],"cioc":"GUM"} +{"name":"Guatemala","topLevelDomain":[".gt"],"alpha2Code":"GT","alpha3Code":"GTM","callingCodes":["502"],"capital":"Guatemala City","altSpellings":["GT"],"region":"Americas","subregion":"Central America","population":16176133,"latlng":[15.5,-90.25],"demonym":"Guatemalan","area":108889.0,"gini":55.9,"timezones":["UTC-06:00"],"borders":["BLZ","SLV","HND","MEX"],"nativeName":"Guatemala","numericCode":"320","currencies":[{"code":"GTQ","name":"Guatemalan quetzal","symbol":"Q"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Guatemala","es":"Guatemala","fr":"Guatemala","ja":"グアテマラ","it":"Guatemala","br":"Guatemala","pt":"Guatemala","nl":"Guatemala","hr":"Gvatemala","fa":"گواتمالا"},"flag":"https://restcountries.eu/data/gtm.svg","regionalBlocs":[{"acronym":"CAIS","name":"Central American Integration System","otherAcronyms":["SICA"],"otherNames":["Sistema de la Integración Centroamericana,"]}],"cioc":"GUA"} +{"name":"Guernsey","topLevelDomain":[".gg"],"alpha2Code":"GG","alpha3Code":"GGY","callingCodes":["44"],"capital":"St. Peter Port","altSpellings":["GG","Bailiwick of Guernsey","Bailliage de Guernesey"],"region":"Europe","subregion":"Northern Europe","population":62999,"latlng":[49.46666666,-2.58333333],"demonym":"Channel Islander","area":78.0,"gini":null,"timezones":["UTC+00:00"],"borders":[],"nativeName":"Guernsey","numericCode":"831","currencies":[{"code":"GBP","name":"British pound","symbol":"£"},{"code":"(none)","name":"Guernsey pound","symbol":"£"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Guernsey","es":"Guernsey","fr":"Guernesey","ja":"ガーンジー","it":"Guernsey","br":"Guernsey","pt":"Guernsey","nl":"Guernsey","hr":"Guernsey","fa":"گرنزی"},"flag":"https://restcountries.eu/data/ggy.svg","regionalBlocs":[],"cioc":""} +{"name":"Guinea","topLevelDomain":[".gn"],"alpha2Code":"GN","alpha3Code":"GIN","callingCodes":["224"],"capital":"Conakry","altSpellings":["GN","Republic of Guinea","République de Guinée"],"region":"Africa","subregion":"Western Africa","population":12947000,"latlng":[11.0,-10.0],"demonym":"Guinean","area":245857.0,"gini":39.4,"timezones":["UTC"],"borders":["CIV","GNB","LBR","MLI","SEN","SLE"],"nativeName":"Guinée","numericCode":"324","currencies":[{"code":"GNF","name":"Guinean franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"ff","iso639_2":"ful","name":"Fula","nativeName":"Fulfulde"}],"translations":{"de":"Guinea","es":"Guinea","fr":"Guinée","ja":"ギニア","it":"Guinea","br":"Guiné","pt":"Guiné","nl":"Guinee","hr":"Gvineja","fa":"گینه"},"flag":"https://restcountries.eu/data/gin.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"GUI"} +{"name":"Guinea-Bissau","topLevelDomain":[".gw"],"alpha2Code":"GW","alpha3Code":"GNB","callingCodes":["245"],"capital":"Bissau","altSpellings":["GW","Republic of Guinea-Bissau","República da Guiné-Bissau"],"region":"Africa","subregion":"Western Africa","population":1547777,"latlng":[12.0,-15.0],"demonym":"Guinea-Bissauan","area":36125.0,"gini":35.5,"timezones":["UTC"],"borders":["GIN","SEN"],"nativeName":"Guiné-Bissau","numericCode":"624","currencies":[{"code":"XOF","name":"West African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"pt","iso639_2":"por","name":"Portuguese","nativeName":"Português"}],"translations":{"de":"Guinea-Bissau","es":"Guinea-Bisáu","fr":"Guinée-Bissau","ja":"ギニアビサウ","it":"Guinea-Bissau","br":"Guiné-Bissau","pt":"Guiné-Bissau","nl":"Guinee-Bissau","hr":"Gvineja Bisau","fa":"گینه بیسائو"},"flag":"https://restcountries.eu/data/gnb.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"GBS"} +{"name":"Guyana","topLevelDomain":[".gy"],"alpha2Code":"GY","alpha3Code":"GUY","callingCodes":["592"],"capital":"Georgetown","altSpellings":["GY","Co-operative Republic of Guyana"],"region":"Americas","subregion":"South America","population":746900,"latlng":[5.0,-59.0],"demonym":"Guyanese","area":214969.0,"gini":44.5,"timezones":["UTC-04:00"],"borders":["BRA","SUR","VEN"],"nativeName":"Guyana","numericCode":"328","currencies":[{"code":"GYD","name":"Guyanese dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Guyana","es":"Guyana","fr":"Guyane","ja":"ガイアナ","it":"Guyana","br":"Guiana","pt":"Guiana","nl":"Guyana","hr":"Gvajana","fa":"گویان"},"flag":"https://restcountries.eu/data/guy.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]},{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"GUY"} +{"name":"Haiti","topLevelDomain":[".ht"],"alpha2Code":"HT","alpha3Code":"HTI","callingCodes":["509"],"capital":"Port-au-Prince","altSpellings":["HT","Republic of Haiti","République d'Haïti","Repiblik Ayiti"],"region":"Americas","subregion":"Caribbean","population":11078033,"latlng":[19.0,-72.41666666],"demonym":"Haitian","area":27750.0,"gini":59.2,"timezones":["UTC-05:00"],"borders":["DOM"],"nativeName":"Haïti","numericCode":"332","currencies":[{"code":"HTG","name":"Haitian gourde","symbol":"G"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"ht","iso639_2":"hat","name":"Haitian","nativeName":"Kreyòl ayisyen"}],"translations":{"de":"Haiti","es":"Haiti","fr":"Haïti","ja":"ハイチ","it":"Haiti","br":"Haiti","pt":"Haiti","nl":"Haïti","hr":"Haiti","fa":"هائیتی"},"flag":"https://restcountries.eu/data/hti.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]}],"cioc":"HAI"} +{"name":"Heard Island and McDonald Islands","topLevelDomain":[".hm",".aq"],"alpha2Code":"HM","alpha3Code":"HMD","callingCodes":[""],"capital":"","altSpellings":["HM"],"region":"","subregion":"","population":0,"latlng":[-53.1,72.51666666],"demonym":"Heard and McDonald Islander","area":412.0,"gini":null,"timezones":["UTC+05:00"],"borders":[],"nativeName":"Heard Island and McDonald Islands","numericCode":"334","currencies":[{"code":"AUD","name":"Australian dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Heard und die McDonaldinseln","es":"Islas Heard y McDonald","fr":"Îles Heard-et-MacDonald","ja":"ハード島とマクドナルド諸島","it":"Isole Heard e McDonald","br":"Ilha Heard e Ilhas McDonald","pt":"Ilha Heard e Ilhas McDonald","nl":"Heard- en McDonaldeilanden","hr":"Otok Heard i otočje McDonald","fa":"جزیره هرد و جزایر مک‌دونالد"},"flag":"https://restcountries.eu/data/hmd.svg","regionalBlocs":[],"cioc":""} +{"name":"Holy See","topLevelDomain":[".va"],"alpha2Code":"VA","alpha3Code":"VAT","callingCodes":["379"],"capital":"Rome","altSpellings":["Sancta Sedes","Vatican","The Vatican"],"region":"Europe","subregion":"Southern Europe","population":451,"latlng":[41.9,12.45],"demonym":"","area":0.44,"gini":null,"timezones":["UTC+01:00"],"borders":["ITA"],"nativeName":"Sancta Sedes","numericCode":"336","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"la","iso639_2":"lat","name":"Latin","nativeName":"latine"},{"iso639_1":"it","iso639_2":"ita","name":"Italian","nativeName":"Italiano"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"de","iso639_2":"deu","name":"German","nativeName":"Deutsch"}],"translations":{"de":"Heiliger Stuhl","es":"Santa Sede","fr":"voir Saint","ja":"聖座","it":"Santa Sede","br":"Vaticano","pt":"Vaticano","nl":"Heilige Stoel","hr":"Sveta Stolica","fa":"سریر مقدس"},"flag":"https://restcountries.eu/data/vat.svg","regionalBlocs":[],"cioc":""} +{"name":"Honduras","topLevelDomain":[".hn"],"alpha2Code":"HN","alpha3Code":"HND","callingCodes":["504"],"capital":"Tegucigalpa","altSpellings":["HN","Republic of Honduras","República de Honduras"],"region":"Americas","subregion":"Central America","population":8576532,"latlng":[15.0,-86.5],"demonym":"Honduran","area":112492.0,"gini":57.0,"timezones":["UTC-06:00"],"borders":["GTM","SLV","NIC"],"nativeName":"Honduras","numericCode":"340","currencies":[{"code":"HNL","name":"Honduran lempira","symbol":"L"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Honduras","es":"Honduras","fr":"Honduras","ja":"ホンジュラス","it":"Honduras","br":"Honduras","pt":"Honduras","nl":"Honduras","hr":"Honduras","fa":"هندوراس"},"flag":"https://restcountries.eu/data/hnd.svg","regionalBlocs":[{"acronym":"CAIS","name":"Central American Integration System","otherAcronyms":["SICA"],"otherNames":["Sistema de la Integración Centroamericana,"]}],"cioc":"HON"} +{"name":"Hong Kong","topLevelDomain":[".hk"],"alpha2Code":"HK","alpha3Code":"HKG","callingCodes":["852"],"capital":"City of Victoria","altSpellings":["HK","香港"],"region":"Asia","subregion":"Eastern Asia","population":7324300,"latlng":[22.25,114.16666666],"demonym":"Chinese","area":1104.0,"gini":53.3,"timezones":["UTC+08:00"],"borders":["CHN"],"nativeName":"香港","numericCode":"344","currencies":[{"code":"HKD","name":"Hong Kong dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"zh","iso639_2":"zho","name":"Chinese","nativeName":"中文 (Zhōngwén)"}],"translations":{"de":"Hong Kong","es":"Hong Kong","fr":"Hong Kong","ja":"香港","it":"Hong Kong","br":"Hong Kong","pt":"Hong Kong","nl":"Hongkong","hr":"Hong Kong","fa":"هنگ‌کنگ"},"flag":"https://restcountries.eu/data/hkg.svg","regionalBlocs":[],"cioc":"HKG"} +{"name":"Hungary","topLevelDomain":[".hu"],"alpha2Code":"HU","alpha3Code":"HUN","callingCodes":["36"],"capital":"Budapest","altSpellings":["HU"],"region":"Europe","subregion":"Eastern Europe","population":9823000,"latlng":[47.0,20.0],"demonym":"Hungarian","area":93028.0,"gini":31.2,"timezones":["UTC+01:00"],"borders":["AUT","HRV","ROU","SRB","SVK","SVN","UKR"],"nativeName":"Magyarország","numericCode":"348","currencies":[{"code":"HUF","name":"Hungarian forint","symbol":"Ft"}],"languages":[{"iso639_1":"hu","iso639_2":"hun","name":"Hungarian","nativeName":"magyar"}],"translations":{"de":"Ungarn","es":"Hungría","fr":"Hongrie","ja":"ハンガリー","it":"Ungheria","br":"Hungria","pt":"Hungria","nl":"Hongarije","hr":"Mađarska","fa":"مجارستان"},"flag":"https://restcountries.eu/data/hun.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"HUN"} +{"name":"Iceland","topLevelDomain":[".is"],"alpha2Code":"IS","alpha3Code":"ISL","callingCodes":["354"],"capital":"Reykjavík","altSpellings":["IS","Island","Republic of Iceland","Lýðveldið Ísland"],"region":"Europe","subregion":"Northern Europe","population":334300,"latlng":[65.0,-18.0],"demonym":"Icelander","area":103000.0,"gini":null,"timezones":["UTC"],"borders":[],"nativeName":"Ísland","numericCode":"352","currencies":[{"code":"ISK","name":"Icelandic króna","symbol":"kr"}],"languages":[{"iso639_1":"is","iso639_2":"isl","name":"Icelandic","nativeName":"Íslenska"}],"translations":{"de":"Island","es":"Islandia","fr":"Islande","ja":"アイスランド","it":"Islanda","br":"Islândia","pt":"Islândia","nl":"IJsland","hr":"Island","fa":"ایسلند"},"flag":"https://restcountries.eu/data/isl.svg","regionalBlocs":[{"acronym":"EFTA","name":"European Free Trade Association","otherAcronyms":[],"otherNames":[]}],"cioc":"ISL"} +{"name":"India","topLevelDomain":[".in"],"alpha2Code":"IN","alpha3Code":"IND","callingCodes":["91"],"capital":"New Delhi","altSpellings":["IN","Bhārat","Republic of India","Bharat Ganrajya"],"region":"Asia","subregion":"Southern Asia","population":1295210000,"latlng":[20.0,77.0],"demonym":"Indian","area":3287590.0,"gini":33.4,"timezones":["UTC+05:30"],"borders":["AFG","BGD","BTN","MMR","CHN","NPL","PAK","LKA"],"nativeName":"भारत","numericCode":"356","currencies":[{"code":"INR","name":"Indian rupee","symbol":"₹"}],"languages":[{"iso639_1":"hi","iso639_2":"hin","name":"Hindi","nativeName":"हिन्दी"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Indien","es":"India","fr":"Inde","ja":"インド","it":"India","br":"Índia","pt":"Índia","nl":"India","hr":"Indija","fa":"هند"},"flag":"https://restcountries.eu/data/ind.svg","regionalBlocs":[{"acronym":"SAARC","name":"South Asian Association for Regional Cooperation","otherAcronyms":[],"otherNames":[]}],"cioc":"IND"} +{"name":"Indonesia","topLevelDomain":[".id"],"alpha2Code":"ID","alpha3Code":"IDN","callingCodes":["62"],"capital":"Jakarta","altSpellings":["ID","Republic of Indonesia","Republik Indonesia"],"region":"Asia","subregion":"South-Eastern Asia","population":258705000,"latlng":[-5.0,120.0],"demonym":"Indonesian","area":1904569.0,"gini":34.0,"timezones":["UTC+07:00","UTC+08:00","UTC+09:00"],"borders":["TLS","MYS","PNG"],"nativeName":"Indonesia","numericCode":"360","currencies":[{"code":"IDR","name":"Indonesian rupiah","symbol":"Rp"}],"languages":[{"iso639_1":"id","iso639_2":"ind","name":"Indonesian","nativeName":"Bahasa Indonesia"}],"translations":{"de":"Indonesien","es":"Indonesia","fr":"Indonésie","ja":"インドネシア","it":"Indonesia","br":"Indonésia","pt":"Indonésia","nl":"Indonesië","hr":"Indonezija","fa":"اندونزی"},"flag":"https://restcountries.eu/data/idn.svg","regionalBlocs":[{"acronym":"ASEAN","name":"Association of Southeast Asian Nations","otherAcronyms":[],"otherNames":[]}],"cioc":"INA"} +{"name":"Côte d'Ivoire","topLevelDomain":[".ci"],"alpha2Code":"CI","alpha3Code":"CIV","callingCodes":["225"],"capital":"Yamoussoukro","altSpellings":["CI","Ivory Coast","Republic of Côte d'Ivoire","République de Côte d'Ivoire"],"region":"Africa","subregion":"Western Africa","population":22671331,"latlng":[8.0,-5.0],"demonym":"Ivorian","area":322463.0,"gini":41.5,"timezones":["UTC"],"borders":["BFA","GHA","GIN","LBR","MLI"],"nativeName":"Côte d'Ivoire","numericCode":"384","currencies":[{"code":"XOF","name":"West African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Elfenbeinküste","es":"Costa de Marfil","fr":"Côte d'Ivoire","ja":"コートジボワール","it":"Costa D'Avorio","br":"Costa do Marfim","pt":"Costa do Marfim","nl":"Ivoorkust","hr":"Obala Bjelokosti","fa":"ساحل عاج"},"flag":"https://restcountries.eu/data/civ.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"CIV"} +{"name":"Iran (Islamic Republic of)","topLevelDomain":[".ir"],"alpha2Code":"IR","alpha3Code":"IRN","callingCodes":["98"],"capital":"Tehran","altSpellings":["IR","Islamic Republic of Iran","Jomhuri-ye Eslāmi-ye Irān"],"region":"Asia","subregion":"Southern Asia","population":79369900,"latlng":[32.0,53.0],"demonym":"Iranian","area":1648195.0,"gini":38.3,"timezones":["UTC+03:30"],"borders":["AFG","ARM","AZE","IRQ","PAK","TUR","TKM"],"nativeName":"ایران","numericCode":"364","currencies":[{"code":"IRR","name":"Iranian rial","symbol":"﷼"}],"languages":[{"iso639_1":"fa","iso639_2":"fas","name":"Persian (Farsi)","nativeName":"فارسی"}],"translations":{"de":"Iran","es":"Iran","fr":"Iran","ja":"イラン・イスラム共和国","it":null,"br":"Irã","pt":"Irão","nl":"Iran","hr":"Iran","fa":"ایران"},"flag":"https://restcountries.eu/data/irn.svg","regionalBlocs":[],"cioc":"IRI"} +{"name":"Iraq","topLevelDomain":[".iq"],"alpha2Code":"IQ","alpha3Code":"IRQ","callingCodes":["964"],"capital":"Baghdad","altSpellings":["IQ","Republic of Iraq","Jumhūriyyat al-‘Irāq"],"region":"Asia","subregion":"Western Asia","population":37883543,"latlng":[33.0,44.0],"demonym":"Iraqi","area":438317.0,"gini":30.9,"timezones":["UTC+03:00"],"borders":["IRN","JOR","KWT","SAU","SYR","TUR"],"nativeName":"العراق","numericCode":"368","currencies":[{"code":"IQD","name":"Iraqi dinar","symbol":"ع.د"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"},{"iso639_1":"ku","iso639_2":"kur","name":"Kurdish","nativeName":"Kurdî"}],"translations":{"de":"Irak","es":"Irak","fr":"Irak","ja":"イラク","it":"Iraq","br":"Iraque","pt":"Iraque","nl":"Irak","hr":"Irak","fa":"عراق"},"flag":"https://restcountries.eu/data/irq.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"IRQ"} +{"name":"Ireland","topLevelDomain":[".ie"],"alpha2Code":"IE","alpha3Code":"IRL","callingCodes":["353"],"capital":"Dublin","altSpellings":["IE","Éire","Republic of Ireland","Poblacht na hÉireann"],"region":"Europe","subregion":"Northern Europe","population":6378000,"latlng":[53.0,-8.0],"demonym":"Irish","area":70273.0,"gini":34.3,"timezones":["UTC"],"borders":["GBR"],"nativeName":"Éire","numericCode":"372","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"ga","iso639_2":"gle","name":"Irish","nativeName":"Gaeilge"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Irland","es":"Irlanda","fr":"Irlande","ja":"アイルランド","it":"Irlanda","br":"Irlanda","pt":"Irlanda","nl":"Ierland","hr":"Irska","fa":"ایرلند"},"flag":"https://restcountries.eu/data/irl.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"IRL"} +{"name":"Isle of Man","topLevelDomain":[".im"],"alpha2Code":"IM","alpha3Code":"IMN","callingCodes":["44"],"capital":"Douglas","altSpellings":["IM","Ellan Vannin","Mann","Mannin"],"region":"Europe","subregion":"Northern Europe","population":84497,"latlng":[54.25,-4.5],"demonym":"Manx","area":572.0,"gini":null,"timezones":["UTC+00:00"],"borders":[],"nativeName":"Isle of Man","numericCode":"833","currencies":[{"code":"GBP","name":"British pound","symbol":"£"},{"code":"IMP[G]","name":"Manx pound","symbol":"£"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"gv","iso639_2":"glv","name":"Manx","nativeName":"Gaelg"}],"translations":{"de":"Insel Man","es":"Isla de Man","fr":"Île de Man","ja":"マン島","it":"Isola di Man","br":"Ilha de Man","pt":"Ilha de Man","nl":"Isle of Man","hr":"Otok Man","fa":"جزیره من"},"flag":"https://restcountries.eu/data/imn.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":""} +{"name":"Israel","topLevelDomain":[".il"],"alpha2Code":"IL","alpha3Code":"ISR","callingCodes":["972"],"capital":"Jerusalem","altSpellings":["IL","State of Israel","Medīnat Yisrā'el"],"region":"Asia","subregion":"Western Asia","population":8527400,"latlng":[31.5,34.75],"demonym":"Israeli","area":20770.0,"gini":39.2,"timezones":["UTC+02:00"],"borders":["EGY","JOR","LBN","SYR"],"nativeName":"יִשְׂרָאֵל","numericCode":"376","currencies":[{"code":"ILS","name":"Israeli new shekel","symbol":"₪"}],"languages":[{"iso639_1":"he","iso639_2":"heb","name":"Hebrew (modern)","nativeName":"עברית"},{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Israel","es":"Israel","fr":"Israël","ja":"イスラエル","it":"Israele","br":"Israel","pt":"Israel","nl":"Israël","hr":"Izrael","fa":"اسرائیل"},"flag":"https://restcountries.eu/data/isr.svg","regionalBlocs":[],"cioc":"ISR"} +{"name":"Italy","topLevelDomain":[".it"],"alpha2Code":"IT","alpha3Code":"ITA","callingCodes":["39"],"capital":"Rome","altSpellings":["IT","Italian Republic","Repubblica italiana"],"region":"Europe","subregion":"Southern Europe","population":60665551,"latlng":[42.83333333,12.83333333],"demonym":"Italian","area":301336.0,"gini":36.0,"timezones":["UTC+01:00"],"borders":["AUT","FRA","SMR","SVN","CHE","VAT"],"nativeName":"Italia","numericCode":"380","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"it","iso639_2":"ita","name":"Italian","nativeName":"Italiano"}],"translations":{"de":"Italien","es":"Italia","fr":"Italie","ja":"イタリア","it":"Italia","br":"Itália","pt":"Itália","nl":"Italië","hr":"Italija","fa":"ایتالیا"},"flag":"https://restcountries.eu/data/ita.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"ITA"} +{"name":"Jamaica","topLevelDomain":[".jm"],"alpha2Code":"JM","alpha3Code":"JAM","callingCodes":["1876"],"capital":"Kingston","altSpellings":["JM"],"region":"Americas","subregion":"Caribbean","population":2723246,"latlng":[18.25,-77.5],"demonym":"Jamaican","area":10991.0,"gini":45.5,"timezones":["UTC-05:00"],"borders":[],"nativeName":"Jamaica","numericCode":"388","currencies":[{"code":"JMD","name":"Jamaican dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Jamaika","es":"Jamaica","fr":"Jamaïque","ja":"ジャマイカ","it":"Giamaica","br":"Jamaica","pt":"Jamaica","nl":"Jamaica","hr":"Jamajka","fa":"جامائیکا"},"flag":"https://restcountries.eu/data/jam.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]}],"cioc":"JAM"} +{"name":"Japan","topLevelDomain":[".jp"],"alpha2Code":"JP","alpha3Code":"JPN","callingCodes":["81"],"capital":"Tokyo","altSpellings":["JP","Nippon","Nihon"],"region":"Asia","subregion":"Eastern Asia","population":126960000,"latlng":[36.0,138.0],"demonym":"Japanese","area":377930.0,"gini":38.1,"timezones":["UTC+09:00"],"borders":[],"nativeName":"日本","numericCode":"392","currencies":[{"code":"JPY","name":"Japanese yen","symbol":"¥"}],"languages":[{"iso639_1":"ja","iso639_2":"jpn","name":"Japanese","nativeName":"日本語 (にほんご)"}],"translations":{"de":"Japan","es":"Japón","fr":"Japon","ja":"日本","it":"Giappone","br":"Japão","pt":"Japão","nl":"Japan","hr":"Japan","fa":"ژاپن"},"flag":"https://restcountries.eu/data/jpn.svg","regionalBlocs":[],"cioc":"JPN"} +{"name":"Jersey","topLevelDomain":[".je"],"alpha2Code":"JE","alpha3Code":"JEY","callingCodes":["44"],"capital":"Saint Helier","altSpellings":["JE","Bailiwick of Jersey","Bailliage de Jersey","Bailliage dé Jèrri"],"region":"Europe","subregion":"Northern Europe","population":100800,"latlng":[49.25,-2.16666666],"demonym":"Channel Islander","area":116.0,"gini":null,"timezones":["UTC+01:00"],"borders":[],"nativeName":"Jersey","numericCode":"832","currencies":[{"code":"GBP","name":"British pound","symbol":"£"},{"code":"JEP[G]","name":"Jersey pound","symbol":"£"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Jersey","es":"Jersey","fr":"Jersey","ja":"ジャージー","it":"Isola di Jersey","br":"Jersey","pt":"Jersey","nl":"Jersey","hr":"Jersey","fa":"جرزی"},"flag":"https://restcountries.eu/data/jey.svg","regionalBlocs":[],"cioc":""} +{"name":"Jordan","topLevelDomain":[".jo"],"alpha2Code":"JO","alpha3Code":"JOR","callingCodes":["962"],"capital":"Amman","altSpellings":["JO","Hashemite Kingdom of Jordan","al-Mamlakah al-Urdunīyah al-Hāshimīyah"],"region":"Asia","subregion":"Western Asia","population":9531712,"latlng":[31.0,36.0],"demonym":"Jordanian","area":89342.0,"gini":35.4,"timezones":["UTC+03:00"],"borders":["IRQ","ISR","SAU","SYR"],"nativeName":"الأردن","numericCode":"400","currencies":[{"code":"JOD","name":"Jordanian dinar","symbol":"د.ا"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Jordanien","es":"Jordania","fr":"Jordanie","ja":"ヨルダン","it":"Giordania","br":"Jordânia","pt":"Jordânia","nl":"Jordanië","hr":"Jordan","fa":"اردن"},"flag":"https://restcountries.eu/data/jor.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"JOR"} +{"name":"Kazakhstan","topLevelDomain":[".kz",".қаз"],"alpha2Code":"KZ","alpha3Code":"KAZ","callingCodes":["76","77"],"capital":"Astana","altSpellings":["KZ","Qazaqstan","Казахстан","Republic of Kazakhstan","Қазақстан Республикасы","Qazaqstan Respublïkası","Республика Казахстан","Respublika Kazakhstan"],"region":"Asia","subregion":"Central Asia","population":17753200,"latlng":[48.0,68.0],"demonym":"Kazakhstani","area":2724900.0,"gini":29.0,"timezones":["UTC+05:00","UTC+06:00"],"borders":["CHN","KGZ","RUS","TKM","UZB"],"nativeName":"Қазақстан","numericCode":"398","currencies":[{"code":"KZT","name":"Kazakhstani tenge","symbol":null}],"languages":[{"iso639_1":"kk","iso639_2":"kaz","name":"Kazakh","nativeName":"қазақ тілі"},{"iso639_1":"ru","iso639_2":"rus","name":"Russian","nativeName":"Русский"}],"translations":{"de":"Kasachstan","es":"Kazajistán","fr":"Kazakhstan","ja":"カザフスタン","it":"Kazakistan","br":"Cazaquistão","pt":"Cazaquistão","nl":"Kazachstan","hr":"Kazahstan","fa":"قزاقستان"},"flag":"https://restcountries.eu/data/kaz.svg","regionalBlocs":[{"acronym":"EEU","name":"Eurasian Economic Union","otherAcronyms":["EAEU"],"otherNames":[]}],"cioc":"KAZ"} +{"name":"Kenya","topLevelDomain":[".ke"],"alpha2Code":"KE","alpha3Code":"KEN","callingCodes":["254"],"capital":"Nairobi","altSpellings":["KE","Republic of Kenya","Jamhuri ya Kenya"],"region":"Africa","subregion":"Eastern Africa","population":47251000,"latlng":[1.0,38.0],"demonym":"Kenyan","area":580367.0,"gini":47.7,"timezones":["UTC+03:00"],"borders":["ETH","SOM","SSD","TZA","UGA"],"nativeName":"Kenya","numericCode":"404","currencies":[{"code":"KES","name":"Kenyan shilling","symbol":"Sh"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"sw","iso639_2":"swa","name":"Swahili","nativeName":"Kiswahili"}],"translations":{"de":"Kenia","es":"Kenia","fr":"Kenya","ja":"ケニア","it":"Kenya","br":"Quênia","pt":"Quénia","nl":"Kenia","hr":"Kenija","fa":"کنیا"},"flag":"https://restcountries.eu/data/ken.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"KEN"} +{"name":"Kiribati","topLevelDomain":[".ki"],"alpha2Code":"KI","alpha3Code":"KIR","callingCodes":["686"],"capital":"South Tarawa","altSpellings":["KI","Republic of Kiribati","Ribaberiki Kiribati"],"region":"Oceania","subregion":"Micronesia","population":113400,"latlng":[1.41666666,173.0],"demonym":"I-Kiribati","area":811.0,"gini":null,"timezones":["UTC+12:00","UTC+13:00","UTC+14:00"],"borders":[],"nativeName":"Kiribati","numericCode":"296","currencies":[{"code":"AUD","name":"Australian dollar","symbol":"$"},{"code":"(none)","name":"Kiribati dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Kiribati","es":"Kiribati","fr":"Kiribati","ja":"キリバス","it":"Kiribati","br":"Kiribati","pt":"Quiribáti","nl":"Kiribati","hr":"Kiribati","fa":"کیریباتی"},"flag":"https://restcountries.eu/data/kir.svg","regionalBlocs":[],"cioc":"KIR"} +{"name":"Kuwait","topLevelDomain":[".kw"],"alpha2Code":"KW","alpha3Code":"KWT","callingCodes":["965"],"capital":"Kuwait City","altSpellings":["KW","State of Kuwait","Dawlat al-Kuwait"],"region":"Asia","subregion":"Western Asia","population":4183658,"latlng":[29.5,45.75],"demonym":"Kuwaiti","area":17818.0,"gini":null,"timezones":["UTC+03:00"],"borders":["IRN","SAU"],"nativeName":"الكويت","numericCode":"414","currencies":[{"code":"KWD","name":"Kuwaiti dinar","symbol":"د.ك"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Kuwait","es":"Kuwait","fr":"Koweït","ja":"クウェート","it":"Kuwait","br":"Kuwait","pt":"Kuwait","nl":"Koeweit","hr":"Kuvajt","fa":"کویت"},"flag":"https://restcountries.eu/data/kwt.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"KUW"} +{"name":"Kyrgyzstan","topLevelDomain":[".kg"],"alpha2Code":"KG","alpha3Code":"KGZ","callingCodes":["996"],"capital":"Bishkek","altSpellings":["KG","Киргизия","Kyrgyz Republic","Кыргыз Республикасы","Kyrgyz Respublikasy"],"region":"Asia","subregion":"Central Asia","population":6047800,"latlng":[41.0,75.0],"demonym":"Kirghiz","area":199951.0,"gini":36.2,"timezones":["UTC+06:00"],"borders":["CHN","KAZ","TJK","UZB"],"nativeName":"Кыргызстан","numericCode":"417","currencies":[{"code":"KGS","name":"Kyrgyzstani som","symbol":"с"}],"languages":[{"iso639_1":"ky","iso639_2":"kir","name":"Kyrgyz","nativeName":"Кыргызча"},{"iso639_1":"ru","iso639_2":"rus","name":"Russian","nativeName":"Русский"}],"translations":{"de":"Kirgisistan","es":"Kirguizistán","fr":"Kirghizistan","ja":"キルギス","it":"Kirghizistan","br":"Quirguistão","pt":"Quirguizistão","nl":"Kirgizië","hr":"Kirgistan","fa":"قرقیزستان"},"flag":"https://restcountries.eu/data/kgz.svg","regionalBlocs":[{"acronym":"EEU","name":"Eurasian Economic Union","otherAcronyms":["EAEU"],"otherNames":[]}],"cioc":"KGZ"} +{"name":"Lao People's Democratic Republic","topLevelDomain":[".la"],"alpha2Code":"LA","alpha3Code":"LAO","callingCodes":["856"],"capital":"Vientiane","altSpellings":["LA","Lao","Laos","Lao People's Democratic Republic","Sathalanalat Paxathipatai Paxaxon Lao"],"region":"Asia","subregion":"South-Eastern Asia","population":6492400,"latlng":[18.0,105.0],"demonym":"Laotian","area":236800.0,"gini":36.7,"timezones":["UTC+07:00"],"borders":["MMR","KHM","CHN","THA","VNM"],"nativeName":"ສປປລາວ","numericCode":"418","currencies":[{"code":"LAK","name":"Lao kip","symbol":"₭"}],"languages":[{"iso639_1":"lo","iso639_2":"lao","name":"Lao","nativeName":"ພາສາລາວ"}],"translations":{"de":"Laos","es":"Laos","fr":"Laos","ja":"ラオス人民民主共和国","it":"Laos","br":"Laos","pt":"Laos","nl":"Laos","hr":"Laos","fa":"لائوس"},"flag":"https://restcountries.eu/data/lao.svg","regionalBlocs":[{"acronym":"ASEAN","name":"Association of Southeast Asian Nations","otherAcronyms":[],"otherNames":[]}],"cioc":"LAO"} +{"name":"Latvia","topLevelDomain":[".lv"],"alpha2Code":"LV","alpha3Code":"LVA","callingCodes":["371"],"capital":"Riga","altSpellings":["LV","Republic of Latvia","Latvijas Republika"],"region":"Europe","subregion":"Northern Europe","population":1961600,"latlng":[57.0,25.0],"demonym":"Latvian","area":64559.0,"gini":36.6,"timezones":["UTC+02:00"],"borders":["BLR","EST","LTU","RUS"],"nativeName":"Latvija","numericCode":"428","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"lv","iso639_2":"lav","name":"Latvian","nativeName":"latviešu valoda"}],"translations":{"de":"Lettland","es":"Letonia","fr":"Lettonie","ja":"ラトビア","it":"Lettonia","br":"Letônia","pt":"Letónia","nl":"Letland","hr":"Latvija","fa":"لتونی"},"flag":"https://restcountries.eu/data/lva.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"LAT"} +{"name":"Lebanon","topLevelDomain":[".lb"],"alpha2Code":"LB","alpha3Code":"LBN","callingCodes":["961"],"capital":"Beirut","altSpellings":["LB","Lebanese Republic","Al-Jumhūrīyah Al-Libnānīyah"],"region":"Asia","subregion":"Western Asia","population":5988000,"latlng":[33.83333333,35.83333333],"demonym":"Lebanese","area":10452.0,"gini":null,"timezones":["UTC+02:00"],"borders":["ISR","SYR"],"nativeName":"لبنان","numericCode":"422","currencies":[{"code":"LBP","name":"Lebanese pound","symbol":"ل.ل"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Libanon","es":"Líbano","fr":"Liban","ja":"レバノン","it":"Libano","br":"Líbano","pt":"Líbano","nl":"Libanon","hr":"Libanon","fa":"لبنان"},"flag":"https://restcountries.eu/data/lbn.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"LIB"} +{"name":"Lesotho","topLevelDomain":[".ls"],"alpha2Code":"LS","alpha3Code":"LSO","callingCodes":["266"],"capital":"Maseru","altSpellings":["LS","Kingdom of Lesotho","Muso oa Lesotho"],"region":"Africa","subregion":"Southern Africa","population":1894194,"latlng":[-29.5,28.5],"demonym":"Mosotho","area":30355.0,"gini":52.5,"timezones":["UTC+02:00"],"borders":["ZAF"],"nativeName":"Lesotho","numericCode":"426","currencies":[{"code":"LSL","name":"Lesotho loti","symbol":"L"},{"code":"ZAR","name":"South African rand","symbol":"R"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"st","iso639_2":"sot","name":"Southern Sotho","nativeName":"Sesotho"}],"translations":{"de":"Lesotho","es":"Lesotho","fr":"Lesotho","ja":"レソト","it":"Lesotho","br":"Lesoto","pt":"Lesoto","nl":"Lesotho","hr":"Lesoto","fa":"لسوتو"},"flag":"https://restcountries.eu/data/lso.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"LES"} +{"name":"Liberia","topLevelDomain":[".lr"],"alpha2Code":"LR","alpha3Code":"LBR","callingCodes":["231"],"capital":"Monrovia","altSpellings":["LR","Republic of Liberia"],"region":"Africa","subregion":"Western Africa","population":4615000,"latlng":[6.5,-9.5],"demonym":"Liberian","area":111369.0,"gini":38.2,"timezones":["UTC"],"borders":["GIN","CIV","SLE"],"nativeName":"Liberia","numericCode":"430","currencies":[{"code":"LRD","name":"Liberian dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Liberia","es":"Liberia","fr":"Liberia","ja":"リベリア","it":"Liberia","br":"Libéria","pt":"Libéria","nl":"Liberia","hr":"Liberija","fa":"لیبریا"},"flag":"https://restcountries.eu/data/lbr.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"LBR"} +{"name":"Libya","topLevelDomain":[".ly"],"alpha2Code":"LY","alpha3Code":"LBY","callingCodes":["218"],"capital":"Tripoli","altSpellings":["LY","State of Libya","Dawlat Libya"],"region":"Africa","subregion":"Northern Africa","population":6385000,"latlng":[25.0,17.0],"demonym":"Libyan","area":1759540.0,"gini":null,"timezones":["UTC+01:00"],"borders":["DZA","TCD","EGY","NER","SDN","TUN"],"nativeName":"‏ليبيا","numericCode":"434","currencies":[{"code":"LYD","name":"Libyan dinar","symbol":"ل.د"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Libyen","es":"Libia","fr":"Libye","ja":"リビア","it":"Libia","br":"Líbia","pt":"Líbia","nl":"Libië","hr":"Libija","fa":"لیبی"},"flag":"https://restcountries.eu/data/lby.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]},{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"LBA"} +{"name":"Liechtenstein","topLevelDomain":[".li"],"alpha2Code":"LI","alpha3Code":"LIE","callingCodes":["423"],"capital":"Vaduz","altSpellings":["LI","Principality of Liechtenstein","Fürstentum Liechtenstein"],"region":"Europe","subregion":"Western Europe","population":37623,"latlng":[47.26666666,9.53333333],"demonym":"Liechtensteiner","area":160.0,"gini":null,"timezones":["UTC+01:00"],"borders":["AUT","CHE"],"nativeName":"Liechtenstein","numericCode":"438","currencies":[{"code":"CHF","name":"Swiss franc","symbol":"Fr"}],"languages":[{"iso639_1":"de","iso639_2":"deu","name":"German","nativeName":"Deutsch"}],"translations":{"de":"Liechtenstein","es":"Liechtenstein","fr":"Liechtenstein","ja":"リヒテンシュタイン","it":"Liechtenstein","br":"Liechtenstein","pt":"Listenstaine","nl":"Liechtenstein","hr":"Lihtenštajn","fa":"لیختن‌اشتاین"},"flag":"https://restcountries.eu/data/lie.svg","regionalBlocs":[{"acronym":"EFTA","name":"European Free Trade Association","otherAcronyms":[],"otherNames":[]}],"cioc":"LIE"} +{"name":"Lithuania","topLevelDomain":[".lt"],"alpha2Code":"LT","alpha3Code":"LTU","callingCodes":["370"],"capital":"Vilnius","altSpellings":["LT","Republic of Lithuania","Lietuvos Respublika"],"region":"Europe","subregion":"Northern Europe","population":2872294,"latlng":[56.0,24.0],"demonym":"Lithuanian","area":65300.0,"gini":37.6,"timezones":["UTC+02:00"],"borders":["BLR","LVA","POL","RUS"],"nativeName":"Lietuva","numericCode":"440","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"lt","iso639_2":"lit","name":"Lithuanian","nativeName":"lietuvių kalba"}],"translations":{"de":"Litauen","es":"Lituania","fr":"Lituanie","ja":"リトアニア","it":"Lituania","br":"Lituânia","pt":"Lituânia","nl":"Litouwen","hr":"Litva","fa":"لیتوانی"},"flag":"https://restcountries.eu/data/ltu.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"LTU"} +{"name":"Luxembourg","topLevelDomain":[".lu"],"alpha2Code":"LU","alpha3Code":"LUX","callingCodes":["352"],"capital":"Luxembourg","altSpellings":["LU","Grand Duchy of Luxembourg","Grand-Duché de Luxembourg","Großherzogtum Luxemburg","Groussherzogtum Lëtzebuerg"],"region":"Europe","subregion":"Western Europe","population":576200,"latlng":[49.75,6.16666666],"demonym":"Luxembourger","area":2586.0,"gini":30.8,"timezones":["UTC+01:00"],"borders":["BEL","FRA","DEU"],"nativeName":"Luxembourg","numericCode":"442","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"de","iso639_2":"deu","name":"German","nativeName":"Deutsch"},{"iso639_1":"lb","iso639_2":"ltz","name":"Luxembourgish","nativeName":"Lëtzebuergesch"}],"translations":{"de":"Luxemburg","es":"Luxemburgo","fr":"Luxembourg","ja":"ルクセンブルク","it":"Lussemburgo","br":"Luxemburgo","pt":"Luxemburgo","nl":"Luxemburg","hr":"Luksemburg","fa":"لوکزامبورگ"},"flag":"https://restcountries.eu/data/lux.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"LUX"} +{"name":"Macao","topLevelDomain":[".mo"],"alpha2Code":"MO","alpha3Code":"MAC","callingCodes":["853"],"capital":"","altSpellings":["MO","澳门","Macao Special Administrative Region of the People's Republic of China","中華人民共和國澳門特別行政區","Região Administrativa Especial de Macau da República Popular da China"],"region":"Asia","subregion":"Eastern Asia","population":649100,"latlng":[22.16666666,113.55],"demonym":"Chinese","area":30.0,"gini":null,"timezones":["UTC+08:00"],"borders":["CHN"],"nativeName":"澳門","numericCode":"446","currencies":[{"code":"MOP","name":"Macanese pataca","symbol":"P"}],"languages":[{"iso639_1":"zh","iso639_2":"zho","name":"Chinese","nativeName":"中文 (Zhōngwén)"},{"iso639_1":"pt","iso639_2":"por","name":"Portuguese","nativeName":"Português"}],"translations":{"de":"Macao","es":"Macao","fr":"Macao","ja":"マカオ","it":"Macao","br":"Macau","pt":"Macau","nl":"Macao","hr":"Makao","fa":"مکائو"},"flag":"https://restcountries.eu/data/mac.svg","regionalBlocs":[],"cioc":""} +{"name":"Macedonia (the former Yugoslav Republic of)","topLevelDomain":[".mk"],"alpha2Code":"MK","alpha3Code":"MKD","callingCodes":["389"],"capital":"Skopje","altSpellings":["MK","Republic of Macedonia","Република Македонија"],"region":"Europe","subregion":"Southern Europe","population":2058539,"latlng":[41.83333333,22.0],"demonym":"Macedonian","area":25713.0,"gini":43.2,"timezones":["UTC+01:00"],"borders":["ALB","BGR","GRC","KOS","SRB"],"nativeName":"Македонија","numericCode":"807","currencies":[{"code":"MKD","name":"Macedonian denar","symbol":"ден"}],"languages":[{"iso639_1":"mk","iso639_2":"mkd","name":"Macedonian","nativeName":"македонски јазик"}],"translations":{"de":"Mazedonien","es":"Macedonia","fr":"Macédoine","ja":"マケドニア旧ユーゴスラビア共和国","it":"Macedonia","br":"Macedônia","pt":"Macedónia","nl":"Macedonië","hr":"Makedonija","fa":""},"flag":"https://restcountries.eu/data/mkd.svg","regionalBlocs":[{"acronym":"CEFTA","name":"Central European Free Trade Agreement","otherAcronyms":[],"otherNames":[]}],"cioc":"MKD"} +{"name":"Madagascar","topLevelDomain":[".mg"],"alpha2Code":"MG","alpha3Code":"MDG","callingCodes":["261"],"capital":"Antananarivo","altSpellings":["MG","Republic of Madagascar","Repoblikan'i Madagasikara","République de Madagascar"],"region":"Africa","subregion":"Eastern Africa","population":22434363,"latlng":[-20.0,47.0],"demonym":"Malagasy","area":587041.0,"gini":44.1,"timezones":["UTC+03:00"],"borders":[],"nativeName":"Madagasikara","numericCode":"450","currencies":[{"code":"MGA","name":"Malagasy ariary","symbol":"Ar"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"mg","iso639_2":"mlg","name":"Malagasy","nativeName":"fiteny malagasy"}],"translations":{"de":"Madagaskar","es":"Madagascar","fr":"Madagascar","ja":"マダガスカル","it":"Madagascar","br":"Madagascar","pt":"Madagáscar","nl":"Madagaskar","hr":"Madagaskar","fa":"ماداگاسکار"},"flag":"https://restcountries.eu/data/mdg.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"MAD"} +{"name":"Malawi","topLevelDomain":[".mw"],"alpha2Code":"MW","alpha3Code":"MWI","callingCodes":["265"],"capital":"Lilongwe","altSpellings":["MW","Republic of Malawi"],"region":"Africa","subregion":"Eastern Africa","population":16832910,"latlng":[-13.5,34.0],"demonym":"Malawian","area":118484.0,"gini":39.0,"timezones":["UTC+02:00"],"borders":["MOZ","TZA","ZMB"],"nativeName":"Malawi","numericCode":"454","currencies":[{"code":"MWK","name":"Malawian kwacha","symbol":"MK"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"ny","iso639_2":"nya","name":"Chichewa","nativeName":"chiCheŵa"}],"translations":{"de":"Malawi","es":"Malawi","fr":"Malawi","ja":"マラウイ","it":"Malawi","br":"Malawi","pt":"Malávi","nl":"Malawi","hr":"Malavi","fa":"مالاوی"},"flag":"https://restcountries.eu/data/mwi.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"MAW"} +{"name":"Malaysia","topLevelDomain":[".my"],"alpha2Code":"MY","alpha3Code":"MYS","callingCodes":["60"],"capital":"Kuala Lumpur","altSpellings":["MY"],"region":"Asia","subregion":"South-Eastern Asia","population":31405416,"latlng":[2.5,112.5],"demonym":"Malaysian","area":330803.0,"gini":46.2,"timezones":["UTC+08:00"],"borders":["BRN","IDN","THA"],"nativeName":"Malaysia","numericCode":"458","currencies":[{"code":"MYR","name":"Malaysian ringgit","symbol":"RM"}],"languages":[{"iso639_1":null,"iso639_2":"zsm","name":"Malaysian","nativeName":"بهاس مليسيا"}],"translations":{"de":"Malaysia","es":"Malasia","fr":"Malaisie","ja":"マレーシア","it":"Malesia","br":"Malásia","pt":"Malásia","nl":"Maleisië","hr":"Malezija","fa":"مالزی"},"flag":"https://restcountries.eu/data/mys.svg","regionalBlocs":[{"acronym":"ASEAN","name":"Association of Southeast Asian Nations","otherAcronyms":[],"otherNames":[]}],"cioc":"MAS"} +{"name":"Maldives","topLevelDomain":[".mv"],"alpha2Code":"MV","alpha3Code":"MDV","callingCodes":["960"],"capital":"Malé","altSpellings":["MV","Maldive Islands","Republic of the Maldives","Dhivehi Raajjeyge Jumhooriyya"],"region":"Asia","subregion":"Southern Asia","population":344023,"latlng":[3.25,73.0],"demonym":"Maldivan","area":300.0,"gini":37.4,"timezones":["UTC+05:00"],"borders":[],"nativeName":"Maldives","numericCode":"462","currencies":[{"code":"MVR","name":"Maldivian rufiyaa","symbol":".ރ"}],"languages":[{"iso639_1":"dv","iso639_2":"div","name":"Divehi","nativeName":"ދިވެހި"}],"translations":{"de":"Malediven","es":"Maldivas","fr":"Maldives","ja":"モルディブ","it":"Maldive","br":"Maldivas","pt":"Maldivas","nl":"Maldiven","hr":"Maldivi","fa":"مالدیو"},"flag":"https://restcountries.eu/data/mdv.svg","regionalBlocs":[{"acronym":"SAARC","name":"South Asian Association for Regional Cooperation","otherAcronyms":[],"otherNames":[]}],"cioc":"MDV"} +{"name":"Mali","topLevelDomain":[".ml"],"alpha2Code":"ML","alpha3Code":"MLI","callingCodes":["223"],"capital":"Bamako","altSpellings":["ML","Republic of Mali","République du Mali"],"region":"Africa","subregion":"Western Africa","population":18135000,"latlng":[17.0,-4.0],"demonym":"Malian","area":1240192.0,"gini":33.0,"timezones":["UTC"],"borders":["DZA","BFA","GIN","CIV","MRT","NER","SEN"],"nativeName":"Mali","numericCode":"466","currencies":[{"code":"XOF","name":"West African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Mali","es":"Mali","fr":"Mali","ja":"マリ","it":"Mali","br":"Mali","pt":"Mali","nl":"Mali","hr":"Mali","fa":"مالی"},"flag":"https://restcountries.eu/data/mli.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"MLI"} +{"name":"Malta","topLevelDomain":[".mt"],"alpha2Code":"MT","alpha3Code":"MLT","callingCodes":["356"],"capital":"Valletta","altSpellings":["MT","Republic of Malta","Repubblika ta' Malta"],"region":"Europe","subregion":"Southern Europe","population":425384,"latlng":[35.83333333,14.58333333],"demonym":"Maltese","area":316.0,"gini":null,"timezones":["UTC+01:00"],"borders":[],"nativeName":"Malta","numericCode":"470","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"mt","iso639_2":"mlt","name":"Maltese","nativeName":"Malti"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Malta","es":"Malta","fr":"Malte","ja":"マルタ","it":"Malta","br":"Malta","pt":"Malta","nl":"Malta","hr":"Malta","fa":"مالت"},"flag":"https://restcountries.eu/data/mlt.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"MLT"} +{"name":"Marshall Islands","topLevelDomain":[".mh"],"alpha2Code":"MH","alpha3Code":"MHL","callingCodes":["692"],"capital":"Majuro","altSpellings":["MH","Republic of the Marshall Islands","Aolepān Aorōkin M̧ajeļ"],"region":"Oceania","subregion":"Micronesia","population":54880,"latlng":[9.0,168.0],"demonym":"Marshallese","area":181.0,"gini":null,"timezones":["UTC+12:00"],"borders":[],"nativeName":"M̧ajeļ","numericCode":"584","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"mh","iso639_2":"mah","name":"Marshallese","nativeName":"Kajin M̧ajeļ"}],"translations":{"de":"Marshallinseln","es":"Islas Marshall","fr":"Îles Marshall","ja":"マーシャル諸島","it":"Isole Marshall","br":"Ilhas Marshall","pt":"Ilhas Marshall","nl":"Marshalleilanden","hr":"Maršalovi Otoci","fa":"جزایر مارشال"},"flag":"https://restcountries.eu/data/mhl.svg","regionalBlocs":[],"cioc":"MHL"} +{"name":"Martinique","topLevelDomain":[".mq"],"alpha2Code":"MQ","alpha3Code":"MTQ","callingCodes":["596"],"capital":"Fort-de-France","altSpellings":["MQ"],"region":"Americas","subregion":"Caribbean","population":378243,"latlng":[14.666667,-61.0],"demonym":"French","area":null,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Martinique","numericCode":"474","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Martinique","es":"Martinica","fr":"Martinique","ja":"マルティニーク","it":"Martinica","br":"Martinica","pt":"Martinica","nl":"Martinique","hr":"Martinique","fa":"مونتسرات"},"flag":"https://restcountries.eu/data/mtq.svg","regionalBlocs":[],"cioc":""} +{"name":"Mauritania","topLevelDomain":[".mr"],"alpha2Code":"MR","alpha3Code":"MRT","callingCodes":["222"],"capital":"Nouakchott","altSpellings":["MR","Islamic Republic of Mauritania","al-Jumhūriyyah al-ʾIslāmiyyah al-Mūrītāniyyah"],"region":"Africa","subregion":"Western Africa","population":3718678,"latlng":[20.0,-12.0],"demonym":"Mauritanian","area":1030700.0,"gini":40.5,"timezones":["UTC"],"borders":["DZA","MLI","SEN","ESH"],"nativeName":"موريتانيا","numericCode":"478","currencies":[{"code":"MRO","name":"Mauritanian ouguiya","symbol":"UM"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Mauretanien","es":"Mauritania","fr":"Mauritanie","ja":"モーリタニア","it":"Mauritania","br":"Mauritânia","pt":"Mauritânia","nl":"Mauritanië","hr":"Mauritanija","fa":"موریتانی"},"flag":"https://restcountries.eu/data/mrt.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]},{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"MTN"} +{"name":"Mauritius","topLevelDomain":[".mu"],"alpha2Code":"MU","alpha3Code":"MUS","callingCodes":["230"],"capital":"Port Louis","altSpellings":["MU","Republic of Mauritius","République de Maurice"],"region":"Africa","subregion":"Eastern Africa","population":1262879,"latlng":[-20.28333333,57.55],"demonym":"Mauritian","area":2040.0,"gini":null,"timezones":["UTC+04:00"],"borders":[],"nativeName":"Maurice","numericCode":"480","currencies":[{"code":"MUR","name":"Mauritian rupee","symbol":"₨"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Mauritius","es":"Mauricio","fr":"Île Maurice","ja":"モーリシャス","it":"Mauritius","br":"Maurício","pt":"Maurícia","nl":"Mauritius","hr":"Mauricijus","fa":"موریس"},"flag":"https://restcountries.eu/data/mus.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"MRI"} +{"name":"Mayotte","topLevelDomain":[".yt"],"alpha2Code":"YT","alpha3Code":"MYT","callingCodes":["262"],"capital":"Mamoudzou","altSpellings":["YT","Department of Mayotte","Département de Mayotte"],"region":"Africa","subregion":"Eastern Africa","population":226915,"latlng":[-12.83333333,45.16666666],"demonym":"French","area":null,"gini":null,"timezones":["UTC+03:00"],"borders":[],"nativeName":"Mayotte","numericCode":"175","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Mayotte","es":"Mayotte","fr":"Mayotte","ja":"マヨット","it":"Mayotte","br":"Mayotte","pt":"Mayotte","nl":"Mayotte","hr":"Mayotte","fa":"مایوت"},"flag":"https://restcountries.eu/data/myt.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":""} +{"name":"Mexico","topLevelDomain":[".mx"],"alpha2Code":"MX","alpha3Code":"MEX","callingCodes":["52"],"capital":"Mexico City","altSpellings":["MX","Mexicanos","United Mexican States","Estados Unidos Mexicanos"],"region":"Americas","subregion":"Central America","population":122273473,"latlng":[23.0,-102.0],"demonym":"Mexican","area":1964375.0,"gini":47.0,"timezones":["UTC-08:00","UTC-07:00","UTC-06:00"],"borders":["BLZ","GTM","USA"],"nativeName":"México","numericCode":"484","currencies":[{"code":"MXN","name":"Mexican peso","symbol":"$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Mexiko","es":"México","fr":"Mexique","ja":"メキシコ","it":"Messico","br":"México","pt":"México","nl":"Mexico","hr":"Meksiko","fa":"مکزیک"},"flag":"https://restcountries.eu/data/mex.svg","regionalBlocs":[{"acronym":"PA","name":"Pacific Alliance","otherAcronyms":[],"otherNames":["Alianza del Pacífico"]},{"acronym":"NAFTA","name":"North American Free Trade Agreement","otherAcronyms":[],"otherNames":["Tratado de Libre Comercio de América del Norte","Accord de Libre-échange Nord-Américain"]}],"cioc":"MEX"} +{"name":"Micronesia (Federated States of)","topLevelDomain":[".fm"],"alpha2Code":"FM","alpha3Code":"FSM","callingCodes":["691"],"capital":"Palikir","altSpellings":["FM","Federated States of Micronesia"],"region":"Oceania","subregion":"Micronesia","population":102800,"latlng":[6.91666666,158.25],"demonym":"Micronesian","area":702.0,"gini":null,"timezones":["UTC+10:00","UTC+11"],"borders":[],"nativeName":"Micronesia","numericCode":"583","currencies":[{"code":null,"name":"[D]","symbol":"$"},{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Mikronesien","es":"Micronesia","fr":"Micronésie","ja":"ミクロネシア連邦","it":"Micronesia","br":"Micronésia","pt":"Micronésia","nl":"Micronesië","hr":"Mikronezija","fa":"ایالات فدرال میکرونزی"},"flag":"https://restcountries.eu/data/fsm.svg","regionalBlocs":[],"cioc":"FSM"} +{"name":"Moldova (Republic of)","topLevelDomain":[".md"],"alpha2Code":"MD","alpha3Code":"MDA","callingCodes":["373"],"capital":"Chișinău","altSpellings":["MD","Republic of Moldova","Republica Moldova"],"region":"Europe","subregion":"Eastern Europe","population":3553100,"latlng":[47.0,29.0],"demonym":"Moldovan","area":33846.0,"gini":33.0,"timezones":["UTC+02:00"],"borders":["ROU","UKR"],"nativeName":"Moldova","numericCode":"498","currencies":[{"code":"MDL","name":"Moldovan leu","symbol":"L"}],"languages":[{"iso639_1":"ro","iso639_2":"ron","name":"Romanian","nativeName":"Română"}],"translations":{"de":"Moldawie","es":"Moldavia","fr":"Moldavie","ja":"モルドバ共和国","it":"Moldavia","br":"Moldávia","pt":"Moldávia","nl":"Moldavië","hr":"Moldova","fa":"مولداوی"},"flag":"https://restcountries.eu/data/mda.svg","regionalBlocs":[{"acronym":"CEFTA","name":"Central European Free Trade Agreement","otherAcronyms":[],"otherNames":[]}],"cioc":"MDA"} +{"name":"Monaco","topLevelDomain":[".mc"],"alpha2Code":"MC","alpha3Code":"MCO","callingCodes":["377"],"capital":"Monaco","altSpellings":["MC","Principality of Monaco","Principauté de Monaco"],"region":"Europe","subregion":"Western Europe","population":38400,"latlng":[43.73333333,7.4],"demonym":"Monegasque","area":2.02,"gini":null,"timezones":["UTC+01:00"],"borders":["FRA"],"nativeName":"Monaco","numericCode":"492","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Monaco","es":"Mónaco","fr":"Monaco","ja":"モナコ","it":"Principato di Monaco","br":"Mônaco","pt":"Mónaco","nl":"Monaco","hr":"Monako","fa":"موناکو"},"flag":"https://restcountries.eu/data/mco.svg","regionalBlocs":[],"cioc":"MON"} +{"name":"Mongolia","topLevelDomain":[".mn"],"alpha2Code":"MN","alpha3Code":"MNG","callingCodes":["976"],"capital":"Ulan Bator","altSpellings":["MN"],"region":"Asia","subregion":"Eastern Asia","population":3093100,"latlng":[46.0,105.0],"demonym":"Mongolian","area":1564110.0,"gini":36.5,"timezones":["UTC+07:00","UTC+08:00"],"borders":["CHN","RUS"],"nativeName":"Монгол улс","numericCode":"496","currencies":[{"code":"MNT","name":"Mongolian tögrög","symbol":"₮"}],"languages":[{"iso639_1":"mn","iso639_2":"mon","name":"Mongolian","nativeName":"Монгол хэл"}],"translations":{"de":"Mongolei","es":"Mongolia","fr":"Mongolie","ja":"モンゴル","it":"Mongolia","br":"Mongólia","pt":"Mongólia","nl":"Mongolië","hr":"Mongolija","fa":"مغولستان"},"flag":"https://restcountries.eu/data/mng.svg","regionalBlocs":[],"cioc":"MGL"} +{"name":"Montenegro","topLevelDomain":[".me"],"alpha2Code":"ME","alpha3Code":"MNE","callingCodes":["382"],"capital":"Podgorica","altSpellings":["ME","Crna Gora"],"region":"Europe","subregion":"Southern Europe","population":621810,"latlng":[42.5,19.3],"demonym":"Montenegrin","area":13812.0,"gini":30.0,"timezones":["UTC+01:00"],"borders":["ALB","BIH","HRV","KOS","SRB"],"nativeName":"Црна Гора","numericCode":"499","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"sr","iso639_2":"srp","name":"Serbian","nativeName":"српски језик"},{"iso639_1":"bs","iso639_2":"bos","name":"Bosnian","nativeName":"bosanski jezik"},{"iso639_1":"sq","iso639_2":"sqi","name":"Albanian","nativeName":"Shqip"},{"iso639_1":"hr","iso639_2":"hrv","name":"Croatian","nativeName":"hrvatski jezik"}],"translations":{"de":"Montenegro","es":"Montenegro","fr":"Monténégro","ja":"モンテネグロ","it":"Montenegro","br":"Montenegro","pt":"Montenegro","nl":"Montenegro","hr":"Crna Gora","fa":"مونته‌نگرو"},"flag":"https://restcountries.eu/data/mne.svg","regionalBlocs":[{"acronym":"CEFTA","name":"Central European Free Trade Agreement","otherAcronyms":[],"otherNames":[]}],"cioc":"MNE"} +{"name":"Montserrat","topLevelDomain":[".ms"],"alpha2Code":"MS","alpha3Code":"MSR","callingCodes":["1664"],"capital":"Plymouth","altSpellings":["MS"],"region":"Americas","subregion":"Caribbean","population":4922,"latlng":[16.75,-62.2],"demonym":"Montserratian","area":102.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Montserrat","numericCode":"500","currencies":[{"code":"XCD","name":"East Caribbean dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Montserrat","es":"Montserrat","fr":"Montserrat","ja":"モントセラト","it":"Montserrat","br":"Montserrat","pt":"Monserrate","nl":"Montserrat","hr":"Montserrat","fa":"مایوت"},"flag":"https://restcountries.eu/data/msr.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]}],"cioc":""} +{"name":"Morocco","topLevelDomain":[".ma"],"alpha2Code":"MA","alpha3Code":"MAR","callingCodes":["212"],"capital":"Rabat","altSpellings":["MA","Kingdom of Morocco","Al-Mamlakah al-Maġribiyah"],"region":"Africa","subregion":"Northern Africa","population":33337529,"latlng":[32.0,-5.0],"demonym":"Moroccan","area":446550.0,"gini":40.9,"timezones":["UTC"],"borders":["DZA","ESH","ESP"],"nativeName":"المغرب","numericCode":"504","currencies":[{"code":"MAD","name":"Moroccan dirham","symbol":"د.م."}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Marokko","es":"Marruecos","fr":"Maroc","ja":"モロッコ","it":"Marocco","br":"Marrocos","pt":"Marrocos","nl":"Marokko","hr":"Maroko","fa":"مراکش"},"flag":"https://restcountries.eu/data/mar.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]},{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"MAR"} +{"name":"Mozambique","topLevelDomain":[".mz"],"alpha2Code":"MZ","alpha3Code":"MOZ","callingCodes":["258"],"capital":"Maputo","altSpellings":["MZ","Republic of Mozambique","República de Moçambique"],"region":"Africa","subregion":"Eastern Africa","population":26423700,"latlng":[-18.25,35.0],"demonym":"Mozambican","area":801590.0,"gini":45.7,"timezones":["UTC+02:00"],"borders":["MWI","ZAF","SWZ","TZA","ZMB","ZWE"],"nativeName":"Moçambique","numericCode":"508","currencies":[{"code":"MZN","name":"Mozambican metical","symbol":"MT"}],"languages":[{"iso639_1":"pt","iso639_2":"por","name":"Portuguese","nativeName":"Português"}],"translations":{"de":"Mosambik","es":"Mozambique","fr":"Mozambique","ja":"モザンビーク","it":"Mozambico","br":"Moçambique","pt":"Moçambique","nl":"Mozambique","hr":"Mozambik","fa":"موزامبیک"},"flag":"https://restcountries.eu/data/moz.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"MOZ"} +{"name":"Myanmar","topLevelDomain":[".mm"],"alpha2Code":"MM","alpha3Code":"MMR","callingCodes":["95"],"capital":"Naypyidaw","altSpellings":["MM","Burma","Republic of the Union of Myanmar","Pyidaunzu Thanmăda Myăma Nainngandaw"],"region":"Asia","subregion":"South-Eastern Asia","population":51419420,"latlng":[22.0,98.0],"demonym":"Burmese","area":676578.0,"gini":null,"timezones":["UTC+06:30"],"borders":["BGD","CHN","IND","LAO","THA"],"nativeName":"Myanma","numericCode":"104","currencies":[{"code":"MMK","name":"Burmese kyat","symbol":"Ks"}],"languages":[{"iso639_1":"my","iso639_2":"mya","name":"Burmese","nativeName":"ဗမာစာ"}],"translations":{"de":"Myanmar","es":"Myanmar","fr":"Myanmar","ja":"ミャンマー","it":"Birmania","br":"Myanmar","pt":"Myanmar","nl":"Myanmar","hr":"Mijanmar","fa":"میانمار"},"flag":"https://restcountries.eu/data/mmr.svg","regionalBlocs":[{"acronym":"ASEAN","name":"Association of Southeast Asian Nations","otherAcronyms":[],"otherNames":[]}],"cioc":"MYA"} +{"name":"Namibia","topLevelDomain":[".na"],"alpha2Code":"NA","alpha3Code":"NAM","callingCodes":["264"],"capital":"Windhoek","altSpellings":["NA","Namibië","Republic of Namibia"],"region":"Africa","subregion":"Southern Africa","population":2324388,"latlng":[-22.0,17.0],"demonym":"Namibian","area":825615.0,"gini":63.9,"timezones":["UTC+01:00"],"borders":["AGO","BWA","ZAF","ZMB"],"nativeName":"Namibia","numericCode":"516","currencies":[{"code":"NAD","name":"Namibian dollar","symbol":"$"},{"code":"ZAR","name":"South African rand","symbol":"R"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"af","iso639_2":"afr","name":"Afrikaans","nativeName":"Afrikaans"}],"translations":{"de":"Namibia","es":"Namibia","fr":"Namibie","ja":"ナミビア","it":"Namibia","br":"Namíbia","pt":"Namíbia","nl":"Namibië","hr":"Namibija","fa":"نامیبیا"},"flag":"https://restcountries.eu/data/nam.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"NAM"} +{"name":"Nauru","topLevelDomain":[".nr"],"alpha2Code":"NR","alpha3Code":"NRU","callingCodes":["674"],"capital":"Yaren","altSpellings":["NR","Naoero","Pleasant Island","Republic of Nauru","Ripublik Naoero"],"region":"Oceania","subregion":"Micronesia","population":10084,"latlng":[-0.53333333,166.91666666],"demonym":"Nauruan","area":21.0,"gini":null,"timezones":["UTC+12:00"],"borders":[],"nativeName":"Nauru","numericCode":"520","currencies":[{"code":"AUD","name":"Australian dollar","symbol":"$"},{"code":"(none)","name":null,"symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"na","iso639_2":"nau","name":"Nauruan","nativeName":"Dorerin Naoero"}],"translations":{"de":"Nauru","es":"Nauru","fr":"Nauru","ja":"ナウル","it":"Nauru","br":"Nauru","pt":"Nauru","nl":"Nauru","hr":"Nauru","fa":"نائورو"},"flag":"https://restcountries.eu/data/nru.svg","regionalBlocs":[],"cioc":"NRU"} +{"name":"Nepal","topLevelDomain":[".np"],"alpha2Code":"NP","alpha3Code":"NPL","callingCodes":["977"],"capital":"Kathmandu","altSpellings":["NP","Federal Democratic Republic of Nepal","Loktāntrik Ganatantra Nepāl"],"region":"Asia","subregion":"Southern Asia","population":28431500,"latlng":[28.0,84.0],"demonym":"Nepalese","area":147181.0,"gini":32.8,"timezones":["UTC+05:45"],"borders":["CHN","IND"],"nativeName":"नेपाल","numericCode":"524","currencies":[{"code":"NPR","name":"Nepalese rupee","symbol":"₨"}],"languages":[{"iso639_1":"ne","iso639_2":"nep","name":"Nepali","nativeName":"नेपाली"}],"translations":{"de":"Népal","es":"Nepal","fr":"Népal","ja":"ネパール","it":"Nepal","br":"Nepal","pt":"Nepal","nl":"Nepal","hr":"Nepal","fa":"نپال"},"flag":"https://restcountries.eu/data/npl.svg","regionalBlocs":[{"acronym":"SAARC","name":"South Asian Association for Regional Cooperation","otherAcronyms":[],"otherNames":[]}],"cioc":"NEP"} +{"name":"Netherlands","topLevelDomain":[".nl"],"alpha2Code":"NL","alpha3Code":"NLD","callingCodes":["31"],"capital":"Amsterdam","altSpellings":["NL","Holland","Nederland"],"region":"Europe","subregion":"Western Europe","population":17019800,"latlng":[52.5,5.75],"demonym":"Dutch","area":41850.0,"gini":30.9,"timezones":["UTC-04:00","UTC+01:00"],"borders":["BEL","DEU"],"nativeName":"Nederland","numericCode":"528","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"nl","iso639_2":"nld","name":"Dutch","nativeName":"Nederlands"}],"translations":{"de":"Niederlande","es":"Países Bajos","fr":"Pays-Bas","ja":"オランダ","it":"Paesi Bassi","br":"Holanda","pt":"Países Baixos","nl":"Nederland","hr":"Nizozemska","fa":"پادشاهی هلند"},"flag":"https://restcountries.eu/data/nld.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"NED"} +{"name":"New Caledonia","topLevelDomain":[".nc"],"alpha2Code":"NC","alpha3Code":"NCL","callingCodes":["687"],"capital":"Nouméa","altSpellings":["NC"],"region":"Oceania","subregion":"Melanesia","population":268767,"latlng":[-21.5,165.5],"demonym":"New Caledonian","area":18575.0,"gini":null,"timezones":["UTC+11:00"],"borders":[],"nativeName":"Nouvelle-Calédonie","numericCode":"540","currencies":[{"code":"XPF","name":"CFP franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Neukaledonien","es":"Nueva Caledonia","fr":"Nouvelle-Calédonie","ja":"ニューカレドニア","it":"Nuova Caledonia","br":"Nova Caledônia","pt":"Nova Caledónia","nl":"Nieuw-Caledonië","hr":"Nova Kaledonija","fa":"کالدونیای جدید"},"flag":"https://restcountries.eu/data/ncl.svg","regionalBlocs":[],"cioc":""} +{"name":"New Zealand","topLevelDomain":[".nz"],"alpha2Code":"NZ","alpha3Code":"NZL","callingCodes":["64"],"capital":"Wellington","altSpellings":["NZ","Aotearoa"],"region":"Oceania","subregion":"Australia and New Zealand","population":4697854,"latlng":[-41.0,174.0],"demonym":"New Zealander","area":270467.0,"gini":36.2,"timezones":["UTC-11:00","UTC-10:00","UTC+12:00","UTC+12:45","UTC+13:00"],"borders":[],"nativeName":"New Zealand","numericCode":"554","currencies":[{"code":"NZD","name":"New Zealand dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"mi","iso639_2":"mri","name":"Māori","nativeName":"te reo Māori"}],"translations":{"de":"Neuseeland","es":"Nueva Zelanda","fr":"Nouvelle-Zélande","ja":"ニュージーランド","it":"Nuova Zelanda","br":"Nova Zelândia","pt":"Nova Zelândia","nl":"Nieuw-Zeeland","hr":"Novi Zeland","fa":"نیوزیلند"},"flag":"https://restcountries.eu/data/nzl.svg","regionalBlocs":[],"cioc":"NZL"} +{"name":"Nicaragua","topLevelDomain":[".ni"],"alpha2Code":"NI","alpha3Code":"NIC","callingCodes":["505"],"capital":"Managua","altSpellings":["NI","Republic of Nicaragua","República de Nicaragua"],"region":"Americas","subregion":"Central America","population":6262703,"latlng":[13.0,-85.0],"demonym":"Nicaraguan","area":130373.0,"gini":40.5,"timezones":["UTC-06:00"],"borders":["CRI","HND"],"nativeName":"Nicaragua","numericCode":"558","currencies":[{"code":"NIO","name":"Nicaraguan córdoba","symbol":"C$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Nicaragua","es":"Nicaragua","fr":"Nicaragua","ja":"ニカラグア","it":"Nicaragua","br":"Nicarágua","pt":"Nicarágua","nl":"Nicaragua","hr":"Nikaragva","fa":"نیکاراگوئه"},"flag":"https://restcountries.eu/data/nic.svg","regionalBlocs":[{"acronym":"CAIS","name":"Central American Integration System","otherAcronyms":["SICA"],"otherNames":["Sistema de la Integración Centroamericana,"]}],"cioc":"NCA"} +{"name":"Niger","topLevelDomain":[".ne"],"alpha2Code":"NE","alpha3Code":"NER","callingCodes":["227"],"capital":"Niamey","altSpellings":["NE","Nijar","Republic of Niger","République du Niger"],"region":"Africa","subregion":"Western Africa","population":20715000,"latlng":[16.0,8.0],"demonym":"Nigerien","area":1267000.0,"gini":34.6,"timezones":["UTC+01:00"],"borders":["DZA","BEN","BFA","TCD","LBY","MLI","NGA"],"nativeName":"Niger","numericCode":"562","currencies":[{"code":"XOF","name":"West African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Niger","es":"Níger","fr":"Niger","ja":"ニジェール","it":"Niger","br":"Níger","pt":"Níger","nl":"Niger","hr":"Niger","fa":"نیجر"},"flag":"https://restcountries.eu/data/ner.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"NIG"} +{"name":"Nigeria","topLevelDomain":[".ng"],"alpha2Code":"NG","alpha3Code":"NGA","callingCodes":["234"],"capital":"Abuja","altSpellings":["NG","Nijeriya","Naíjíríà","Federal Republic of Nigeria"],"region":"Africa","subregion":"Western Africa","population":186988000,"latlng":[10.0,8.0],"demonym":"Nigerian","area":923768.0,"gini":48.8,"timezones":["UTC+01:00"],"borders":["BEN","CMR","TCD","NER"],"nativeName":"Nigeria","numericCode":"566","currencies":[{"code":"NGN","name":"Nigerian naira","symbol":"₦"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Nigeria","es":"Nigeria","fr":"Nigéria","ja":"ナイジェリア","it":"Nigeria","br":"Nigéria","pt":"Nigéria","nl":"Nigeria","hr":"Nigerija","fa":"نیجریه"},"flag":"https://restcountries.eu/data/nga.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"NGR"} +{"name":"Niue","topLevelDomain":[".nu"],"alpha2Code":"NU","alpha3Code":"NIU","callingCodes":["683"],"capital":"Alofi","altSpellings":["NU"],"region":"Oceania","subregion":"Polynesia","population":1470,"latlng":[-19.03333333,-169.86666666],"demonym":"Niuean","area":260.0,"gini":null,"timezones":["UTC-11:00"],"borders":[],"nativeName":"Niuē","numericCode":"570","currencies":[{"code":"NZD","name":"New Zealand dollar","symbol":"$"},{"code":"(none)","name":"Niue dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Niue","es":"Niue","fr":"Niue","ja":"ニウエ","it":"Niue","br":"Niue","pt":"Niue","nl":"Niue","hr":"Niue","fa":"نیووی"},"flag":"https://restcountries.eu/data/niu.svg","regionalBlocs":[],"cioc":""} +{"name":"Norfolk Island","topLevelDomain":[".nf"],"alpha2Code":"NF","alpha3Code":"NFK","callingCodes":["672"],"capital":"Kingston","altSpellings":["NF","Territory of Norfolk Island","Teratri of Norf'k Ailen"],"region":"Oceania","subregion":"Australia and New Zealand","population":2302,"latlng":[-29.03333333,167.95],"demonym":"Norfolk Islander","area":36.0,"gini":null,"timezones":["UTC+11:30"],"borders":[],"nativeName":"Norfolk Island","numericCode":"574","currencies":[{"code":"AUD","name":"Australian dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Norfolkinsel","es":"Isla de Norfolk","fr":"Île de Norfolk","ja":"ノーフォーク島","it":"Isola Norfolk","br":"Ilha Norfolk","pt":"Ilha Norfolk","nl":"Norfolkeiland","hr":"Otok Norfolk","fa":"جزیره نورفک"},"flag":"https://restcountries.eu/data/nfk.svg","regionalBlocs":[],"cioc":""} +{"name":"Korea (Democratic People's Republic of)","topLevelDomain":[".kp"],"alpha2Code":"KP","alpha3Code":"PRK","callingCodes":["850"],"capital":"Pyongyang","altSpellings":["KP","Democratic People's Republic of Korea","조선민주주의인민공화국","Chosŏn Minjujuŭi Inmin Konghwaguk"],"region":"Asia","subregion":"Eastern Asia","population":25281000,"latlng":[40.0,127.0],"demonym":"North Korean","area":120538.0,"gini":null,"timezones":["UTC+09:00"],"borders":["CHN","KOR","RUS"],"nativeName":"북한","numericCode":"408","currencies":[{"code":"KPW","name":"North Korean won","symbol":"₩"}],"languages":[{"iso639_1":"ko","iso639_2":"kor","name":"Korean","nativeName":"한국어"}],"translations":{"de":"Nordkorea","es":"Corea del Norte","fr":"Corée du Nord","ja":"朝鮮民主主義人民共和国","it":"Corea del Nord","br":"Coreia do Norte","pt":"Coreia do Norte","nl":"Noord-Korea","hr":"Sjeverna Koreja","fa":"کره جنوبی"},"flag":"https://restcountries.eu/data/prk.svg","regionalBlocs":[],"cioc":"PRK"} +{"name":"Northern Mariana Islands","topLevelDomain":[".mp"],"alpha2Code":"MP","alpha3Code":"MNP","callingCodes":["1670"],"capital":"Saipan","altSpellings":["MP","Commonwealth of the Northern Mariana Islands","Sankattan Siha Na Islas Mariånas"],"region":"Oceania","subregion":"Micronesia","population":56940,"latlng":[15.2,145.75],"demonym":"American","area":464.0,"gini":null,"timezones":["UTC+10:00"],"borders":[],"nativeName":"Northern Mariana Islands","numericCode":"580","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"ch","iso639_2":"cha","name":"Chamorro","nativeName":"Chamoru"}],"translations":{"de":"Nördliche Marianen","es":"Islas Marianas del Norte","fr":"Îles Mariannes du Nord","ja":"北マリアナ諸島","it":"Isole Marianne Settentrionali","br":"Ilhas Marianas","pt":"Ilhas Marianas","nl":"Noordelijke Marianeneilanden","hr":"Sjevernomarijanski otoci","fa":"جزایر ماریانای شمالی"},"flag":"https://restcountries.eu/data/mnp.svg","regionalBlocs":[],"cioc":""} +{"name":"Norway","topLevelDomain":[".no"],"alpha2Code":"NO","alpha3Code":"NOR","callingCodes":["47"],"capital":"Oslo","altSpellings":["NO","Norge","Noreg","Kingdom of Norway","Kongeriket Norge","Kongeriket Noreg"],"region":"Europe","subregion":"Northern Europe","population":5223256,"latlng":[62.0,10.0],"demonym":"Norwegian","area":323802.0,"gini":25.8,"timezones":["UTC+01:00"],"borders":["FIN","SWE","RUS"],"nativeName":"Norge","numericCode":"578","currencies":[{"code":"NOK","name":"Norwegian krone","symbol":"kr"}],"languages":[{"iso639_1":"no","iso639_2":"nor","name":"Norwegian","nativeName":"Norsk"},{"iso639_1":"nb","iso639_2":"nob","name":"Norwegian Bokmål","nativeName":"Norsk bokmål"},{"iso639_1":"nn","iso639_2":"nno","name":"Norwegian Nynorsk","nativeName":"Norsk nynorsk"}],"translations":{"de":"Norwegen","es":"Noruega","fr":"Norvège","ja":"ノルウェー","it":"Norvegia","br":"Noruega","pt":"Noruega","nl":"Noorwegen","hr":"Norveška","fa":"نروژ"},"flag":"https://restcountries.eu/data/nor.svg","regionalBlocs":[{"acronym":"EFTA","name":"European Free Trade Association","otherAcronyms":[],"otherNames":[]}],"cioc":"NOR"} +{"name":"Oman","topLevelDomain":[".om"],"alpha2Code":"OM","alpha3Code":"OMN","callingCodes":["968"],"capital":"Muscat","altSpellings":["OM","Sultanate of Oman","Salṭanat ʻUmān"],"region":"Asia","subregion":"Western Asia","population":4420133,"latlng":[21.0,57.0],"demonym":"Omani","area":309500.0,"gini":null,"timezones":["UTC+04:00"],"borders":["SAU","ARE","YEM"],"nativeName":"عمان","numericCode":"512","currencies":[{"code":"OMR","name":"Omani rial","symbol":"ر.ع."}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Oman","es":"Omán","fr":"Oman","ja":"オマーン","it":"oman","br":"Omã","pt":"Omã","nl":"Oman","hr":"Oman","fa":"عمان"},"flag":"https://restcountries.eu/data/omn.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"OMA"} +{"name":"Pakistan","topLevelDomain":[".pk"],"alpha2Code":"PK","alpha3Code":"PAK","callingCodes":["92"],"capital":"Islamabad","altSpellings":["PK","Pākistān","Islamic Republic of Pakistan","Islāmī Jumhūriya'eh Pākistān"],"region":"Asia","subregion":"Southern Asia","population":194125062,"latlng":[30.0,70.0],"demonym":"Pakistani","area":881912.0,"gini":30.0,"timezones":["UTC+05:00"],"borders":["AFG","CHN","IND","IRN"],"nativeName":"Pakistan","numericCode":"586","currencies":[{"code":"PKR","name":"Pakistani rupee","symbol":"₨"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"ur","iso639_2":"urd","name":"Urdu","nativeName":"اردو"}],"translations":{"de":"Pakistan","es":"Pakistán","fr":"Pakistan","ja":"パキスタン","it":"Pakistan","br":"Paquistão","pt":"Paquistão","nl":"Pakistan","hr":"Pakistan","fa":"پاکستان"},"flag":"https://restcountries.eu/data/pak.svg","regionalBlocs":[{"acronym":"SAARC","name":"South Asian Association for Regional Cooperation","otherAcronyms":[],"otherNames":[]}],"cioc":"PAK"} +{"name":"Palau","topLevelDomain":[".pw"],"alpha2Code":"PW","alpha3Code":"PLW","callingCodes":["680"],"capital":"Ngerulmud","altSpellings":["PW","Republic of Palau","Beluu er a Belau"],"region":"Oceania","subregion":"Micronesia","population":17950,"latlng":[7.5,134.5],"demonym":"Palauan","area":459.0,"gini":null,"timezones":["UTC+09:00"],"borders":[],"nativeName":"Palau","numericCode":"585","currencies":[{"code":"(none)","name":"[E]","symbol":"$"},{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Palau","es":"Palau","fr":"Palaos","ja":"パラオ","it":"Palau","br":"Palau","pt":"Palau","nl":"Palau","hr":"Palau","fa":"پالائو"},"flag":"https://restcountries.eu/data/plw.svg","regionalBlocs":[],"cioc":"PLW"} +{"name":"Palestine, State of","topLevelDomain":[".ps"],"alpha2Code":"PS","alpha3Code":"PSE","callingCodes":["970"],"capital":"Ramallah","altSpellings":["PS","State of Palestine","Dawlat Filasṭin"],"region":"Asia","subregion":"Western Asia","population":4682467,"latlng":[31.9,35.2],"demonym":"Palestinian","area":null,"gini":35.5,"timezones":["UTC+02:00"],"borders":["ISR","EGY","JOR"],"nativeName":"فلسطين","numericCode":"275","currencies":[{"code":"ILS","name":"Israeli new sheqel","symbol":"₪"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Palästina","es":"Palestina","fr":"Palestine","ja":"パレスチナ","it":"Palestina","br":"Palestina","pt":"Palestina","nl":"Palestijnse gebieden","hr":"Palestina","fa":"فلسطین"},"flag":"https://restcountries.eu/data/pse.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"PLE"} +{"name":"Panama","topLevelDomain":[".pa"],"alpha2Code":"PA","alpha3Code":"PAN","callingCodes":["507"],"capital":"Panama City","altSpellings":["PA","Republic of Panama","República de Panamá"],"region":"Americas","subregion":"Central America","population":3814672,"latlng":[9.0,-80.0],"demonym":"Panamanian","area":75417.0,"gini":51.9,"timezones":["UTC-05:00"],"borders":["COL","CRI"],"nativeName":"Panamá","numericCode":"591","currencies":[{"code":"PAB","name":"Panamanian balboa","symbol":"B/."},{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Panama","es":"Panamá","fr":"Panama","ja":"パナマ","it":"Panama","br":"Panamá","pt":"Panamá","nl":"Panama","hr":"Panama","fa":"پاناما"},"flag":"https://restcountries.eu/data/pan.svg","regionalBlocs":[{"acronym":"CAIS","name":"Central American Integration System","otherAcronyms":["SICA"],"otherNames":["Sistema de la Integración Centroamericana,"]}],"cioc":"PAN"} +{"name":"Papua New Guinea","topLevelDomain":[".pg"],"alpha2Code":"PG","alpha3Code":"PNG","callingCodes":["675"],"capital":"Port Moresby","altSpellings":["PG","Independent State of Papua New Guinea","Independen Stet bilong Papua Niugini"],"region":"Oceania","subregion":"Melanesia","population":8083700,"latlng":[-6.0,147.0],"demonym":"Papua New Guinean","area":462840.0,"gini":50.9,"timezones":["UTC+10:00"],"borders":["IDN"],"nativeName":"Papua Niugini","numericCode":"598","currencies":[{"code":"PGK","name":"Papua New Guinean kina","symbol":"K"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Papua-Neuguinea","es":"Papúa Nueva Guinea","fr":"Papouasie-Nouvelle-Guinée","ja":"パプアニューギニア","it":"Papua Nuova Guinea","br":"Papua Nova Guiné","pt":"Papua Nova Guiné","nl":"Papoea-Nieuw-Guinea","hr":"Papua Nova Gvineja","fa":"پاپوآ گینه نو"},"flag":"https://restcountries.eu/data/png.svg","regionalBlocs":[],"cioc":"PNG"} +{"name":"Paraguay","topLevelDomain":[".py"],"alpha2Code":"PY","alpha3Code":"PRY","callingCodes":["595"],"capital":"Asunción","altSpellings":["PY","Republic of Paraguay","República del Paraguay","Tetã Paraguái"],"region":"Americas","subregion":"South America","population":6854536,"latlng":[-23.0,-58.0],"demonym":"Paraguayan","area":406752.0,"gini":52.4,"timezones":["UTC-04:00"],"borders":["ARG","BOL","BRA"],"nativeName":"Paraguay","numericCode":"600","currencies":[{"code":"PYG","name":"Paraguayan guaraní","symbol":"₲"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"},{"iso639_1":"gn","iso639_2":"grn","name":"Guaraní","nativeName":"Avañe'ẽ"}],"translations":{"de":"Paraguay","es":"Paraguay","fr":"Paraguay","ja":"パラグアイ","it":"Paraguay","br":"Paraguai","pt":"Paraguai","nl":"Paraguay","hr":"Paragvaj","fa":"پاراگوئه"},"flag":"https://restcountries.eu/data/pry.svg","regionalBlocs":[{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"PAR"} +{"name":"Peru","topLevelDomain":[".pe"],"alpha2Code":"PE","alpha3Code":"PER","callingCodes":["51"],"capital":"Lima","altSpellings":["PE","Republic of Peru"," República del Perú"],"region":"Americas","subregion":"South America","population":31488700,"latlng":[-10.0,-76.0],"demonym":"Peruvian","area":1285216.0,"gini":48.1,"timezones":["UTC-05:00"],"borders":["BOL","BRA","CHL","COL","ECU"],"nativeName":"Perú","numericCode":"604","currencies":[{"code":"PEN","name":"Peruvian sol","symbol":"S/."}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Peru","es":"Perú","fr":"Pérou","ja":"ペルー","it":"Perù","br":"Peru","pt":"Peru","nl":"Peru","hr":"Peru","fa":"پرو"},"flag":"https://restcountries.eu/data/per.svg","regionalBlocs":[{"acronym":"PA","name":"Pacific Alliance","otherAcronyms":[],"otherNames":["Alianza del Pacífico"]},{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"PER"} +{"name":"Philippines","topLevelDomain":[".ph"],"alpha2Code":"PH","alpha3Code":"PHL","callingCodes":["63"],"capital":"Manila","altSpellings":["PH","Republic of the Philippines","Repúblika ng Pilipinas"],"region":"Asia","subregion":"South-Eastern Asia","population":103279800,"latlng":[13.0,122.0],"demonym":"Filipino","area":342353.0,"gini":43.0,"timezones":["UTC+08:00"],"borders":[],"nativeName":"Pilipinas","numericCode":"608","currencies":[{"code":"PHP","name":"Philippine peso","symbol":"₱"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Philippinen","es":"Filipinas","fr":"Philippines","ja":"フィリピン","it":"Filippine","br":"Filipinas","pt":"Filipinas","nl":"Filipijnen","hr":"Filipini","fa":"جزایر الندفیلیپین"},"flag":"https://restcountries.eu/data/phl.svg","regionalBlocs":[{"acronym":"ASEAN","name":"Association of Southeast Asian Nations","otherAcronyms":[],"otherNames":[]}],"cioc":"PHI"} +{"name":"Pitcairn","topLevelDomain":[".pn"],"alpha2Code":"PN","alpha3Code":"PCN","callingCodes":["64"],"capital":"Adamstown","altSpellings":["PN","Pitcairn Henderson Ducie and Oeno Islands"],"region":"Oceania","subregion":"Polynesia","population":56,"latlng":[-25.06666666,-130.1],"demonym":"Pitcairn Islander","area":47.0,"gini":null,"timezones":["UTC-08:00"],"borders":[],"nativeName":"Pitcairn Islands","numericCode":"612","currencies":[{"code":"NZD","name":"New Zealand dollar","symbol":"$"},{"code":null,"name":"Pitcairn Islands dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Pitcairn","es":"Islas Pitcairn","fr":"Îles Pitcairn","ja":"ピトケアン","it":"Isole Pitcairn","br":"Ilhas Pitcairn","pt":"Ilhas Picárnia","nl":"Pitcairneilanden","hr":"Pitcairnovo otočje","fa":"پیتکرن"},"flag":"https://restcountries.eu/data/pcn.svg","regionalBlocs":[],"cioc":""} +{"name":"Poland","topLevelDomain":[".pl"],"alpha2Code":"PL","alpha3Code":"POL","callingCodes":["48"],"capital":"Warsaw","altSpellings":["PL","Republic of Poland","Rzeczpospolita Polska"],"region":"Europe","subregion":"Eastern Europe","population":38437239,"latlng":[52.0,20.0],"demonym":"Polish","area":312679.0,"gini":34.1,"timezones":["UTC+01:00"],"borders":["BLR","CZE","DEU","LTU","RUS","SVK","UKR"],"nativeName":"Polska","numericCode":"616","currencies":[{"code":"PLN","name":"Polish złoty","symbol":"zł"}],"languages":[{"iso639_1":"pl","iso639_2":"pol","name":"Polish","nativeName":"język polski"}],"translations":{"de":"Polen","es":"Polonia","fr":"Pologne","ja":"ポーランド","it":"Polonia","br":"Polônia","pt":"Polónia","nl":"Polen","hr":"Poljska","fa":"لهستان"},"flag":"https://restcountries.eu/data/pol.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"POL"} +{"name":"Portugal","topLevelDomain":[".pt"],"alpha2Code":"PT","alpha3Code":"PRT","callingCodes":["351"],"capital":"Lisbon","altSpellings":["PT","Portuguesa","Portuguese Republic","República Portuguesa"],"region":"Europe","subregion":"Southern Europe","population":10374822,"latlng":[39.5,-8.0],"demonym":"Portuguese","area":92090.0,"gini":38.5,"timezones":["UTC-01:00","UTC"],"borders":["ESP"],"nativeName":"Portugal","numericCode":"620","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"pt","iso639_2":"por","name":"Portuguese","nativeName":"Português"}],"translations":{"de":"Portugal","es":"Portugal","fr":"Portugal","ja":"ポルトガル","it":"Portogallo","br":"Portugal","pt":"Portugal","nl":"Portugal","hr":"Portugal","fa":"پرتغال"},"flag":"https://restcountries.eu/data/prt.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"POR"} +{"name":"Puerto Rico","topLevelDomain":[".pr"],"alpha2Code":"PR","alpha3Code":"PRI","callingCodes":["1787","1939"],"capital":"San Juan","altSpellings":["PR","Commonwealth of Puerto Rico","Estado Libre Asociado de Puerto Rico"],"region":"Americas","subregion":"Caribbean","population":3474182,"latlng":[18.25,-66.5],"demonym":"Puerto Rican","area":8870.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Puerto Rico","numericCode":"630","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Puerto Rico","es":"Puerto Rico","fr":"Porto Rico","ja":"プエルトリコ","it":"Porto Rico","br":"Porto Rico","pt":"Porto Rico","nl":"Puerto Rico","hr":"Portoriko","fa":"پورتو ریکو"},"flag":"https://restcountries.eu/data/pri.svg","regionalBlocs":[],"cioc":"PUR"} +{"name":"Qatar","topLevelDomain":[".qa"],"alpha2Code":"QA","alpha3Code":"QAT","callingCodes":["974"],"capital":"Doha","altSpellings":["QA","State of Qatar","Dawlat Qaṭar"],"region":"Asia","subregion":"Western Asia","population":2587564,"latlng":[25.5,51.25],"demonym":"Qatari","area":11586.0,"gini":41.1,"timezones":["UTC+03:00"],"borders":["SAU"],"nativeName":"قطر","numericCode":"634","currencies":[{"code":"QAR","name":"Qatari riyal","symbol":"ر.ق"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Katar","es":"Catar","fr":"Qatar","ja":"カタール","it":"Qatar","br":"Catar","pt":"Catar","nl":"Qatar","hr":"Katar","fa":"قطر"},"flag":"https://restcountries.eu/data/qat.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"QAT"} +{"name":"Republic of Kosovo","topLevelDomain":[""],"alpha2Code":"XK","alpha3Code":"KOS","callingCodes":["383"],"capital":"Pristina","altSpellings":["XK","Република Косово"],"region":"Europe","subregion":"Eastern Europe","population":1733842,"latlng":[42.666667,21.166667],"demonym":"Kosovar","area":10908.0,"gini":null,"timezones":["UTC+01:00"],"borders":["ALB","MKD","MNE","SRB"],"nativeName":"Republika e Kosovës","numericCode":null,"currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"sq","iso639_2":"sqi","name":"Albanian","nativeName":"Shqip"},{"iso639_1":"sr","iso639_2":"srp","name":"Serbian","nativeName":"српски језик"}],"translations":{"de":null,"es":"Kosovo","fr":null,"ja":null,"it":null,"br":"Kosovo","pt":"Kosovo","nl":null,"hr":"Kosovo","fa":"کوزوو"},"flag":"https://restcountries.eu/data/kos.svg","regionalBlocs":[{"acronym":"CEFTA","name":"Central European Free Trade Agreement","otherAcronyms":[],"otherNames":[]}],"cioc":null} +{"name":"Réunion","topLevelDomain":[".re"],"alpha2Code":"RE","alpha3Code":"REU","callingCodes":["262"],"capital":"Saint-Denis","altSpellings":["RE","Reunion"],"region":"Africa","subregion":"Eastern Africa","population":840974,"latlng":[-21.15,55.5],"demonym":"French","area":null,"gini":null,"timezones":["UTC+04:00"],"borders":[],"nativeName":"La Réunion","numericCode":"638","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Réunion","es":"Reunión","fr":"Réunion","ja":"レユニオン","it":"Riunione","br":"Reunião","pt":"Reunião","nl":"Réunion","hr":"Réunion","fa":"رئونیون"},"flag":"https://restcountries.eu/data/reu.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":""} +{"name":"Romania","topLevelDomain":[".ro"],"alpha2Code":"RO","alpha3Code":"ROU","callingCodes":["40"],"capital":"Bucharest","altSpellings":["RO","Rumania","Roumania","România"],"region":"Europe","subregion":"Eastern Europe","population":19861408,"latlng":[46.0,25.0],"demonym":"Romanian","area":238391.0,"gini":30.0,"timezones":["UTC+02:00"],"borders":["BGR","HUN","MDA","SRB","UKR"],"nativeName":"România","numericCode":"642","currencies":[{"code":"RON","name":"Romanian leu","symbol":"lei"}],"languages":[{"iso639_1":"ro","iso639_2":"ron","name":"Romanian","nativeName":"Română"}],"translations":{"de":"Rumänien","es":"Rumania","fr":"Roumanie","ja":"ルーマニア","it":"Romania","br":"Romênia","pt":"Roménia","nl":"Roemenië","hr":"Rumunjska","fa":"رومانی"},"flag":"https://restcountries.eu/data/rou.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"ROU"} +{"name":"Russian Federation","topLevelDomain":[".ru"],"alpha2Code":"RU","alpha3Code":"RUS","callingCodes":["7"],"capital":"Moscow","altSpellings":["RU","Rossiya","Russian Federation","Российская Федерация","Rossiyskaya Federatsiya"],"region":"Europe","subregion":"Eastern Europe","population":146599183,"latlng":[60.0,100.0],"demonym":"Russian","area":1.7124442E7,"gini":40.1,"timezones":["UTC+03:00","UTC+04:00","UTC+06:00","UTC+07:00","UTC+08:00","UTC+09:00","UTC+10:00","UTC+11:00","UTC+12:00"],"borders":["AZE","BLR","CHN","EST","FIN","GEO","KAZ","PRK","LVA","LTU","MNG","NOR","POL","UKR"],"nativeName":"Россия","numericCode":"643","currencies":[{"code":"RUB","name":"Russian ruble","symbol":"₽"}],"languages":[{"iso639_1":"ru","iso639_2":"rus","name":"Russian","nativeName":"Русский"}],"translations":{"de":"Russland","es":"Rusia","fr":"Russie","ja":"ロシア連邦","it":"Russia","br":"Rússia","pt":"Rússia","nl":"Rusland","hr":"Rusija","fa":"روسیه"},"flag":"https://restcountries.eu/data/rus.svg","regionalBlocs":[{"acronym":"EEU","name":"Eurasian Economic Union","otherAcronyms":["EAEU"],"otherNames":[]}],"cioc":"RUS"} +{"name":"Rwanda","topLevelDomain":[".rw"],"alpha2Code":"RW","alpha3Code":"RWA","callingCodes":["250"],"capital":"Kigali","altSpellings":["RW","Republic of Rwanda","Repubulika y'u Rwanda","République du Rwanda"],"region":"Africa","subregion":"Eastern Africa","population":11553188,"latlng":[-2.0,30.0],"demonym":"Rwandan","area":26338.0,"gini":50.8,"timezones":["UTC+02:00"],"borders":["BDI","COD","TZA","UGA"],"nativeName":"Rwanda","numericCode":"646","currencies":[{"code":"RWF","name":"Rwandan franc","symbol":"Fr"}],"languages":[{"iso639_1":"rw","iso639_2":"kin","name":"Kinyarwanda","nativeName":"Ikinyarwanda"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Ruanda","es":"Ruanda","fr":"Rwanda","ja":"ルワンダ","it":"Ruanda","br":"Ruanda","pt":"Ruanda","nl":"Rwanda","hr":"Ruanda","fa":"رواندا"},"flag":"https://restcountries.eu/data/rwa.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"RWA"} +{"name":"Saint Barthélemy","topLevelDomain":[".bl"],"alpha2Code":"BL","alpha3Code":"BLM","callingCodes":["590"],"capital":"Gustavia","altSpellings":["BL","St. Barthelemy","Collectivity of Saint Barthélemy","Collectivité de Saint-Barthélemy"],"region":"Americas","subregion":"Caribbean","population":9417,"latlng":[18.5,-63.41666666],"demonym":"Saint Barthélemy Islander","area":21.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Saint-Barthélemy","numericCode":"652","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Saint-Barthélemy","es":"San Bartolomé","fr":"Saint-Barthélemy","ja":"サン・バルテルミー","it":"Antille Francesi","br":"São Bartolomeu","pt":"São Bartolomeu","nl":"Saint Barthélemy","hr":"Saint Barthélemy","fa":"سن-بارتلمی"},"flag":"https://restcountries.eu/data/blm.svg","regionalBlocs":[],"cioc":""} +{"name":"Saint Helena, Ascension and Tristan da Cunha","topLevelDomain":[".sh"],"alpha2Code":"SH","alpha3Code":"SHN","callingCodes":["290"],"capital":"Jamestown","altSpellings":["SH"],"region":"Africa","subregion":"Western Africa","population":4255,"latlng":[-15.95,-5.7],"demonym":"Saint Helenian","area":null,"gini":null,"timezones":["UTC+00:00"],"borders":[],"nativeName":"Saint Helena","numericCode":"654","currencies":[{"code":"SHP","name":"Saint Helena pound","symbol":"£"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Sankt Helena","es":"Santa Helena","fr":"Sainte-Hélène","ja":"セントヘレナ・アセンションおよびトリスタンダクーニャ","it":"Sant'Elena","br":"Santa Helena","pt":"Santa Helena","nl":"Sint-Helena","hr":"Sveta Helena","fa":"سنت هلنا، اسنشن و تریستان دا کونا"},"flag":"https://restcountries.eu/data/shn.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":null} +{"name":"Saint Kitts and Nevis","topLevelDomain":[".kn"],"alpha2Code":"KN","alpha3Code":"KNA","callingCodes":["1869"],"capital":"Basseterre","altSpellings":["KN","Federation of Saint Christopher and Nevis"],"region":"Americas","subregion":"Caribbean","population":46204,"latlng":[17.33333333,-62.75],"demonym":"Kittian and Nevisian","area":261.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Saint Kitts and Nevis","numericCode":"659","currencies":[{"code":"XCD","name":"East Caribbean dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"St. Kitts und Nevis","es":"San Cristóbal y Nieves","fr":"Saint-Christophe-et-Niévès","ja":"セントクリストファー・ネイビス","it":"Saint Kitts e Nevis","br":"São Cristóvão e Neves","pt":"São Cristóvão e Neves","nl":"Saint Kitts en Nevis","hr":"Sveti Kristof i Nevis","fa":"سنت کیتس و نویس"},"flag":"https://restcountries.eu/data/kna.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]}],"cioc":"SKN"} +{"name":"Saint Lucia","topLevelDomain":[".lc"],"alpha2Code":"LC","alpha3Code":"LCA","callingCodes":["1758"],"capital":"Castries","altSpellings":["LC"],"region":"Americas","subregion":"Caribbean","population":186000,"latlng":[13.88333333,-60.96666666],"demonym":"Saint Lucian","area":616.0,"gini":42.6,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Saint Lucia","numericCode":"662","currencies":[{"code":"XCD","name":"East Caribbean dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Saint Lucia","es":"Santa Lucía","fr":"Saint-Lucie","ja":"セントルシア","it":"Santa Lucia","br":"Santa Lúcia","pt":"Santa Lúcia","nl":"Saint Lucia","hr":"Sveta Lucija","fa":"سنت لوسیا"},"flag":"https://restcountries.eu/data/lca.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]}],"cioc":"LCA"} +{"name":"Saint Martin (French part)","topLevelDomain":[".mf",".fr",".gp"],"alpha2Code":"MF","alpha3Code":"MAF","callingCodes":["590"],"capital":"Marigot","altSpellings":["MF","Collectivity of Saint Martin","Collectivité de Saint-Martin"],"region":"Americas","subregion":"Caribbean","population":36979,"latlng":[18.08333333,-63.95],"demonym":"Saint Martin Islander","area":53.0,"gini":null,"timezones":["UTC-04:00"],"borders":["SXM","NLD"],"nativeName":"Saint-Martin","numericCode":"663","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"nl","iso639_2":"nld","name":"Dutch","nativeName":"Nederlands"}],"translations":{"de":"Saint Martin","es":"Saint Martin","fr":"Saint-Martin","ja":"サン・マルタン(フランス領)","it":"Saint Martin","br":"Saint Martin","pt":"Ilha São Martinho","nl":"Saint-Martin","hr":"Sveti Martin","fa":"سینت مارتن"},"flag":"https://restcountries.eu/data/maf.svg","regionalBlocs":[],"cioc":""} +{"name":"Saint Pierre and Miquelon","topLevelDomain":[".pm"],"alpha2Code":"PM","alpha3Code":"SPM","callingCodes":["508"],"capital":"Saint-Pierre","altSpellings":["PM","Collectivité territoriale de Saint-Pierre-et-Miquelon"],"region":"Americas","subregion":"Northern America","population":6069,"latlng":[46.83333333,-56.33333333],"demonym":"French","area":242.0,"gini":null,"timezones":["UTC-03:00"],"borders":[],"nativeName":"Saint-Pierre-et-Miquelon","numericCode":"666","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Saint-Pierre und Miquelon","es":"San Pedro y Miquelón","fr":"Saint-Pierre-et-Miquelon","ja":"サンピエール島・ミクロン島","it":"Saint-Pierre e Miquelon","br":"Saint-Pierre e Miquelon","pt":"São Pedro e Miquelon","nl":"Saint Pierre en Miquelon","hr":"Sveti Petar i Mikelon","fa":"سن پیر و میکلن"},"flag":"https://restcountries.eu/data/spm.svg","regionalBlocs":[],"cioc":""} +{"name":"Saint Vincent and the Grenadines","topLevelDomain":[".vc"],"alpha2Code":"VC","alpha3Code":"VCT","callingCodes":["1784"],"capital":"Kingstown","altSpellings":["VC"],"region":"Americas","subregion":"Caribbean","population":109991,"latlng":[13.25,-61.2],"demonym":"Saint Vincentian","area":389.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Saint Vincent and the Grenadines","numericCode":"670","currencies":[{"code":"XCD","name":"East Caribbean dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Saint Vincent und die Grenadinen","es":"San Vicente y Granadinas","fr":"Saint-Vincent-et-les-Grenadines","ja":"セントビンセントおよびグレナディーン諸島","it":"Saint Vincent e Grenadine","br":"São Vicente e Granadinas","pt":"São Vicente e Granadinas","nl":"Saint Vincent en de Grenadines","hr":"Sveti Vincent i Grenadini","fa":"سنت وینسنت و گرنادین‌ها"},"flag":"https://restcountries.eu/data/vct.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]}],"cioc":"VIN"} +{"name":"Samoa","topLevelDomain":[".ws"],"alpha2Code":"WS","alpha3Code":"WSM","callingCodes":["685"],"capital":"Apia","altSpellings":["WS","Independent State of Samoa","Malo Saʻoloto Tutoʻatasi o Sāmoa"],"region":"Oceania","subregion":"Polynesia","population":194899,"latlng":[-13.58333333,-172.33333333],"demonym":"Samoan","area":2842.0,"gini":null,"timezones":["UTC+13:00"],"borders":[],"nativeName":"Samoa","numericCode":"882","currencies":[{"code":"WST","name":"Samoan tālā","symbol":"T"}],"languages":[{"iso639_1":"sm","iso639_2":"smo","name":"Samoan","nativeName":"gagana fa'a Samoa"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Samoa","es":"Samoa","fr":"Samoa","ja":"サモア","it":"Samoa","br":"Samoa","pt":"Samoa","nl":"Samoa","hr":"Samoa","fa":"ساموآ"},"flag":"https://restcountries.eu/data/wsm.svg","regionalBlocs":[],"cioc":"SAM"} +{"name":"San Marino","topLevelDomain":[".sm"],"alpha2Code":"SM","alpha3Code":"SMR","callingCodes":["378"],"capital":"City of San Marino","altSpellings":["SM","Republic of San Marino","Repubblica di San Marino"],"region":"Europe","subregion":"Southern Europe","population":33005,"latlng":[43.76666666,12.41666666],"demonym":"Sammarinese","area":61.0,"gini":null,"timezones":["UTC+01:00"],"borders":["ITA"],"nativeName":"San Marino","numericCode":"674","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"it","iso639_2":"ita","name":"Italian","nativeName":"Italiano"}],"translations":{"de":"San Marino","es":"San Marino","fr":"Saint-Marin","ja":"サンマリノ","it":"San Marino","br":"San Marino","pt":"São Marinho","nl":"San Marino","hr":"San Marino","fa":"سان مارینو"},"flag":"https://restcountries.eu/data/smr.svg","regionalBlocs":[],"cioc":"SMR"} +{"name":"Sao Tome and Principe","topLevelDomain":[".st"],"alpha2Code":"ST","alpha3Code":"STP","callingCodes":["239"],"capital":"São Tomé","altSpellings":["ST","Democratic Republic of São Tomé and Príncipe","República Democrática de São Tomé e Príncipe"],"region":"Africa","subregion":"Middle Africa","population":187356,"latlng":[1.0,7.0],"demonym":"Sao Tomean","area":964.0,"gini":50.8,"timezones":["UTC"],"borders":[],"nativeName":"São Tomé e Príncipe","numericCode":"678","currencies":[{"code":"STD","name":"São Tomé and Príncipe dobra","symbol":"Db"}],"languages":[{"iso639_1":"pt","iso639_2":"por","name":"Portuguese","nativeName":"Português"}],"translations":{"de":"São Tomé und Príncipe","es":"Santo Tomé y Príncipe","fr":"Sao Tomé-et-Principe","ja":"サントメ・プリンシペ","it":"São Tomé e Príncipe","br":"São Tomé e Príncipe","pt":"São Tomé e Príncipe","nl":"Sao Tomé en Principe","hr":"Sveti Toma i Princip","fa":"کواترو دو فرویرو"},"flag":"https://restcountries.eu/data/stp.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"STP"} +{"name":"Saudi Arabia","topLevelDomain":[".sa"],"alpha2Code":"SA","alpha3Code":"SAU","callingCodes":["966"],"capital":"Riyadh","altSpellings":["SA","Kingdom of Saudi Arabia","Al-Mamlakah al-‘Arabiyyah as-Su‘ūdiyyah"],"region":"Asia","subregion":"Western Asia","population":32248200,"latlng":[25.0,45.0],"demonym":"Saudi Arabian","area":2149690.0,"gini":null,"timezones":["UTC+03:00"],"borders":["IRQ","JOR","KWT","OMN","QAT","ARE","YEM"],"nativeName":"العربية السعودية","numericCode":"682","currencies":[{"code":"SAR","name":"Saudi riyal","symbol":"ر.س"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Saudi-Arabien","es":"Arabia Saudí","fr":"Arabie Saoudite","ja":"サウジアラビア","it":"Arabia Saudita","br":"Arábia Saudita","pt":"Arábia Saudita","nl":"Saoedi-Arabië","hr":"Saudijska Arabija","fa":"عربستان سعودی"},"flag":"https://restcountries.eu/data/sau.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"KSA"} +{"name":"Senegal","topLevelDomain":[".sn"],"alpha2Code":"SN","alpha3Code":"SEN","callingCodes":["221"],"capital":"Dakar","altSpellings":["SN","Republic of Senegal","République du Sénégal"],"region":"Africa","subregion":"Western Africa","population":14799859,"latlng":[14.0,-14.0],"demonym":"Senegalese","area":196722.0,"gini":39.2,"timezones":["UTC"],"borders":["GMB","GIN","GNB","MLI","MRT"],"nativeName":"Sénégal","numericCode":"686","currencies":[{"code":"XOF","name":"West African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Senegal","es":"Senegal","fr":"Sénégal","ja":"セネガル","it":"Senegal","br":"Senegal","pt":"Senegal","nl":"Senegal","hr":"Senegal","fa":"سنگال"},"flag":"https://restcountries.eu/data/sen.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"SEN"} +{"name":"Serbia","topLevelDomain":[".rs"],"alpha2Code":"RS","alpha3Code":"SRB","callingCodes":["381"],"capital":"Belgrade","altSpellings":["RS","Srbija","Republic of Serbia","Република Србија","Republika Srbija"],"region":"Europe","subregion":"Southern Europe","population":7076372,"latlng":[44.0,21.0],"demonym":"Serbian","area":88361.0,"gini":27.8,"timezones":["UTC+01:00"],"borders":["BIH","BGR","HRV","HUN","KOS","MKD","MNE","ROU"],"nativeName":"Србија","numericCode":"688","currencies":[{"code":"RSD","name":"Serbian dinar","symbol":"дин."}],"languages":[{"iso639_1":"sr","iso639_2":"srp","name":"Serbian","nativeName":"српски језик"}],"translations":{"de":"Serbien","es":"Serbia","fr":"Serbie","ja":"セルビア","it":"Serbia","br":"Sérvia","pt":"Sérvia","nl":"Servië","hr":"Srbija","fa":"صربستان"},"flag":"https://restcountries.eu/data/srb.svg","regionalBlocs":[{"acronym":"CEFTA","name":"Central European Free Trade Agreement","otherAcronyms":[],"otherNames":[]}],"cioc":"SRB"} +{"name":"Seychelles","topLevelDomain":[".sc"],"alpha2Code":"SC","alpha3Code":"SYC","callingCodes":["248"],"capital":"Victoria","altSpellings":["SC","Republic of Seychelles","Repiblik Sesel","République des Seychelles"],"region":"Africa","subregion":"Eastern Africa","population":91400,"latlng":[-4.58333333,55.66666666],"demonym":"Seychellois","area":452.0,"gini":65.8,"timezones":["UTC+04:00"],"borders":[],"nativeName":"Seychelles","numericCode":"690","currencies":[{"code":"SCR","name":"Seychellois rupee","symbol":"₨"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Seychellen","es":"Seychelles","fr":"Seychelles","ja":"セーシェル","it":"Seychelles","br":"Seicheles","pt":"Seicheles","nl":"Seychellen","hr":"Sejšeli","fa":"سیشل"},"flag":"https://restcountries.eu/data/syc.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"SEY"} +{"name":"Sierra Leone","topLevelDomain":[".sl"],"alpha2Code":"SL","alpha3Code":"SLE","callingCodes":["232"],"capital":"Freetown","altSpellings":["SL","Republic of Sierra Leone"],"region":"Africa","subregion":"Western Africa","population":7075641,"latlng":[8.5,-11.5],"demonym":"Sierra Leonean","area":71740.0,"gini":42.5,"timezones":["UTC"],"borders":["GIN","LBR"],"nativeName":"Sierra Leone","numericCode":"694","currencies":[{"code":"SLL","name":"Sierra Leonean leone","symbol":"Le"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Sierra Leone","es":"Sierra Leone","fr":"Sierra Leone","ja":"シエラレオネ","it":"Sierra Leone","br":"Serra Leoa","pt":"Serra Leoa","nl":"Sierra Leone","hr":"Sijera Leone","fa":"سیرالئون"},"flag":"https://restcountries.eu/data/sle.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"SLE"} +{"name":"Singapore","topLevelDomain":[".sg"],"alpha2Code":"SG","alpha3Code":"SGP","callingCodes":["65"],"capital":"Singapore","altSpellings":["SG","Singapura","Republik Singapura","新加坡共和国"],"region":"Asia","subregion":"South-Eastern Asia","population":5535000,"latlng":[1.36666666,103.8],"demonym":"Singaporean","area":710.0,"gini":48.1,"timezones":["UTC+08:00"],"borders":[],"nativeName":"Singapore","numericCode":"702","currencies":[{"code":"BND","name":"Brunei dollar","symbol":"$"},{"code":"SGD","name":"Singapore dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"ms","iso639_2":"msa","name":"Malay","nativeName":"bahasa Melayu"},{"iso639_1":"ta","iso639_2":"tam","name":"Tamil","nativeName":"தமிழ்"},{"iso639_1":"zh","iso639_2":"zho","name":"Chinese","nativeName":"中文 (Zhōngwén)"}],"translations":{"de":"Singapur","es":"Singapur","fr":"Singapour","ja":"シンガポール","it":"Singapore","br":"Singapura","pt":"Singapura","nl":"Singapore","hr":"Singapur","fa":"سنگاپور"},"flag":"https://restcountries.eu/data/sgp.svg","regionalBlocs":[{"acronym":"ASEAN","name":"Association of Southeast Asian Nations","otherAcronyms":[],"otherNames":[]}],"cioc":"SIN"} +{"name":"Sint Maarten (Dutch part)","topLevelDomain":[".sx"],"alpha2Code":"SX","alpha3Code":"SXM","callingCodes":["1721"],"capital":"Philipsburg","altSpellings":["SX"],"region":"Americas","subregion":"Caribbean","population":38247,"latlng":[18.033333,-63.05],"demonym":"Dutch","area":34.0,"gini":null,"timezones":["UTC-04:00"],"borders":["MAF"],"nativeName":"Sint Maarten","numericCode":"534","currencies":[{"code":"ANG","name":"Netherlands Antillean guilder","symbol":"ƒ"}],"languages":[{"iso639_1":"nl","iso639_2":"nld","name":"Dutch","nativeName":"Nederlands"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Sint Maarten (niederl. Teil)","es":null,"fr":"Saint Martin (partie néerlandaise)","ja":null,"it":"Saint Martin (parte olandese)","br":"Sint Maarten","pt":"São Martinho","nl":"Sint Maarten","hr":null,"fa":"سینت مارتن"},"flag":"https://restcountries.eu/data/sxm.svg","regionalBlocs":[],"cioc":""} +{"name":"Slovakia","topLevelDomain":[".sk"],"alpha2Code":"SK","alpha3Code":"SVK","callingCodes":["421"],"capital":"Bratislava","altSpellings":["SK","Slovak Republic","Slovenská republika"],"region":"Europe","subregion":"Eastern Europe","population":5426252,"latlng":[48.66666666,19.5],"demonym":"Slovak","area":49037.0,"gini":26.0,"timezones":["UTC+01:00"],"borders":["AUT","CZE","HUN","POL","UKR"],"nativeName":"Slovensko","numericCode":"703","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"sk","iso639_2":"slk","name":"Slovak","nativeName":"slovenčina"}],"translations":{"de":"Slowakei","es":"República Eslovaca","fr":"Slovaquie","ja":"スロバキア","it":"Slovacchia","br":"Eslováquia","pt":"Eslováquia","nl":"Slowakije","hr":"Slovačka","fa":"اسلواکی"},"flag":"https://restcountries.eu/data/svk.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"SVK"} +{"name":"Slovenia","topLevelDomain":[".si"],"alpha2Code":"SI","alpha3Code":"SVN","callingCodes":["386"],"capital":"Ljubljana","altSpellings":["SI","Republic of Slovenia","Republika Slovenija"],"region":"Europe","subregion":"Southern Europe","population":2064188,"latlng":[46.11666666,14.81666666],"demonym":"Slovene","area":20273.0,"gini":31.2,"timezones":["UTC+01:00"],"borders":["AUT","HRV","ITA","HUN"],"nativeName":"Slovenija","numericCode":"705","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"sl","iso639_2":"slv","name":"Slovene","nativeName":"slovenski jezik"}],"translations":{"de":"Slowenien","es":"Eslovenia","fr":"Slovénie","ja":"スロベニア","it":"Slovenia","br":"Eslovênia","pt":"Eslovénia","nl":"Slovenië","hr":"Slovenija","fa":"اسلوونی"},"flag":"https://restcountries.eu/data/svn.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"SLO"} +{"name":"Solomon Islands","topLevelDomain":[".sb"],"alpha2Code":"SB","alpha3Code":"SLB","callingCodes":["677"],"capital":"Honiara","altSpellings":["SB"],"region":"Oceania","subregion":"Melanesia","population":642000,"latlng":[-8.0,159.0],"demonym":"Solomon Islander","area":28896.0,"gini":null,"timezones":["UTC+11:00"],"borders":[],"nativeName":"Solomon Islands","numericCode":"090","currencies":[{"code":"SBD","name":"Solomon Islands dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Salomonen","es":"Islas Salomón","fr":"Îles Salomon","ja":"ソロモン諸島","it":"Isole Salomone","br":"Ilhas Salomão","pt":"Ilhas Salomão","nl":"Salomonseilanden","hr":"Solomonski Otoci","fa":"جزایر سلیمان"},"flag":"https://restcountries.eu/data/slb.svg","regionalBlocs":[],"cioc":"SOL"} +{"name":"Somalia","topLevelDomain":[".so"],"alpha2Code":"SO","alpha3Code":"SOM","callingCodes":["252"],"capital":"Mogadishu","altSpellings":["SO","aṣ-Ṣūmāl","Federal Republic of Somalia","Jamhuuriyadda Federaalka Soomaaliya","Jumhūriyyat aṣ-Ṣūmāl al-Fiderāliyya"],"region":"Africa","subregion":"Eastern Africa","population":11079000,"latlng":[10.0,49.0],"demonym":"Somali","area":637657.0,"gini":null,"timezones":["UTC+03:00"],"borders":["DJI","ETH","KEN"],"nativeName":"Soomaaliya","numericCode":"706","currencies":[{"code":"SOS","name":"Somali shilling","symbol":"Sh"}],"languages":[{"iso639_1":"so","iso639_2":"som","name":"Somali","nativeName":"Soomaaliga"},{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Somalia","es":"Somalia","fr":"Somalie","ja":"ソマリア","it":"Somalia","br":"Somália","pt":"Somália","nl":"Somalië","hr":"Somalija","fa":"سومالی"},"flag":"https://restcountries.eu/data/som.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]},{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"SOM"} +{"name":"South Africa","topLevelDomain":[".za"],"alpha2Code":"ZA","alpha3Code":"ZAF","callingCodes":["27"],"capital":"Pretoria","altSpellings":["ZA","RSA","Suid-Afrika","Republic of South Africa"],"region":"Africa","subregion":"Southern Africa","population":55653654,"latlng":[-29.0,24.0],"demonym":"South African","area":1221037.0,"gini":63.1,"timezones":["UTC+02:00"],"borders":["BWA","LSO","MOZ","NAM","SWZ","ZWE"],"nativeName":"South Africa","numericCode":"710","currencies":[{"code":"ZAR","name":"South African rand","symbol":"R"}],"languages":[{"iso639_1":"af","iso639_2":"afr","name":"Afrikaans","nativeName":"Afrikaans"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"nr","iso639_2":"nbl","name":"Southern Ndebele","nativeName":"isiNdebele"},{"iso639_1":"st","iso639_2":"sot","name":"Southern Sotho","nativeName":"Sesotho"},{"iso639_1":"ss","iso639_2":"ssw","name":"Swati","nativeName":"SiSwati"},{"iso639_1":"tn","iso639_2":"tsn","name":"Tswana","nativeName":"Setswana"},{"iso639_1":"ts","iso639_2":"tso","name":"Tsonga","nativeName":"Xitsonga"},{"iso639_1":"ve","iso639_2":"ven","name":"Venda","nativeName":"Tshivenḓa"},{"iso639_1":"xh","iso639_2":"xho","name":"Xhosa","nativeName":"isiXhosa"},{"iso639_1":"zu","iso639_2":"zul","name":"Zulu","nativeName":"isiZulu"}],"translations":{"de":"Republik Südafrika","es":"República de Sudáfrica","fr":"Afrique du Sud","ja":"南アフリカ","it":"Sud Africa","br":"República Sul-Africana","pt":"República Sul-Africana","nl":"Zuid-Afrika","hr":"Južnoafrička Republika","fa":"آفریقای جنوبی"},"flag":"https://restcountries.eu/data/zaf.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"RSA"} +{"name":"South Georgia and the South Sandwich Islands","topLevelDomain":[".gs"],"alpha2Code":"GS","alpha3Code":"SGS","callingCodes":["500"],"capital":"King Edward Point","altSpellings":["GS","South Georgia and the South Sandwich Islands"],"region":"Americas","subregion":"South America","population":30,"latlng":[-54.5,-37.0],"demonym":"South Georgia and the South Sandwich Islander","area":null,"gini":null,"timezones":["UTC-02:00"],"borders":[],"nativeName":"South Georgia","numericCode":"239","currencies":[{"code":"GBP","name":"British pound","symbol":"£"},{"code":"(none)","name":null,"symbol":"£"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Südgeorgien und die Südlichen Sandwichinseln","es":"Islas Georgias del Sur y Sandwich del Sur","fr":"Géorgie du Sud-et-les Îles Sandwich du Sud","ja":"サウスジョージア・サウスサンドウィッチ諸島","it":"Georgia del Sud e Isole Sandwich Meridionali","br":"Ilhas Geórgias do Sul e Sandwich do Sul","pt":"Ilhas Geórgia do Sul e Sanduíche do Sul","nl":"Zuid-Georgia en Zuidelijke Sandwicheilanden","hr":"Južna Georgija i otočje Južni Sandwich","fa":"جزایر جورجیای جنوبی و ساندویچ جنوبی"},"flag":"https://restcountries.eu/data/sgs.svg","regionalBlocs":[{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":""} +{"name":"Korea (Republic of)","topLevelDomain":[".kr"],"alpha2Code":"KR","alpha3Code":"KOR","callingCodes":["82"],"capital":"Seoul","altSpellings":["KR","Republic of Korea"],"region":"Asia","subregion":"Eastern Asia","population":50801405,"latlng":[37.0,127.5],"demonym":"South Korean","area":100210.0,"gini":31.3,"timezones":["UTC+09:00"],"borders":["PRK"],"nativeName":"대한민국","numericCode":"410","currencies":[{"code":"KRW","name":"South Korean won","symbol":"₩"}],"languages":[{"iso639_1":"ko","iso639_2":"kor","name":"Korean","nativeName":"한국어"}],"translations":{"de":"Südkorea","es":"Corea del Sur","fr":"Corée du Sud","ja":"大韓民国","it":"Corea del Sud","br":"Coreia do Sul","pt":"Coreia do Sul","nl":"Zuid-Korea","hr":"Južna Koreja","fa":"کره شمالی"},"flag":"https://restcountries.eu/data/kor.svg","regionalBlocs":[],"cioc":"KOR"} +{"name":"South Sudan","topLevelDomain":[".ss"],"alpha2Code":"SS","alpha3Code":"SSD","callingCodes":["211"],"capital":"Juba","altSpellings":["SS"],"region":"Africa","subregion":"Middle Africa","population":12131000,"latlng":[7.0,30.0],"demonym":"South Sudanese","area":619745.0,"gini":45.5,"timezones":["UTC+03:00"],"borders":["CAF","COD","ETH","KEN","SDN","UGA"],"nativeName":"South Sudan","numericCode":"728","currencies":[{"code":"SSP","name":"South Sudanese pound","symbol":"£"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Südsudan","es":"Sudán del Sur","fr":"Soudan du Sud","ja":"南スーダン","it":"Sudan del sud","br":"Sudão do Sul","pt":"Sudão do Sul","nl":"Zuid-Soedan","hr":"Južni Sudan","fa":"سودان جنوبی"},"flag":"https://restcountries.eu/data/ssd.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":""} +{"name":"Spain","topLevelDomain":[".es"],"alpha2Code":"ES","alpha3Code":"ESP","callingCodes":["34"],"capital":"Madrid","altSpellings":["ES","Kingdom of Spain","Reino de España"],"region":"Europe","subregion":"Southern Europe","population":46438422,"latlng":[40.0,-4.0],"demonym":"Spanish","area":505992.0,"gini":34.7,"timezones":["UTC","UTC+01:00"],"borders":["AND","FRA","GIB","PRT","MAR"],"nativeName":"España","numericCode":"724","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Spanien","es":"España","fr":"Espagne","ja":"スペイン","it":"Spagna","br":"Espanha","pt":"Espanha","nl":"Spanje","hr":"Španjolska","fa":"اسپانیا"},"flag":"https://restcountries.eu/data/esp.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"ESP"} +{"name":"Sri Lanka","topLevelDomain":[".lk"],"alpha2Code":"LK","alpha3Code":"LKA","callingCodes":["94"],"capital":"Colombo","altSpellings":["LK","ilaṅkai","Democratic Socialist Republic of Sri Lanka"],"region":"Asia","subregion":"Southern Asia","population":20966000,"latlng":[7.0,81.0],"demonym":"Sri Lankan","area":65610.0,"gini":40.3,"timezones":["UTC+05:30"],"borders":["IND"],"nativeName":"śrī laṃkāva","numericCode":"144","currencies":[{"code":"LKR","name":"Sri Lankan rupee","symbol":"Rs"}],"languages":[{"iso639_1":"si","iso639_2":"sin","name":"Sinhalese","nativeName":"සිංහල"},{"iso639_1":"ta","iso639_2":"tam","name":"Tamil","nativeName":"தமிழ்"}],"translations":{"de":"Sri Lanka","es":"Sri Lanka","fr":"Sri Lanka","ja":"スリランカ","it":"Sri Lanka","br":"Sri Lanka","pt":"Sri Lanka","nl":"Sri Lanka","hr":"Šri Lanka","fa":"سری‌لانکا"},"flag":"https://restcountries.eu/data/lka.svg","regionalBlocs":[{"acronym":"SAARC","name":"South Asian Association for Regional Cooperation","otherAcronyms":[],"otherNames":[]}],"cioc":"SRI"} +{"name":"Sudan","topLevelDomain":[".sd"],"alpha2Code":"SD","alpha3Code":"SDN","callingCodes":["249"],"capital":"Khartoum","altSpellings":["SD","Republic of the Sudan","Jumhūrīyat as-Sūdān"],"region":"Africa","subregion":"Northern Africa","population":39598700,"latlng":[15.0,30.0],"demonym":"Sudanese","area":1886068.0,"gini":35.3,"timezones":["UTC+03:00"],"borders":["CAF","TCD","EGY","ERI","ETH","LBY","SSD"],"nativeName":"السودان","numericCode":"729","currencies":[{"code":"SDG","name":"Sudanese pound","symbol":"ج.س."}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Sudan","es":"Sudán","fr":"Soudan","ja":"スーダン","it":"Sudan","br":"Sudão","pt":"Sudão","nl":"Soedan","hr":"Sudan","fa":"سودان"},"flag":"https://restcountries.eu/data/sdn.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]},{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"SUD"} +{"name":"Suriname","topLevelDomain":[".sr"],"alpha2Code":"SR","alpha3Code":"SUR","callingCodes":["597"],"capital":"Paramaribo","altSpellings":["SR","Sarnam","Sranangron","Republic of Suriname","Republiek Suriname"],"region":"Americas","subregion":"South America","population":541638,"latlng":[4.0,-56.0],"demonym":"Surinamer","area":163820.0,"gini":52.9,"timezones":["UTC-03:00"],"borders":["BRA","GUF","FRA","GUY"],"nativeName":"Suriname","numericCode":"740","currencies":[{"code":"SRD","name":"Surinamese dollar","symbol":"$"}],"languages":[{"iso639_1":"nl","iso639_2":"nld","name":"Dutch","nativeName":"Nederlands"}],"translations":{"de":"Suriname","es":"Surinam","fr":"Surinam","ja":"スリナム","it":"Suriname","br":"Suriname","pt":"Suriname","nl":"Suriname","hr":"Surinam","fa":"سورینام"},"flag":"https://restcountries.eu/data/sur.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]},{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"SUR"} +{"name":"Svalbard and Jan Mayen","topLevelDomain":[".sj"],"alpha2Code":"SJ","alpha3Code":"SJM","callingCodes":["4779"],"capital":"Longyearbyen","altSpellings":["SJ","Svalbard and Jan Mayen Islands"],"region":"Europe","subregion":"Northern Europe","population":2562,"latlng":[78.0,20.0],"demonym":"Norwegian","area":null,"gini":null,"timezones":["UTC+01:00"],"borders":[],"nativeName":"Svalbard og Jan Mayen","numericCode":"744","currencies":[{"code":"NOK","name":"Norwegian krone","symbol":"kr"}],"languages":[{"iso639_1":"no","iso639_2":"nor","name":"Norwegian","nativeName":"Norsk"}],"translations":{"de":"Svalbard und Jan Mayen","es":"Islas Svalbard y Jan Mayen","fr":"Svalbard et Jan Mayen","ja":"スヴァールバル諸島およびヤンマイエン島","it":"Svalbard e Jan Mayen","br":"Svalbard","pt":"Svalbard","nl":"Svalbard en Jan Mayen","hr":"Svalbard i Jan Mayen","fa":"سوالبارد و یان ماین"},"flag":"https://restcountries.eu/data/sjm.svg","regionalBlocs":[],"cioc":""} +{"name":"Swaziland","topLevelDomain":[".sz"],"alpha2Code":"SZ","alpha3Code":"SWZ","callingCodes":["268"],"capital":"Lobamba","altSpellings":["SZ","weSwatini","Swatini","Ngwane","Kingdom of Swaziland","Umbuso waseSwatini"],"region":"Africa","subregion":"Southern Africa","population":1132657,"latlng":[-26.5,31.5],"demonym":"Swazi","area":17364.0,"gini":51.5,"timezones":["UTC+02:00"],"borders":["MOZ","ZAF"],"nativeName":"Swaziland","numericCode":"748","currencies":[{"code":"SZL","name":"Swazi lilangeni","symbol":"L"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"ss","iso639_2":"ssw","name":"Swati","nativeName":"SiSwati"}],"translations":{"de":"Swasiland","es":"Suazilandia","fr":"Swaziland","ja":"スワジランド","it":"Swaziland","br":"Suazilândia","pt":"Suazilândia","nl":"Swaziland","hr":"Svazi","fa":"سوازیلند"},"flag":"https://restcountries.eu/data/swz.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"SWZ"} +{"name":"Sweden","topLevelDomain":[".se"],"alpha2Code":"SE","alpha3Code":"SWE","callingCodes":["46"],"capital":"Stockholm","altSpellings":["SE","Kingdom of Sweden","Konungariket Sverige"],"region":"Europe","subregion":"Northern Europe","population":9894888,"latlng":[62.0,15.0],"demonym":"Swedish","area":450295.0,"gini":25.0,"timezones":["UTC+01:00"],"borders":["FIN","NOR"],"nativeName":"Sverige","numericCode":"752","currencies":[{"code":"SEK","name":"Swedish krona","symbol":"kr"}],"languages":[{"iso639_1":"sv","iso639_2":"swe","name":"Swedish","nativeName":"svenska"}],"translations":{"de":"Schweden","es":"Suecia","fr":"Suède","ja":"スウェーデン","it":"Svezia","br":"Suécia","pt":"Suécia","nl":"Zweden","hr":"Švedska","fa":"سوئد"},"flag":"https://restcountries.eu/data/swe.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"SWE"} +{"name":"Switzerland","topLevelDomain":[".ch"],"alpha2Code":"CH","alpha3Code":"CHE","callingCodes":["41"],"capital":"Bern","altSpellings":["CH","Swiss Confederation","Schweiz","Suisse","Svizzera","Svizra"],"region":"Europe","subregion":"Western Europe","population":8341600,"latlng":[47.0,8.0],"demonym":"Swiss","area":41284.0,"gini":33.7,"timezones":["UTC+01:00"],"borders":["AUT","FRA","ITA","LIE","DEU"],"nativeName":"Schweiz","numericCode":"756","currencies":[{"code":"CHF","name":"Swiss franc","symbol":"Fr"}],"languages":[{"iso639_1":"de","iso639_2":"deu","name":"German","nativeName":"Deutsch"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"},{"iso639_1":"it","iso639_2":"ita","name":"Italian","nativeName":"Italiano"}],"translations":{"de":"Schweiz","es":"Suiza","fr":"Suisse","ja":"スイス","it":"Svizzera","br":"Suíça","pt":"Suíça","nl":"Zwitserland","hr":"Švicarska","fa":"سوئیس"},"flag":"https://restcountries.eu/data/che.svg","regionalBlocs":[{"acronym":"EFTA","name":"European Free Trade Association","otherAcronyms":[],"otherNames":[]}],"cioc":"SUI"} +{"name":"Syrian Arab Republic","topLevelDomain":[".sy"],"alpha2Code":"SY","alpha3Code":"SYR","callingCodes":["963"],"capital":"Damascus","altSpellings":["SY","Syrian Arab Republic","Al-Jumhūrīyah Al-ʻArabīyah As-Sūrīyah"],"region":"Asia","subregion":"Western Asia","population":18564000,"latlng":[35.0,38.0],"demonym":"Syrian","area":185180.0,"gini":35.8,"timezones":["UTC+02:00"],"borders":["IRQ","ISR","JOR","LBN","TUR"],"nativeName":"سوريا","numericCode":"760","currencies":[{"code":"SYP","name":"Syrian pound","symbol":"£"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Syrien","es":"Siria","fr":"Syrie","ja":"シリア・アラブ共和国","it":"Siria","br":"Síria","pt":"Síria","nl":"Syrië","hr":"Sirija","fa":"سوریه"},"flag":"https://restcountries.eu/data/syr.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"SYR"} +{"name":"Taiwan","topLevelDomain":[".tw"],"alpha2Code":"TW","alpha3Code":"TWN","callingCodes":["886"],"capital":"Taipei","altSpellings":["TW","Táiwān","Republic of China","中華民國","Zhōnghuá Mínguó"],"region":"Asia","subregion":"Eastern Asia","population":23503349,"latlng":[23.5,121.0],"demonym":"Taiwanese","area":36193.0,"gini":null,"timezones":["UTC+08:00"],"borders":[],"nativeName":"臺灣","numericCode":"158","currencies":[{"code":"TWD","name":"New Taiwan dollar","symbol":"$"}],"languages":[{"iso639_1":"zh","iso639_2":"zho","name":"Chinese","nativeName":"中文 (Zhōngwén)"}],"translations":{"de":"Taiwan","es":"Taiwán","fr":"Taïwan","ja":"台湾(中華民国)","it":"Taiwan","br":"Taiwan","pt":"Taiwan","nl":"Taiwan","hr":"Tajvan","fa":"تایوان"},"flag":"https://restcountries.eu/data/twn.svg","regionalBlocs":[],"cioc":"TPE"} +{"name":"Tajikistan","topLevelDomain":[".tj"],"alpha2Code":"TJ","alpha3Code":"TJK","callingCodes":["992"],"capital":"Dushanbe","altSpellings":["TJ","Toçikiston","Republic of Tajikistan","Ҷумҳурии Тоҷикистон","Çumhuriyi Toçikiston"],"region":"Asia","subregion":"Central Asia","population":8593600,"latlng":[39.0,71.0],"demonym":"Tadzhik","area":143100.0,"gini":30.8,"timezones":["UTC+05:00"],"borders":["AFG","CHN","KGZ","UZB"],"nativeName":"Тоҷикистон","numericCode":"762","currencies":[{"code":"TJS","name":"Tajikistani somoni","symbol":"ЅМ"}],"languages":[{"iso639_1":"tg","iso639_2":"tgk","name":"Tajik","nativeName":"тоҷикӣ"},{"iso639_1":"ru","iso639_2":"rus","name":"Russian","nativeName":"Русский"}],"translations":{"de":"Tadschikistan","es":"Tayikistán","fr":"Tadjikistan","ja":"タジキスタン","it":"Tagikistan","br":"Tajiquistão","pt":"Tajiquistão","nl":"Tadzjikistan","hr":"Tađikistan","fa":"تاجیکستان"},"flag":"https://restcountries.eu/data/tjk.svg","regionalBlocs":[],"cioc":"TJK"} +{"name":"Tanzania, United Republic of","topLevelDomain":[".tz"],"alpha2Code":"TZ","alpha3Code":"TZA","callingCodes":["255"],"capital":"Dodoma","altSpellings":["TZ","United Republic of Tanzania","Jamhuri ya Muungano wa Tanzania"],"region":"Africa","subregion":"Eastern Africa","population":55155000,"latlng":[-6.0,35.0],"demonym":"Tanzanian","area":945087.0,"gini":37.6,"timezones":["UTC+03:00"],"borders":["BDI","COD","KEN","MWI","MOZ","RWA","UGA","ZMB"],"nativeName":"Tanzania","numericCode":"834","currencies":[{"code":"TZS","name":"Tanzanian shilling","symbol":"Sh"}],"languages":[{"iso639_1":"sw","iso639_2":"swa","name":"Swahili","nativeName":"Kiswahili"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Tansania","es":"Tanzania","fr":"Tanzanie","ja":"タンザニア","it":"Tanzania","br":"Tanzânia","pt":"Tanzânia","nl":"Tanzania","hr":"Tanzanija","fa":"تانزانیا"},"flag":"https://restcountries.eu/data/tza.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"TAN"} +{"name":"Thailand","topLevelDomain":[".th"],"alpha2Code":"TH","alpha3Code":"THA","callingCodes":["66"],"capital":"Bangkok","altSpellings":["TH","Prathet","Thai","Kingdom of Thailand","ราชอาณาจักรไทย","Ratcha Anachak Thai"],"region":"Asia","subregion":"South-Eastern Asia","population":65327652,"latlng":[15.0,100.0],"demonym":"Thai","area":513120.0,"gini":40.0,"timezones":["UTC+07:00"],"borders":["MMR","KHM","LAO","MYS"],"nativeName":"ประเทศไทย","numericCode":"764","currencies":[{"code":"THB","name":"Thai baht","symbol":"฿"}],"languages":[{"iso639_1":"th","iso639_2":"tha","name":"Thai","nativeName":"ไทย"}],"translations":{"de":"Thailand","es":"Tailandia","fr":"Thaïlande","ja":"タイ","it":"Tailandia","br":"Tailândia","pt":"Tailândia","nl":"Thailand","hr":"Tajland","fa":"تایلند"},"flag":"https://restcountries.eu/data/tha.svg","regionalBlocs":[{"acronym":"ASEAN","name":"Association of Southeast Asian Nations","otherAcronyms":[],"otherNames":[]}],"cioc":"THA"} +{"name":"Timor-Leste","topLevelDomain":[".tl"],"alpha2Code":"TL","alpha3Code":"TLS","callingCodes":["670"],"capital":"Dili","altSpellings":["TL","East Timor","Democratic Republic of Timor-Leste","República Democrática de Timor-Leste","Repúblika Demokrátika Timór-Leste"],"region":"Asia","subregion":"South-Eastern Asia","population":1167242,"latlng":[-8.83333333,125.91666666],"demonym":"East Timorese","area":14874.0,"gini":31.9,"timezones":["UTC+09:00"],"borders":["IDN"],"nativeName":"Timor-Leste","numericCode":"626","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"},{"code":null,"name":null,"symbol":null}],"languages":[{"iso639_1":"pt","iso639_2":"por","name":"Portuguese","nativeName":"Português"}],"translations":{"de":"Timor-Leste","es":"Timor Oriental","fr":"Timor oriental","ja":"東ティモール","it":"Timor Est","br":"Timor Leste","pt":"Timor Leste","nl":"Oost-Timor","hr":"Istočni Timor","fa":"تیمور شرقی"},"flag":"https://restcountries.eu/data/tls.svg","regionalBlocs":[],"cioc":"TLS"} +{"name":"Togo","topLevelDomain":[".tg"],"alpha2Code":"TG","alpha3Code":"TGO","callingCodes":["228"],"capital":"Lomé","altSpellings":["TG","Togolese","Togolese Republic","République Togolaise"],"region":"Africa","subregion":"Western Africa","population":7143000,"latlng":[8.0,1.16666666],"demonym":"Togolese","area":56785.0,"gini":34.4,"timezones":["UTC"],"borders":["BEN","BFA","GHA"],"nativeName":"Togo","numericCode":"768","currencies":[{"code":"XOF","name":"West African CFA franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Togo","es":"Togo","fr":"Togo","ja":"トーゴ","it":"Togo","br":"Togo","pt":"Togo","nl":"Togo","hr":"Togo","fa":"توگو"},"flag":"https://restcountries.eu/data/tgo.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"TOG"} +{"name":"Tokelau","topLevelDomain":[".tk"],"alpha2Code":"TK","alpha3Code":"TKL","callingCodes":["690"],"capital":"Fakaofo","altSpellings":["TK"],"region":"Oceania","subregion":"Polynesia","population":1411,"latlng":[-9.0,-172.0],"demonym":"Tokelauan","area":12.0,"gini":null,"timezones":["UTC+13:00"],"borders":[],"nativeName":"Tokelau","numericCode":"772","currencies":[{"code":"NZD","name":"New Zealand dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Tokelau","es":"Islas Tokelau","fr":"Tokelau","ja":"トケラウ","it":"Isole Tokelau","br":"Tokelau","pt":"Toquelau","nl":"Tokelau","hr":"Tokelau","fa":"توکلائو"},"flag":"https://restcountries.eu/data/tkl.svg","regionalBlocs":[],"cioc":""} +{"name":"Tonga","topLevelDomain":[".to"],"alpha2Code":"TO","alpha3Code":"TON","callingCodes":["676"],"capital":"Nuku'alofa","altSpellings":["TO"],"region":"Oceania","subregion":"Polynesia","population":103252,"latlng":[-20.0,-175.0],"demonym":"Tongan","area":747.0,"gini":null,"timezones":["UTC+13:00"],"borders":[],"nativeName":"Tonga","numericCode":"776","currencies":[{"code":"TOP","name":"Tongan paʻanga","symbol":"T$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"to","iso639_2":"ton","name":"Tonga (Tonga Islands)","nativeName":"faka Tonga"}],"translations":{"de":"Tonga","es":"Tonga","fr":"Tonga","ja":"トンガ","it":"Tonga","br":"Tonga","pt":"Tonga","nl":"Tonga","hr":"Tonga","fa":"تونگا"},"flag":"https://restcountries.eu/data/ton.svg","regionalBlocs":[],"cioc":"TGA"} +{"name":"Trinidad and Tobago","topLevelDomain":[".tt"],"alpha2Code":"TT","alpha3Code":"TTO","callingCodes":["1868"],"capital":"Port of Spain","altSpellings":["TT","Republic of Trinidad and Tobago"],"region":"Americas","subregion":"Caribbean","population":1349667,"latlng":[11.0,-61.0],"demonym":"Trinidadian","area":5130.0,"gini":40.3,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Trinidad and Tobago","numericCode":"780","currencies":[{"code":"TTD","name":"Trinidad and Tobago dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Trinidad und Tobago","es":"Trinidad y Tobago","fr":"Trinité et Tobago","ja":"トリニダード・トバゴ","it":"Trinidad e Tobago","br":"Trinidad e Tobago","pt":"Trindade e Tobago","nl":"Trinidad en Tobago","hr":"Trinidad i Tobago","fa":"ترینیداد و توباگو"},"flag":"https://restcountries.eu/data/tto.svg","regionalBlocs":[{"acronym":"CARICOM","name":"Caribbean Community","otherAcronyms":[],"otherNames":["Comunidad del Caribe","Communauté Caribéenne","Caribische Gemeenschap"]}],"cioc":"TTO"} +{"name":"Tunisia","topLevelDomain":[".tn"],"alpha2Code":"TN","alpha3Code":"TUN","callingCodes":["216"],"capital":"Tunis","altSpellings":["TN","Republic of Tunisia","al-Jumhūriyyah at-Tūnisiyyah"],"region":"Africa","subregion":"Northern Africa","population":11154400,"latlng":[34.0,9.0],"demonym":"Tunisian","area":163610.0,"gini":41.4,"timezones":["UTC+01:00"],"borders":["DZA","LBY"],"nativeName":"تونس","numericCode":"788","currencies":[{"code":"TND","name":"Tunisian dinar","symbol":"د.ت"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Tunesien","es":"Túnez","fr":"Tunisie","ja":"チュニジア","it":"Tunisia","br":"Tunísia","pt":"Tunísia","nl":"Tunesië","hr":"Tunis","fa":"تونس"},"flag":"https://restcountries.eu/data/tun.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]},{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"TUN"} +{"name":"Turkey","topLevelDomain":[".tr"],"alpha2Code":"TR","alpha3Code":"TUR","callingCodes":["90"],"capital":"Ankara","altSpellings":["TR","Turkiye","Republic of Turkey","Türkiye Cumhuriyeti"],"region":"Asia","subregion":"Western Asia","population":78741053,"latlng":[39.0,35.0],"demonym":"Turkish","area":783562.0,"gini":39.0,"timezones":["UTC+03:00"],"borders":["ARM","AZE","BGR","GEO","GRC","IRN","IRQ","SYR"],"nativeName":"Türkiye","numericCode":"792","currencies":[{"code":"TRY","name":"Turkish lira","symbol":null}],"languages":[{"iso639_1":"tr","iso639_2":"tur","name":"Turkish","nativeName":"Türkçe"}],"translations":{"de":"Türkei","es":"Turquía","fr":"Turquie","ja":"トルコ","it":"Turchia","br":"Turquia","pt":"Turquia","nl":"Turkije","hr":"Turska","fa":"ترکیه"},"flag":"https://restcountries.eu/data/tur.svg","regionalBlocs":[],"cioc":"TUR"} +{"name":"Turkmenistan","topLevelDomain":[".tm"],"alpha2Code":"TM","alpha3Code":"TKM","callingCodes":["993"],"capital":"Ashgabat","altSpellings":["TM"],"region":"Asia","subregion":"Central Asia","population":4751120,"latlng":[40.0,60.0],"demonym":"Turkmen","area":488100.0,"gini":40.8,"timezones":["UTC+05:00"],"borders":["AFG","IRN","KAZ","UZB"],"nativeName":"Türkmenistan","numericCode":"795","currencies":[{"code":"TMT","name":"Turkmenistan manat","symbol":"m"}],"languages":[{"iso639_1":"tk","iso639_2":"tuk","name":"Turkmen","nativeName":"Türkmen"},{"iso639_1":"ru","iso639_2":"rus","name":"Russian","nativeName":"Русский"}],"translations":{"de":"Turkmenistan","es":"Turkmenistán","fr":"Turkménistan","ja":"トルクメニスタン","it":"Turkmenistan","br":"Turcomenistão","pt":"Turquemenistão","nl":"Turkmenistan","hr":"Turkmenistan","fa":"ترکمنستان"},"flag":"https://restcountries.eu/data/tkm.svg","regionalBlocs":[],"cioc":"TKM"} +{"name":"Turks and Caicos Islands","topLevelDomain":[".tc"],"alpha2Code":"TC","alpha3Code":"TCA","callingCodes":["1649"],"capital":"Cockburn Town","altSpellings":["TC"],"region":"Americas","subregion":"Caribbean","population":31458,"latlng":[21.75,-71.58333333],"demonym":"Turks and Caicos Islander","area":948.0,"gini":null,"timezones":["UTC-04:00"],"borders":[],"nativeName":"Turks and Caicos Islands","numericCode":"796","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Turks- und Caicosinseln","es":"Islas Turks y Caicos","fr":"Îles Turques-et-Caïques","ja":"タークス・カイコス諸島","it":"Isole Turks e Caicos","br":"Ilhas Turcas e Caicos","pt":"Ilhas Turcas e Caicos","nl":"Turks- en Caicoseilanden","hr":"Otoci Turks i Caicos","fa":"جزایر تورکس و کایکوس"},"flag":"https://restcountries.eu/data/tca.svg","regionalBlocs":[],"cioc":""} +{"name":"Tuvalu","topLevelDomain":[".tv"],"alpha2Code":"TV","alpha3Code":"TUV","callingCodes":["688"],"capital":"Funafuti","altSpellings":["TV"],"region":"Oceania","subregion":"Polynesia","population":10640,"latlng":[-8.0,178.0],"demonym":"Tuvaluan","area":26.0,"gini":null,"timezones":["UTC+12:00"],"borders":[],"nativeName":"Tuvalu","numericCode":"798","currencies":[{"code":"AUD","name":"Australian dollar","symbol":"$"},{"code":"TVD[G]","name":"Tuvaluan dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Tuvalu","es":"Tuvalu","fr":"Tuvalu","ja":"ツバル","it":"Tuvalu","br":"Tuvalu","pt":"Tuvalu","nl":"Tuvalu","hr":"Tuvalu","fa":"تووالو"},"flag":"https://restcountries.eu/data/tuv.svg","regionalBlocs":[],"cioc":"TUV"} +{"name":"Uganda","topLevelDomain":[".ug"],"alpha2Code":"UG","alpha3Code":"UGA","callingCodes":["256"],"capital":"Kampala","altSpellings":["UG","Republic of Uganda","Jamhuri ya Uganda"],"region":"Africa","subregion":"Eastern Africa","population":33860700,"latlng":[1.0,32.0],"demonym":"Ugandan","area":241550.0,"gini":44.3,"timezones":["UTC+03:00"],"borders":["COD","KEN","RWA","SSD","TZA"],"nativeName":"Uganda","numericCode":"800","currencies":[{"code":"UGX","name":"Ugandan shilling","symbol":"Sh"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"sw","iso639_2":"swa","name":"Swahili","nativeName":"Kiswahili"}],"translations":{"de":"Uganda","es":"Uganda","fr":"Uganda","ja":"ウガンダ","it":"Uganda","br":"Uganda","pt":"Uganda","nl":"Oeganda","hr":"Uganda","fa":"اوگاندا"},"flag":"https://restcountries.eu/data/uga.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"UGA"} +{"name":"Ukraine","topLevelDomain":[".ua"],"alpha2Code":"UA","alpha3Code":"UKR","callingCodes":["380"],"capital":"Kiev","altSpellings":["UA","Ukrayina"],"region":"Europe","subregion":"Eastern Europe","population":42692393,"latlng":[49.0,32.0],"demonym":"Ukrainian","area":603700.0,"gini":26.4,"timezones":["UTC+02:00"],"borders":["BLR","HUN","MDA","POL","ROU","RUS","SVK"],"nativeName":"Україна","numericCode":"804","currencies":[{"code":"UAH","name":"Ukrainian hryvnia","symbol":"₴"}],"languages":[{"iso639_1":"uk","iso639_2":"ukr","name":"Ukrainian","nativeName":"Українська"}],"translations":{"de":"Ukraine","es":"Ucrania","fr":"Ukraine","ja":"ウクライナ","it":"Ucraina","br":"Ucrânia","pt":"Ucrânia","nl":"Oekraïne","hr":"Ukrajina","fa":"وکراین"},"flag":"https://restcountries.eu/data/ukr.svg","regionalBlocs":[],"cioc":"UKR"} +{"name":"United Arab Emirates","topLevelDomain":[".ae"],"alpha2Code":"AE","alpha3Code":"ARE","callingCodes":["971"],"capital":"Abu Dhabi","altSpellings":["AE","UAE"],"region":"Asia","subregion":"Western Asia","population":9856000,"latlng":[24.0,54.0],"demonym":"Emirati","area":83600.0,"gini":null,"timezones":["UTC+04"],"borders":["OMN","SAU"],"nativeName":"دولة الإمارات العربية المتحدة","numericCode":"784","currencies":[{"code":"AED","name":"United Arab Emirates dirham","symbol":"د.إ"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Vereinigte Arabische Emirate","es":"Emiratos Árabes Unidos","fr":"Émirats arabes unis","ja":"アラブ首長国連邦","it":"Emirati Arabi Uniti","br":"Emirados árabes Unidos","pt":"Emirados árabes Unidos","nl":"Verenigde Arabische Emiraten","hr":"Ujedinjeni Arapski Emirati","fa":"امارات متحده عربی"},"flag":"https://restcountries.eu/data/are.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"UAE"} +{"name":"United Kingdom of Great Britain and Northern Ireland","topLevelDomain":[".uk"],"alpha2Code":"GB","alpha3Code":"GBR","callingCodes":["44"],"capital":"London","altSpellings":["GB","UK","Great Britain"],"region":"Europe","subregion":"Northern Europe","population":65110000,"latlng":[54.0,-2.0],"demonym":"British","area":242900.0,"gini":34.0,"timezones":["UTC-08:00","UTC-05:00","UTC-04:00","UTC-03:00","UTC-02:00","UTC","UTC+01:00","UTC+02:00","UTC+06:00"],"borders":["IRL"],"nativeName":"United Kingdom","numericCode":"826","currencies":[{"code":"GBP","name":"British pound","symbol":"£"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Vereinigtes Königreich","es":"Reino Unido","fr":"Royaume-Uni","ja":"イギリス","it":"Regno Unito","br":"Reino Unido","pt":"Reino Unido","nl":"Verenigd Koninkrijk","hr":"Ujedinjeno Kraljevstvo","fa":"بریتانیای کبیر و ایرلند شمالی"},"flag":"https://restcountries.eu/data/gbr.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"GBR"} +{"name":"United States of America","topLevelDomain":[".us"],"alpha2Code":"US","alpha3Code":"USA","callingCodes":["1"],"capital":"Washington, D.C.","altSpellings":["US","USA","United States of America"],"region":"Americas","subregion":"Northern America","population":323947000,"latlng":[38.0,-97.0],"demonym":"American","area":9629091.0,"gini":48.0,"timezones":["UTC-12:00","UTC-11:00","UTC-10:00","UTC-09:00","UTC-08:00","UTC-07:00","UTC-06:00","UTC-05:00","UTC-04:00","UTC+10:00","UTC+12:00"],"borders":["CAN","MEX"],"nativeName":"United States","numericCode":"840","currencies":[{"code":"USD","name":"United States dollar","symbol":"$"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Vereinigte Staaten von Amerika","es":"Estados Unidos","fr":"États-Unis","ja":"アメリカ合衆国","it":"Stati Uniti D'America","br":"Estados Unidos","pt":"Estados Unidos","nl":"Verenigde Staten","hr":"Sjedinjene Američke Države","fa":"ایالات متحده آمریکا"},"flag":"https://restcountries.eu/data/usa.svg","regionalBlocs":[{"acronym":"NAFTA","name":"North American Free Trade Agreement","otherAcronyms":[],"otherNames":["Tratado de Libre Comercio de América del Norte","Accord de Libre-échange Nord-Américain"]}],"cioc":"USA"} +{"name":"Uruguay","topLevelDomain":[".uy"],"alpha2Code":"UY","alpha3Code":"URY","callingCodes":["598"],"capital":"Montevideo","altSpellings":["UY","Oriental Republic of Uruguay","República Oriental del Uruguay"],"region":"Americas","subregion":"South America","population":3480222,"latlng":[-33.0,-56.0],"demonym":"Uruguayan","area":181034.0,"gini":39.7,"timezones":["UTC-03:00"],"borders":["ARG","BRA"],"nativeName":"Uruguay","numericCode":"858","currencies":[{"code":"UYU","name":"Uruguayan peso","symbol":"$"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Uruguay","es":"Uruguay","fr":"Uruguay","ja":"ウルグアイ","it":"Uruguay","br":"Uruguai","pt":"Uruguai","nl":"Uruguay","hr":"Urugvaj","fa":"اروگوئه"},"flag":"https://restcountries.eu/data/ury.svg","regionalBlocs":[{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"URU"} +{"name":"Uzbekistan","topLevelDomain":[".uz"],"alpha2Code":"UZ","alpha3Code":"UZB","callingCodes":["998"],"capital":"Tashkent","altSpellings":["UZ","Republic of Uzbekistan","O‘zbekiston Respublikasi","Ўзбекистон Республикаси"],"region":"Asia","subregion":"Central Asia","population":31576400,"latlng":[41.0,64.0],"demonym":"Uzbekistani","area":447400.0,"gini":36.7,"timezones":["UTC+05:00"],"borders":["AFG","KAZ","KGZ","TJK","TKM"],"nativeName":"O‘zbekiston","numericCode":"860","currencies":[{"code":"UZS","name":"Uzbekistani so'm","symbol":null}],"languages":[{"iso639_1":"uz","iso639_2":"uzb","name":"Uzbek","nativeName":"Oʻzbek"},{"iso639_1":"ru","iso639_2":"rus","name":"Russian","nativeName":"Русский"}],"translations":{"de":"Usbekistan","es":"Uzbekistán","fr":"Ouzbékistan","ja":"ウズベキスタン","it":"Uzbekistan","br":"Uzbequistão","pt":"Usbequistão","nl":"Oezbekistan","hr":"Uzbekistan","fa":"ازبکستان"},"flag":"https://restcountries.eu/data/uzb.svg","regionalBlocs":[],"cioc":"UZB"} +{"name":"Vanuatu","topLevelDomain":[".vu"],"alpha2Code":"VU","alpha3Code":"VUT","callingCodes":["678"],"capital":"Port Vila","altSpellings":["VU","Republic of Vanuatu","Ripablik blong Vanuatu","République de Vanuatu"],"region":"Oceania","subregion":"Melanesia","population":277500,"latlng":[-16.0,167.0],"demonym":"Ni-Vanuatu","area":12189.0,"gini":null,"timezones":["UTC+11:00"],"borders":[],"nativeName":"Vanuatu","numericCode":"548","currencies":[{"code":"VUV","name":"Vanuatu vatu","symbol":"Vt"}],"languages":[{"iso639_1":"bi","iso639_2":"bis","name":"Bislama","nativeName":"Bislama"},{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Vanuatu","es":"Vanuatu","fr":"Vanuatu","ja":"バヌアツ","it":"Vanuatu","br":"Vanuatu","pt":"Vanuatu","nl":"Vanuatu","hr":"Vanuatu","fa":"وانواتو"},"flag":"https://restcountries.eu/data/vut.svg","regionalBlocs":[],"cioc":"VAN"} +{"name":"Venezuela (Bolivarian Republic of)","topLevelDomain":[".ve"],"alpha2Code":"VE","alpha3Code":"VEN","callingCodes":["58"],"capital":"Caracas","altSpellings":["VE","Bolivarian Republic of Venezuela","República Bolivariana de Venezuela"],"region":"Americas","subregion":"South America","population":31028700,"latlng":[8.0,-66.0],"demonym":"Venezuelan","area":916445.0,"gini":44.8,"timezones":["UTC-04:00"],"borders":["BRA","COL","GUY"],"nativeName":"Venezuela","numericCode":"862","currencies":[{"code":"VEF","name":"Venezuelan bolívar","symbol":"Bs F"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Venezuela","es":"Venezuela","fr":"Venezuela","ja":"ベネズエラ・ボリバル共和国","it":"Venezuela","br":"Venezuela","pt":"Venezuela","nl":"Venezuela","hr":"Venezuela","fa":"ونزوئلا"},"flag":"https://restcountries.eu/data/ven.svg","regionalBlocs":[{"acronym":"USAN","name":"Union of South American Nations","otherAcronyms":["UNASUR","UNASUL","UZAN"],"otherNames":["Unión de Naciones Suramericanas","União de Nações Sul-Americanas","Unie van Zuid-Amerikaanse Naties","South American Union"]}],"cioc":"VEN"} +{"name":"Viet Nam","topLevelDomain":[".vn"],"alpha2Code":"VN","alpha3Code":"VNM","callingCodes":["84"],"capital":"Hanoi","altSpellings":["VN","Socialist Republic of Vietnam","Cộng hòa Xã hội chủ nghĩa Việt Nam"],"region":"Asia","subregion":"South-Eastern Asia","population":92700000,"latlng":[16.16666666,107.83333333],"demonym":"Vietnamese","area":331212.0,"gini":35.6,"timezones":["UTC+07:00"],"borders":["KHM","CHN","LAO"],"nativeName":"Việt Nam","numericCode":"704","currencies":[{"code":"VND","name":"Vietnamese đồng","symbol":"₫"}],"languages":[{"iso639_1":"vi","iso639_2":"vie","name":"Vietnamese","nativeName":"Tiếng Việt"}],"translations":{"de":"Vietnam","es":"Vietnam","fr":"Viêt Nam","ja":"ベトナム","it":"Vietnam","br":"Vietnã","pt":"Vietname","nl":"Vietnam","hr":"Vijetnam","fa":"ویتنام"},"flag":"https://restcountries.eu/data/vnm.svg","regionalBlocs":[{"acronym":"ASEAN","name":"Association of Southeast Asian Nations","otherAcronyms":[],"otherNames":[]}],"cioc":"VIE"} +{"name":"Wallis and Futuna","topLevelDomain":[".wf"],"alpha2Code":"WF","alpha3Code":"WLF","callingCodes":["681"],"capital":"Mata-Utu","altSpellings":["WF","Territory of the Wallis and Futuna Islands","Territoire des îles Wallis et Futuna"],"region":"Oceania","subregion":"Polynesia","population":11750,"latlng":[-13.3,-176.2],"demonym":"Wallis and Futuna Islander","area":142.0,"gini":null,"timezones":["UTC+12:00"],"borders":[],"nativeName":"Wallis et Futuna","numericCode":"876","currencies":[{"code":"XPF","name":"CFP franc","symbol":"Fr"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Wallis und Futuna","es":"Wallis y Futuna","fr":"Wallis-et-Futuna","ja":"ウォリス・フツナ","it":"Wallis e Futuna","br":"Wallis e Futuna","pt":"Wallis e Futuna","nl":"Wallis en Futuna","hr":"Wallis i Fortuna","fa":"والیس و فوتونا"},"flag":"https://restcountries.eu/data/wlf.svg","regionalBlocs":[],"cioc":""} +{"name":"Western Sahara","topLevelDomain":[".eh"],"alpha2Code":"EH","alpha3Code":"ESH","callingCodes":["212"],"capital":"El Aaiún","altSpellings":["EH","Taneẓroft Tutrimt"],"region":"Africa","subregion":"Northern Africa","population":510713,"latlng":[24.5,-13.0],"demonym":"Sahrawi","area":266000.0,"gini":null,"timezones":["UTC+00:00"],"borders":["DZA","MRT","MAR"],"nativeName":"الصحراء الغربية","numericCode":"732","currencies":[{"code":"MAD","name":"Moroccan dirham","symbol":"د.م."},{"code":"DZD","name":"Algerian dinar","symbol":"د.ج"}],"languages":[{"iso639_1":"es","iso639_2":"spa","name":"Spanish","nativeName":"Español"}],"translations":{"de":"Westsahara","es":"Sahara Occidental","fr":"Sahara Occidental","ja":"西サハラ","it":"Sahara Occidentale","br":"Saara Ocidental","pt":"Saara Ocidental","nl":"Westelijke Sahara","hr":"Zapadna Sahara","fa":"جمهوری دموکراتیک عربی صحرا"},"flag":"https://restcountries.eu/data/esh.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":""} +{"name":"Yemen","topLevelDomain":[".ye"],"alpha2Code":"YE","alpha3Code":"YEM","callingCodes":["967"],"capital":"Sana'a","altSpellings":["YE","Yemeni Republic","al-Jumhūriyyah al-Yamaniyyah"],"region":"Asia","subregion":"Western Asia","population":27478000,"latlng":[15.0,48.0],"demonym":"Yemeni","area":527968.0,"gini":37.7,"timezones":["UTC+03:00"],"borders":["OMN","SAU"],"nativeName":"اليَمَن","numericCode":"887","currencies":[{"code":"YER","name":"Yemeni rial","symbol":"﷼"}],"languages":[{"iso639_1":"ar","iso639_2":"ara","name":"Arabic","nativeName":"العربية"}],"translations":{"de":"Jemen","es":"Yemen","fr":"Yémen","ja":"イエメン","it":"Yemen","br":"Iêmen","pt":"Iémen","nl":"Jemen","hr":"Jemen","fa":"یمن"},"flag":"https://restcountries.eu/data/yem.svg","regionalBlocs":[{"acronym":"AL","name":"Arab League","otherAcronyms":[],"otherNames":["جامعة الدول العربية","Jāmiʻat ad-Duwal al-ʻArabīyah","League of Arab States"]}],"cioc":"YEM"} +{"name":"Zambia","topLevelDomain":[".zm"],"alpha2Code":"ZM","alpha3Code":"ZMB","callingCodes":["260"],"capital":"Lusaka","altSpellings":["ZM","Republic of Zambia"],"region":"Africa","subregion":"Eastern Africa","population":15933883,"latlng":[-15.0,30.0],"demonym":"Zambian","area":752612.0,"gini":54.6,"timezones":["UTC+02:00"],"borders":["AGO","BWA","COD","MWI","MOZ","NAM","TZA","ZWE"],"nativeName":"Zambia","numericCode":"894","currencies":[{"code":"ZMW","name":"Zambian kwacha","symbol":"ZK"}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"}],"translations":{"de":"Sambia","es":"Zambia","fr":"Zambie","ja":"ザンビア","it":"Zambia","br":"Zâmbia","pt":"Zâmbia","nl":"Zambia","hr":"Zambija","fa":"زامبیا"},"flag":"https://restcountries.eu/data/zmb.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"ZAM"} +{"name":"Zimbabwe","topLevelDomain":[".zw"],"alpha2Code":"ZW","alpha3Code":"ZWE","callingCodes":["263"],"capital":"Harare","altSpellings":["ZW","Republic of Zimbabwe"],"region":"Africa","subregion":"Eastern Africa","population":14240168,"latlng":[-20.0,30.0],"demonym":"Zimbabwean","area":390757.0,"gini":null,"timezones":["UTC+02:00"],"borders":["BWA","MOZ","ZAF","ZMB"],"nativeName":"Zimbabwe","numericCode":"716","currencies":[{"code":"BWP","name":"Botswana pula","symbol":"P"},{"code":"GBP","name":"British pound","symbol":"£"},{"code":"CNY","name":"Chinese yuan","symbol":"¥"},{"code":"EUR","name":"Euro","symbol":"€"},{"code":"INR","name":"Indian rupee","symbol":"₹"},{"code":"JPY","name":"Japanese yen","symbol":"¥"},{"code":"ZAR","name":"South African rand","symbol":"Rs"},{"code":"USD","name":"United States dollar","symbol":"$"},{"code":"(none)","name":null,"symbol":null}],"languages":[{"iso639_1":"en","iso639_2":"eng","name":"English","nativeName":"English"},{"iso639_1":"sn","iso639_2":"sna","name":"Shona","nativeName":"chiShona"},{"iso639_1":"nd","iso639_2":"nde","name":"Northern Ndebele","nativeName":"isiNdebele"}],"translations":{"de":"Simbabwe","es":"Zimbabue","fr":"Zimbabwe","ja":"ジンバブエ","it":"Zimbabwe","br":"Zimbabwe","pt":"Zimbabué","nl":"Zimbabwe","hr":"Zimbabve","fa":"زیمباوه"},"flag":"https://restcountries.eu/data/zwe.svg","regionalBlocs":[{"acronym":"AU","name":"African Union","otherAcronyms":[],"otherNames":["الاتحاد الأفريقي","Union africaine","União Africana","Unión Africana","Umoja wa Afrika"]}],"cioc":"ZIM"} \ No newline at end of file diff --git a/persistence-modules/jnosql/jnosql-diana/pom.xml b/persistence-modules/jnosql/jnosql-diana/pom.xml index 22e066d36d..79c455646c 100644 --- a/persistence-modules/jnosql/jnosql-diana/pom.xml +++ b/persistence-modules/jnosql/jnosql-diana/pom.xml @@ -55,7 +55,7 @@ org.codehaus.mojo exec-maven-plugin - 1.6.0 + ${exec-maven-plugin.version} document diff --git a/persistence-modules/jnosql/pom.xml b/persistence-modules/jnosql/pom.xml index b96722de18..fb7ac72b05 100644 --- a/persistence-modules/jnosql/pom.xml +++ b/persistence-modules/jnosql/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ @@ -22,8 +21,6 @@ - 1.8 - 1.8 0.0.5 diff --git a/persistence-modules/jpa-hibernate-cascade-type/pom.xml b/persistence-modules/jpa-hibernate-cascade-type/pom.xml index a545723746..1fc119592c 100644 --- a/persistence-modules/jpa-hibernate-cascade-type/pom.xml +++ b/persistence-modules/jpa-hibernate-cascade-type/pom.xml @@ -4,13 +4,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jpa-hibernate-cascade-type - 1.0.0-SNAPSHOT - com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ @@ -48,24 +45,12 @@ - - jpa-hibernate-cascade-type - - - src/test/resources - true - - - - 5.4.3.Final 3.12.2 6.0.17.Final 3.0.0 3.0.1-b11 - 1.8 - 1.8 \ No newline at end of file diff --git a/persistence-modules/liquibase/pom.xml b/persistence-modules/liquibase/pom.xml index 39e86b5186..af1af2259e 100644 --- a/persistence-modules/liquibase/pom.xml +++ b/persistence-modules/liquibase/pom.xml @@ -7,9 +7,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/orientdb/pom.xml b/persistence-modules/orientdb/pom.xml index 7b0bef7fc5..5b28fb01b0 100644 --- a/persistence-modules/orientdb/pom.xml +++ b/persistence-modules/orientdb/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/persistence-libraries/pom.xml b/persistence-modules/persistence-libraries/pom.xml index 74ff262637..a72654f2aa 100644 --- a/persistence-modules/persistence-libraries/pom.xml +++ b/persistence-modules/persistence-libraries/pom.xml @@ -10,7 +10,6 @@ com.baeldung persistence-modules 1.0.0-SNAPSHOT - .. @@ -25,30 +24,10 @@ ${hsqldb.version} test - - junit - junit - ${junit.version} - test - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 8 - 8 - - - - - 2.4.0 - 4.12 1.6.0 diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index c0f7c07b70..78da896861 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -10,7 +10,6 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - .. @@ -22,9 +21,12 @@ flyway hbase hibernate5 - hibernate5-2 hibernate-mapping hibernate-ogm + hibernate-annotations + hibernate-jpa + hibernate-queries + hibernate-enterprise influxdb java-cassandra java-cockroachdb @@ -42,7 +44,7 @@ redis solr - spring-boot-jdbi + spring-boot-persistence-2 spring-boot-mysql spring-boot-persistence spring-boot-persistence-h2 @@ -59,6 +61,7 @@ spring-data-jpa-2 spring-data-jpa-3 spring-data-jpa-4 + spring-data-jpa-5 spring-data-keyvalue spring-data-mongodb spring-data-neo4j @@ -70,6 +73,7 @@ spring-jpa spring-persistence-simple + spring-persistence-simple-2 diff --git a/persistence-modules/querydsl/README.md b/persistence-modules/querydsl/README.md index 77b9fd6baf..03e113795d 100644 --- a/persistence-modules/querydsl/README.md +++ b/persistence-modules/querydsl/README.md @@ -1,3 +1,3 @@ ### Relevant Articles: -- [Intro to Querydsl](http://www.baeldung.com/intro-to-querydsl) -- [A Guide to Querydsl with JPA](http://www.baeldung.com/querydsl-with-jpa-tutorial) +- [Intro to Querydsl](https://www.baeldung.com/intro-to-querydsl) +- [A Guide to Querydsl with JPA](https://www.baeldung.com/querydsl-with-jpa-tutorial) diff --git a/persistence-modules/querydsl/pom.xml b/persistence-modules/querydsl/pom.xml index 690e65d737..9f6802ff77 100644 --- a/persistence-modules/querydsl/pom.xml +++ b/persistence-modules/querydsl/pom.xml @@ -6,13 +6,11 @@ 0.1-SNAPSHOT querydsl jar - http://maven.apache.org com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/dao/PersonDao.java b/persistence-modules/querydsl/src/main/java/com/baeldung/dao/PersonDao.java new file mode 100644 index 0000000000..fb39821981 --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/dao/PersonDao.java @@ -0,0 +1,22 @@ +package com.baeldung.dao; + +import java.util.List; +import java.util.Map; + +import com.baeldung.entity.Person; + +public interface PersonDao { + + public Person save(Person person); + + public List findPersonsByFirstnameQueryDSL(String firstname); + + public List findPersonsByFirstnameAndSurnameQueryDSL(String firstname, String surname); + + public List findPersonsByFirstnameInDescendingOrderQueryDSL(String firstname); + + public int findMaxAge(); + + public Map findMaxAgeByName(); + +} \ No newline at end of file diff --git a/persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java b/persistence-modules/querydsl/src/main/java/com/baeldung/dao/PersonDaoImpl.java similarity index 95% rename from persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java rename to persistence-modules/querydsl/src/main/java/com/baeldung/dao/PersonDaoImpl.java index 9acaf1dd18..20ebe0e3fe 100644 --- a/persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/dao/PersonDaoImpl.java @@ -1,17 +1,15 @@ -package org.baeldung.dao; +package com.baeldung.dao; -import java.util.List; -import java.util.Map; +import com.baeldung.entity.Person; +import com.baeldung.entity.QPerson; +import com.querydsl.core.group.GroupBy; +import com.querydsl.jpa.impl.JPAQuery; +import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; - -import org.baeldung.entity.Person; -import org.baeldung.entity.QPerson; -import org.springframework.stereotype.Repository; - -import com.querydsl.core.group.GroupBy; -import com.querydsl.jpa.impl.JPAQuery; +import java.util.List; +import java.util.Map; @Repository public class PersonDaoImpl implements PersonDao { diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/entity/Person.java b/persistence-modules/querydsl/src/main/java/com/baeldung/entity/Person.java new file mode 100644 index 0000000000..310f21ab2a --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/entity/Person.java @@ -0,0 +1,69 @@ +package com.baeldung.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column + private String firstname; + + @Column + private String surname; + + @Column + private int age; + + Person() { + } + + public Person(final String firstname, final String surname) { + this.firstname = firstname; + this.surname = surname; + } + + public Person(final String firstname, final String surname, final int age) { + this(firstname, surname); + this.age = age; + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getFirstname() { + return firstname; + } + + public void setFirstname(final String firstname) { + this.firstname = firstname; + } + + public String getSurname() { + return surname; + } + + public void setSurname(final String surname) { + this.surname = surname; + } + + public int getAge() { + return age; + } + + public void setAge(final int age) { + this.age = age; + } +} \ No newline at end of file diff --git a/persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/BlogPost.java similarity index 95% rename from persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java rename to persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/BlogPost.java index 241bc50b03..6712ad08d5 100644 --- a/persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/BlogPost.java @@ -1,7 +1,7 @@ /* * (c) Центр ИТ, 2016. Все права защищены. */ -package org.baeldung.querydsl.intro.entities; +package com.baeldung.querydsl.intro.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/User.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/User.java new file mode 100644 index 0000000000..4111284d5a --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/User.java @@ -0,0 +1,55 @@ +/* + * (c) Центр ИТ, 2016. Все права защищены. + */ +package com.baeldung.querydsl.intro.entities; + +import java.util.HashSet; +import java.util.Set; +import javax.persistence.*; + +@Entity +public class User { + + @Id + @GeneratedValue + private Long id; + + private String login; + + private Boolean disabled; + + @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "user") + private Set blogPosts = new HashSet<>(0); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String name) { + this.login = name; + } + + public Set getBlogPosts() { + return blogPosts; + } + + public void setBlogPosts(Set blogPosts) { + this.blogPosts = blogPosts; + } + + public Boolean getDisabled() { + return disabled; + } + + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } +} diff --git a/persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDao.java b/persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDao.java deleted file mode 100644 index 7df4ebb22d..0000000000 --- a/persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDao.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.dao; - -import java.util.List; -import java.util.Map; - -import org.baeldung.entity.Person; - -public interface PersonDao { - - public Person save(Person person); - - public List findPersonsByFirstnameQueryDSL(String firstname); - - public List findPersonsByFirstnameAndSurnameQueryDSL(String firstname, String surname); - - public List findPersonsByFirstnameInDescendingOrderQueryDSL(String firstname); - - public int findMaxAge(); - - public Map findMaxAgeByName(); - -} \ No newline at end of file diff --git a/persistence-modules/querydsl/src/main/java/org/baeldung/entity/Person.java b/persistence-modules/querydsl/src/main/java/org/baeldung/entity/Person.java deleted file mode 100644 index 6f04210d90..0000000000 --- a/persistence-modules/querydsl/src/main/java/org/baeldung/entity/Person.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.baeldung.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Person { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Column - private String firstname; - - @Column - private String surname; - - @Column - private int age; - - Person() { - } - - public Person(final String firstname, final String surname) { - this.firstname = firstname; - this.surname = surname; - } - - public Person(final String firstname, final String surname, final int age) { - this(firstname, surname); - this.age = age; - } - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getFirstname() { - return firstname; - } - - public void setFirstname(final String firstname) { - this.firstname = firstname; - } - - public String getSurname() { - return surname; - } - - public void setSurname(final String surname) { - this.surname = surname; - } - - public int getAge() { - return age; - } - - public void setAge(final int age) { - this.age = age; - } -} \ No newline at end of file diff --git a/persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java b/persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java deleted file mode 100644 index c0681e15d1..0000000000 --- a/persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * (c) Центр ИТ, 2016. Все права защищены. - */ -package org.baeldung.querydsl.intro.entities; - -import java.util.HashSet; -import java.util.Set; -import javax.persistence.*; - -@Entity -public class User { - - @Id - @GeneratedValue - private Long id; - - private String login; - - private Boolean disabled; - - @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "user") - private Set blogPosts = new HashSet<>(0); - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getLogin() { - return login; - } - - public void setLogin(String name) { - this.login = name; - } - - public Set getBlogPosts() { - return blogPosts; - } - - public void setBlogPosts(Set blogPosts) { - this.blogPosts = blogPosts; - } - - public Boolean getDisabled() { - return disabled; - } - - public void setDisabled(Boolean disabled) { - this.disabled = disabled; - } -} diff --git a/persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml b/persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml index 2964382d48..4b51cb444b 100644 --- a/persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml @@ -17,7 +17,7 @@ - + org.hibernate.jpa.HibernatePersistenceProvider diff --git a/persistence-modules/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java b/persistence-modules/querydsl/src/test/java/com/baeldung/dao/PersonDaoIntegrationTest.java similarity index 97% rename from persistence-modules/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java rename to persistence-modules/querydsl/src/test/java/com/baeldung/dao/PersonDaoIntegrationTest.java index a666aea8da..cf4e9ab872 100644 --- a/persistence-modules/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java +++ b/persistence-modules/querydsl/src/test/java/com/baeldung/dao/PersonDaoIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.dao; +package com.baeldung.dao; import java.util.Map; -import org.baeldung.entity.Person; +import com.baeldung.entity.Person; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/persistence-modules/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLIntegrationTest.java b/persistence-modules/querydsl/src/test/java/com/baeldung/querydsl/intro/QueryDSLIntegrationTest.java similarity index 94% rename from persistence-modules/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLIntegrationTest.java rename to persistence-modules/querydsl/src/test/java/com/baeldung/querydsl/intro/QueryDSLIntegrationTest.java index 15a32b8df5..7ae97c2880 100644 --- a/persistence-modules/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLIntegrationTest.java +++ b/persistence-modules/querydsl/src/test/java/com/baeldung/querydsl/intro/QueryDSLIntegrationTest.java @@ -1,17 +1,17 @@ /* * (c) Центр ИТ, 2016. Все права защищены. */ -package org.baeldung.querydsl.intro; +package com.baeldung.querydsl.intro; +import com.baeldung.querydsl.intro.entities.BlogPost; +import com.baeldung.querydsl.intro.entities.QBlogPost; +import com.baeldung.querydsl.intro.entities.QUser; +import com.baeldung.querydsl.intro.entities.User; import com.querydsl.core.Tuple; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.NumberPath; import com.querydsl.jpa.JPAExpressions; import com.querydsl.jpa.impl.JPAQueryFactory; -import org.baeldung.querydsl.intro.entities.BlogPost; -import org.baeldung.querydsl.intro.entities.QBlogPost; -import org.baeldung.querydsl.intro.entities.QUser; -import org.baeldung.querydsl.intro.entities.User; import org.junit.*; import javax.persistence.EntityManager; @@ -31,7 +31,7 @@ public class QueryDSLIntegrationTest { @BeforeClass public static void populateDatabase() { - emf = Persistence.createEntityManagerFactory("org.baeldung.querydsl.intro"); + emf = Persistence.createEntityManagerFactory("com.baeldung.querydsl.intro"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); diff --git a/persistence-modules/querydsl/src/test/resources/test-context.xml b/persistence-modules/querydsl/src/test/resources/test-context.xml index 13d823a857..1503364320 100644 --- a/persistence-modules/querydsl/src/test/resources/test-context.xml +++ b/persistence-modules/querydsl/src/test/resources/test-context.xml @@ -13,7 +13,7 @@ > - + diff --git a/persistence-modules/r2dbc/pom.xml b/persistence-modules/r2dbc/pom.xml index 3b2a57401c..70ff8d6a87 100644 --- a/persistence-modules/r2dbc/pom.xml +++ b/persistence-modules/r2dbc/pom.xml @@ -3,10 +3,10 @@ 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 - org.baeldung.examples.r2dbc + com.baeldung.examples.r2dbc r2dbc-example 0.0.1-SNAPSHOT - r2dbc-example + r2dbc Sample R2DBC Project @@ -61,32 +61,10 @@ - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - 1.8 - 0.8.0.M8 + 0.8.1.RELEASE + 1.4.200 diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/Account.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/Account.java new file mode 100644 index 0000000000..0310cd94b6 --- /dev/null +++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/Account.java @@ -0,0 +1,68 @@ +package com.baeldung.examples.r2dbc; + +import java.math.BigDecimal; + +public class Account { + + private Long id; + private String iban; + private BigDecimal balance; + + + public Account() {} + + public Account(Long id, String iban, BigDecimal balance) { + this.id = id; + this.iban = iban; + this.balance = balance; + } + + public Account(Long id, String iban, Double balance) { + this.id = id; + this.iban = iban; + this.balance = new BigDecimal(balance); + } + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the iban + */ + public String getIban() { + return iban; + } + + /** + * @param iban the iban to set + */ + public void setIban(String iban) { + this.iban = iban; + } + + /** + * @return the balance + */ + public BigDecimal getBalance() { + return balance; + } + + /** + * @param balance the balance to set + */ + public void setBalance(BigDecimal balance) { + this.balance = balance; + } + +} diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/AccountResource.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/AccountResource.java new file mode 100644 index 0000000000..5b0d0cded3 --- /dev/null +++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/AccountResource.java @@ -0,0 +1,50 @@ +/** + * + */ +package com.baeldung.examples.r2dbc; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +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.RestController; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * @author Philippe + * + */ +@RestController +public class AccountResource { + + private final ReactiveAccountDao accountDao; + + public AccountResource(ReactiveAccountDao accountDao) { + this.accountDao = accountDao; + } + + @GetMapping("/accounts/{id}") + public Mono> getAccount(@PathVariable("id") Long id) { + + return accountDao.findById(id) + .map(acc -> new ResponseEntity<>(acc, HttpStatus.OK)) + .switchIfEmpty(Mono.just(new ResponseEntity<>(null, HttpStatus.NOT_FOUND))); + } + + @GetMapping("/accounts") + public Flux getAllAccounts() { + return accountDao.findAll(); + } + + @PostMapping("/accounts") + public Mono> postAccount(@RequestBody Account account) { + return accountDao.createAccount(account) + .map(acc -> new ResponseEntity<>(acc, HttpStatus.CREATED)) + .log(); + } + +} diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/DatasourceConfig.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/DatasourceConfig.java new file mode 100644 index 0000000000..21cc0bc6d3 --- /dev/null +++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/DatasourceConfig.java @@ -0,0 +1,63 @@ +package com.baeldung.examples.r2dbc; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import io.netty.util.internal.StringUtil; +import io.r2dbc.spi.ConnectionFactories; +import io.r2dbc.spi.ConnectionFactory; +import io.r2dbc.spi.ConnectionFactoryOptions; +import io.r2dbc.spi.ConnectionFactoryOptions.Builder; +import reactor.core.publisher.Flux; + +import static io.r2dbc.spi.ConnectionFactoryOptions.*; + + +@Configuration +public class DatasourceConfig { + + @Bean + public ConnectionFactory connectionFactory(R2DBCConfigurationProperties properties) { + + ConnectionFactoryOptions baseOptions = ConnectionFactoryOptions.parse(properties.getUrl()); + Builder ob = ConnectionFactoryOptions.builder().from(baseOptions); + if ( !StringUtil.isNullOrEmpty(properties.getUser())) { + ob = ob.option(USER, properties.getUser()); + } + + if ( !StringUtil.isNullOrEmpty(properties.getPassword())) { + ob = ob.option(PASSWORD, properties.getPassword()); + } + + ConnectionFactory cf = ConnectionFactories.get(ob.build()); + return cf; + } + + + @Bean + public CommandLineRunner initDatabase(ConnectionFactory cf) { + + return (args) -> + Flux.from(cf.create()) + .flatMap(c -> + Flux.from(c.createBatch() + .add("drop table if exists Account") + .add("create table Account(" + + "id IDENTITY(1,1)," + + "iban varchar(80) not null," + + "balance DECIMAL(18,2) not null)") + .add("insert into Account(iban,balance)" + + "values('BR430120980198201982',100.00)") + .add("insert into Account(iban,balance)" + + "values('BR430120998729871000',250.00)") + .execute()) + .doFinally((st) -> c.close()) + ) + .log() + .blockLast(); + } + + +} + diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2DBCConfigurationProperties.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/R2DBCConfigurationProperties.java similarity index 96% rename from persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2DBCConfigurationProperties.java rename to persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/R2DBCConfigurationProperties.java index 02733ebed9..b40c7ec2cd 100644 --- a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2DBCConfigurationProperties.java +++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/R2DBCConfigurationProperties.java @@ -1,4 +1,4 @@ -package org.baeldung.examples.r2dbc; +package com.baeldung.examples.r2dbc; import javax.validation.constraints.NotEmpty; diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2dbcExampleApplication.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/R2dbcExampleApplication.java similarity index 92% rename from persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2dbcExampleApplication.java rename to persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/R2dbcExampleApplication.java index 1147936e2d..11670a4154 100644 --- a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2dbcExampleApplication.java +++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/R2dbcExampleApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.examples.r2dbc; +package com.baeldung.examples.r2dbc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/ReactiveAccountDao.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/ReactiveAccountDao.java similarity index 95% rename from persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/ReactiveAccountDao.java rename to persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/ReactiveAccountDao.java index f9717d4b9b..6a7974aeb1 100644 --- a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/ReactiveAccountDao.java +++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/ReactiveAccountDao.java @@ -1,9 +1,7 @@ -package org.baeldung.examples.r2dbc; +package com.baeldung.examples.r2dbc; import java.math.BigDecimal; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import io.r2dbc.spi.Connection; diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/Account.java b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/Account.java deleted file mode 100644 index 65bf33168e..0000000000 --- a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/Account.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.baeldung.examples.r2dbc; - -import java.math.BigDecimal; - -public class Account { - - private Long id; - private String iban; - private BigDecimal balance; - - - public Account() {} - - public Account(Long id, String iban, BigDecimal balance) { - this.id = id; - this.iban = iban; - this.balance = balance; - } - - public Account(Long id, String iban, Double balance) { - this.id = id; - this.iban = iban; - this.balance = new BigDecimal(balance); - } - - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the iban - */ - public String getIban() { - return iban; - } - - /** - * @param iban the iban to set - */ - public void setIban(String iban) { - this.iban = iban; - } - - /** - * @return the balance - */ - public BigDecimal getBalance() { - return balance; - } - - /** - * @param balance the balance to set - */ - public void setBalance(BigDecimal balance) { - this.balance = balance; - } - -} diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/AccountResource.java b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/AccountResource.java deleted file mode 100644 index 90816a7522..0000000000 --- a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/AccountResource.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * - */ -package org.baeldung.examples.r2dbc; - -import java.math.BigDecimal; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.RestController; - -import io.r2dbc.spi.Connection; -import io.r2dbc.spi.ConnectionFactory; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * @author Philippe - * - */ -@RestController -public class AccountResource { - - private final ReactiveAccountDao accountDao; - - public AccountResource(ReactiveAccountDao accountDao) { - this.accountDao = accountDao; - } - - @GetMapping("/accounts/{id}") - public Mono> getAccount(@PathVariable("id") Long id) { - - return accountDao.findById(id) - .map(acc -> new ResponseEntity<>(acc, HttpStatus.OK)) - .switchIfEmpty(Mono.just(new ResponseEntity<>(null, HttpStatus.NOT_FOUND))); - } - - @GetMapping("/accounts") - public Flux getAllAccounts() { - return accountDao.findAll(); - } - - @PostMapping("/accounts") - public Mono> postAccount(@RequestBody Account account) { - return accountDao.createAccount(account) - .map(acc -> new ResponseEntity<>(acc, HttpStatus.CREATED)) - .log(); - } - -} diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/DatasourceConfig.java b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/DatasourceConfig.java deleted file mode 100644 index 5b695f39f5..0000000000 --- a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/DatasourceConfig.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.baeldung.examples.r2dbc; - -import org.springframework.boot.CommandLineRunner; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; - -import io.netty.util.internal.StringUtil; -import io.r2dbc.spi.ConnectionFactories; -import io.r2dbc.spi.ConnectionFactory; -import io.r2dbc.spi.ConnectionFactoryOptions; -import io.r2dbc.spi.ConnectionFactoryOptions.Builder; -import io.r2dbc.spi.Option; -import reactor.core.publisher.Flux; - -import static io.r2dbc.spi.ConnectionFactoryOptions.*; - - -@Configuration -public class DatasourceConfig { - - @Bean - public ConnectionFactory connectionFactory(R2DBCConfigurationProperties properties) { - - ConnectionFactoryOptions baseOptions = ConnectionFactoryOptions.parse(properties.getUrl()); - Builder ob = ConnectionFactoryOptions.builder().from(baseOptions); - if ( !StringUtil.isNullOrEmpty(properties.getUser())) { - ob = ob.option(USER, properties.getUser()); - } - - if ( !StringUtil.isNullOrEmpty(properties.getPassword())) { - ob = ob.option(PASSWORD, properties.getPassword()); - } - - ConnectionFactory cf = ConnectionFactories.get(ob.build()); - return cf; - } - - - @Bean - public CommandLineRunner initDatabase(ConnectionFactory cf) { - - return (args) -> - Flux.from(cf.create()) - .flatMap(c -> - Flux.from(c.createBatch() - .add("drop table if exists Account") - .add("create table Account(" + - "id IDENTITY(1,1)," + - "iban varchar(80) not null," + - "balance DECIMAL(18,2) not null)") - .add("insert into Account(iban,balance)" + - "values('BR430120980198201982',100.00)") - .add("insert into Account(iban,balance)" + - "values('BR430120998729871000',250.00)") - .execute()) - .doFinally((st) -> c.close()) - ) - .log() - .blockLast(); - } - - -} - diff --git a/persistence-modules/r2dbc/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/persistence-modules/r2dbc/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 55eb5659a7..79d401392c 100644 --- a/persistence-modules/r2dbc/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/persistence-modules/r2dbc/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -1,5 +1,5 @@ {"properties": [{ "name": "r2dbc", - "type": "org.baeldung.examples.r2dbc.R2DBCConfigurationProperties", + "type": "com.baeldung.examples.r2dbc.R2DBCConfigurationProperties", "description": "R2DBC Connection properties" }]} \ No newline at end of file diff --git a/persistence-modules/r2dbc/src/test/java/org/baeldung/examples/r2dbc/R2dbcExampleApplicationTests.java b/persistence-modules/r2dbc/src/test/java/com/baeldung/examples/r2dbc/R2dbcExampleApplicationTests.java similarity index 92% rename from persistence-modules/r2dbc/src/test/java/org/baeldung/examples/r2dbc/R2dbcExampleApplicationTests.java rename to persistence-modules/r2dbc/src/test/java/com/baeldung/examples/r2dbc/R2dbcExampleApplicationTests.java index a1d433847b..3fb9e24a8e 100644 --- a/persistence-modules/r2dbc/src/test/java/org/baeldung/examples/r2dbc/R2dbcExampleApplicationTests.java +++ b/persistence-modules/r2dbc/src/test/java/com/baeldung/examples/r2dbc/R2dbcExampleApplicationTests.java @@ -1,19 +1,15 @@ -package org.baeldung.examples.r2dbc; +package com.baeldung.examples.r2dbc; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.util.List; -import org.hamcrest.core.IsNull; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; diff --git a/persistence-modules/redis/README.md b/persistence-modules/redis/README.md index 21cd048693..668b8d33f8 100644 --- a/persistence-modules/redis/README.md +++ b/persistence-modules/redis/README.md @@ -2,3 +2,4 @@ - [Intro to Jedis – the Java Redis Client Library](http://www.baeldung.com/jedis-java-redis-client-library) - [A Guide to Redis with Redisson](http://www.baeldung.com/redis-redisson) - [Introduction to Lettuce – the Java Redis Client](https://www.baeldung.com/java-redis-lettuce) +- [List All Available Redis Keys](https://www.baeldung.com/redis-list-available-keys) diff --git a/persistence-modules/redis/pom.xml b/persistence-modules/redis/pom.xml index c4a928bb4a..c9206e5f92 100644 --- a/persistence-modules/redis/pom.xml +++ b/persistence-modules/redis/pom.xml @@ -9,17 +9,31 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-redis + + redis.clients jedis - ${jedis.version} - + com.github.kstyrc embedded-redis @@ -33,15 +47,12 @@ io.lettuce lettuce-core - ${lettuce-core.version} - + - - 2.9.0 + 0.6 - 3.3.0 - 5.0.1.RELEASE + 3.3.0 diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/client/RedisClient.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/client/RedisClient.java new file mode 100644 index 0000000000..72ff42ff74 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/client/RedisClient.java @@ -0,0 +1,154 @@ +package com.baeldung.redis_scan.client; + +import com.baeldung.redis_scan.iterator.RedisIterator; +import com.baeldung.redis_scan.strategy.ScanStrategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; + +public class RedisClient { + private static Logger log = LoggerFactory.getLogger(RedisClient.class); + + private static volatile RedisClient instance = null; + + private static JedisPool jedisPool; + + public static RedisClient getInstance(String ip, final int port) { + if (instance == null) { + synchronized (RedisClient.class) { + if (instance == null) { + instance = new RedisClient(ip, port); + } + } + } + return instance; + } + + private RedisClient(String ip, int port) { + try { + if (jedisPool == null) { + jedisPool = new JedisPool(new URI("http://" + ip + ":" + port)); + } + } catch (URISyntaxException e) { + log.error("Malformed server address", e); + } + } + + public Long lpush(final String key, final String[] strings) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.lpush(key, strings); + } catch (Exception ex) { + log.error("Exception caught in lpush", ex); + } + return null; + } + + public List lrange(final String key, final long start, final long stop) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.lrange(key, start, stop); + } catch (Exception ex) { + log.error("Exception caught in lrange", ex); + } + return new LinkedList(); + } + + public String hmset(final String key, final Map hash) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.hmset(key, hash); + } catch (Exception ex) { + log.error("Exception caught in hmset", ex); + } + return null; + } + + public Map hgetAll(final String key) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.hgetAll(key); + } catch (Exception ex) { + log.error("Exception caught in hgetAll", ex); + } + return new HashMap(); + } + + public Long sadd(final String key, final String... members) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.sadd(key, members); + } catch (Exception ex) { + log.error("Exception caught in sadd", ex); + } + return null; + } + + public Set smembers(final String key) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.smembers(key); + } catch (Exception ex) { + log.error("Exception caught in smembers", ex); + } + return new HashSet(); + } + + public Long zadd(final String key, final Map scoreMembers) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.zadd(key, scoreMembers); + } catch (Exception ex) { + log.error("Exception caught in zadd", ex); + } + return 0L; + } + + public Set zrange(final String key, final long start, final long stop) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.zrange(key, start, stop); + } catch (Exception ex) { + log.error("Exception caught in zrange", ex); + } + return new HashSet(); + } + + public String mset(final HashMap keysValues) { + try (Jedis jedis = jedisPool.getResource()) { + ArrayList keysValuesArrayList = new ArrayList(); + keysValues.forEach((key, value) -> { + keysValuesArrayList.add(key); + keysValuesArrayList.add(value); + }); + return jedis.mset((keysValuesArrayList.toArray(new String[keysValues.size()]))); + } catch (Exception ex) { + log.error("Exception caught in mset", ex); + } + return null; + } + + public Set keys(final String pattern) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.keys(pattern); + } catch (Exception ex) { + log.error("Exception caught in keys", ex); + } + return new HashSet(); + } + + public RedisIterator iterator(int initialScanCount, String pattern, ScanStrategy strategy) { + return new RedisIterator(jedisPool, initialScanCount, pattern, strategy); + } + + public void flushAll() { + try (Jedis jedis = jedisPool.getResource()) { + jedis.flushAll(); + } catch (Exception ex) { + log.error("Exception caught in flushAll", ex); + } + } + + public void destroyInstance() { + jedisPool = null; + instance = null; + } + +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/iterator/RedisIterator.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/iterator/RedisIterator.java new file mode 100644 index 0000000000..5fbd798ac2 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/iterator/RedisIterator.java @@ -0,0 +1,60 @@ +package com.baeldung.redis_scan.iterator; + +import com.baeldung.redis_scan.strategy.ScanStrategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +public class RedisIterator implements Iterator> { + + private static Logger log = LoggerFactory.getLogger(RedisIterator.class); + private static final int DEFAULT_SCAN_COUNT = 10; + + private final JedisPool jedisPool; + private ScanParams scanParams; + private String cursor; + private ScanStrategy strategy; + + public RedisIterator(JedisPool jedisPool, int initialScanCount, String pattern, ScanStrategy strategy) { + super(); + this.jedisPool = jedisPool; + this.scanParams = new ScanParams().match(pattern).count(initialScanCount); + this.strategy = strategy; + } + + public RedisIterator(JedisPool jedisPool, String pattern, ScanStrategy strategy) { + super(); + this.jedisPool = jedisPool; + this.scanParams = new ScanParams().match(pattern).count(DEFAULT_SCAN_COUNT); + this.strategy = strategy; + } + + @Override + public boolean hasNext() { + return !"0".equals(cursor); + } + + @Override + public List next() { + if (cursor == null) { + cursor = "0"; + } + try (Jedis jedis = jedisPool.getResource()) { + ScanResult scanResult = strategy.scan(jedis, cursor, scanParams); + cursor = scanResult.getCursor(); + return scanResult.getResult(); + + } catch (Exception ex) { + log.error("Exception caught in next()", ex); + } + return new LinkedList(); + } + +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/ScanStrategy.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/ScanStrategy.java new file mode 100644 index 0000000000..39d9e44a63 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/ScanStrategy.java @@ -0,0 +1,9 @@ +package com.baeldung.redis_scan.strategy; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + +public interface ScanStrategy { + ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams); +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Hscan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Hscan.java new file mode 100644 index 0000000000..fd5ecd14ec --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Hscan.java @@ -0,0 +1,25 @@ +package com.baeldung.redis_scan.strategy.impl; + +import com.baeldung.redis_scan.strategy.ScanStrategy; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + +import java.util.Map; +import java.util.Map.Entry; + +public class Hscan implements ScanStrategy> { + + private String key; + + public Hscan(String key) { + super(); + this.key = key; + } + + @Override + public ScanResult> scan(Jedis jedis, String cursor, ScanParams scanParams) { + return jedis.hscan(key, cursor, scanParams); + } + +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Scan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Scan.java new file mode 100644 index 0000000000..f28b56e34c --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Scan.java @@ -0,0 +1,14 @@ +package com.baeldung.redis_scan.strategy.impl; + +import com.baeldung.redis_scan.strategy.ScanStrategy; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + +public class Scan implements ScanStrategy { + + + public ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams) { + return jedis.scan(cursor, scanParams); + } +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Sscan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Sscan.java new file mode 100644 index 0000000000..ed47f7087e --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Sscan.java @@ -0,0 +1,29 @@ +package com.baeldung.redis_scan.strategy.impl; + +import com.baeldung.redis_scan.strategy.ScanStrategy; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + +public class Sscan implements ScanStrategy { + + private String key; + + + public Sscan(String key) { + super(); + this.key = key; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams) { + return jedis.sscan(key, cursor, scanParams); + } +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Zscan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Zscan.java new file mode 100644 index 0000000000..bdffc15883 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Zscan.java @@ -0,0 +1,25 @@ +package com.baeldung.redis_scan.strategy.impl; + +import com.baeldung.redis_scan.strategy.ScanStrategy; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; +import redis.clients.jedis.Tuple; + +public class Zscan implements ScanStrategy { + + private String key; + + + public Zscan(String key) { + super(); + this.key = key; + } + + + @Override + public ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams) { + return jedis.zscan(key, cursor, scanParams); + } + +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/RedisConfig.java b/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/RedisConfig.java new file mode 100644 index 0000000000..ad43ad8159 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/RedisConfig.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.redis.configuration; + +import org.springframework.boot.autoconfigure.data.redis.RedisProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; + +import com.baeldung.spring.redis.configuration.entity.Book; + +@Configuration +@EnableConfigurationProperties(RedisProperties.class) +public class RedisConfig { + + @Bean + public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(connectionFactory); + // Add some specific configuration here. Key serializers, etc. + return template; + } + +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/SpringRedisConfigurationApplication.java b/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/SpringRedisConfigurationApplication.java new file mode 100644 index 0000000000..932a6b7478 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/SpringRedisConfigurationApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.redis.configuration; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringRedisConfigurationApplication implements CommandLineRunner { + + public static void main(String[] args) { + SpringApplication.run(SpringRedisConfigurationApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + + } + +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/controller/BooksController.java b/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/controller/BooksController.java new file mode 100644 index 0000000000..b3faf030c9 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/controller/BooksController.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.redis.configuration.controller; + +import org.springframework.beans.factory.annotation.Autowired; +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 com.baeldung.spring.redis.configuration.entity.Book; +import com.baeldung.spring.redis.configuration.repository.BooksRepository; + +@RestController +@RequestMapping("/books") +public class BooksController { + + @Autowired + private BooksRepository repository; + + @PostMapping("/create") + public String newBook(@RequestBody Book newBook) { + repository.save(newBook); + return "Added"; + } + + @GetMapping("/get/{id}") + public Book findOne(@PathVariable Long id) { + return repository.findById(id); + } + +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/entity/Book.java b/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/entity/Book.java new file mode 100644 index 0000000000..52d579d4fb --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/entity/Book.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.redis.configuration.entity; + +import java.io.Serializable; + +public class Book implements Serializable { + + private static final long serialVersionUID = 1L; + + private Long id; + + private String name; + + public Book() { + } + + public Book(String name) { + this.name = name; + } + + public Book(Long id, String name) { + 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; + } + + @Override + public String toString() { + return "Book [id=" + id + ", name=" + name + "]"; + } + +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/repository/BooksRepository.java b/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/repository/BooksRepository.java new file mode 100644 index 0000000000..a6eba0e742 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/spring/redis/configuration/repository/BooksRepository.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.redis.configuration.repository; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import com.baeldung.spring.redis.configuration.entity.Book; + +@Component +public class BooksRepository { + + @Autowired + private RedisTemplate redisTemplate; + + public void save(Book book) { + redisTemplate.opsForValue() + .set(book.getId(), book); + } + + public Book findById(Long id) { + return redisTemplate.opsForValue() + .get(id); + } + +} diff --git a/persistence-modules/redis/src/main/resources/application.properties b/persistence-modules/redis/src/main/resources/application.properties new file mode 100644 index 0000000000..e3140c4e29 --- /dev/null +++ b/persistence-modules/redis/src/main/resources/application.properties @@ -0,0 +1,9 @@ +spring.redis.database=0 +spring.redis.host=localhost +spring.redis.port=16379 +spring.redis.password=mypass +spring.redis.timeout=60000 +spring.redis.lettuce.pool.max-active=8 +spring.redis.lettuce.pool.max-idle=8 +spring.redis.lettuce.pool.max-wait=-1 +spring.redis.lettuce.pool.min-idle=0 \ No newline at end of file diff --git a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java new file mode 100644 index 0000000000..9bf0b2b086 --- /dev/null +++ b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java @@ -0,0 +1,97 @@ +package com.baeldung.redis_scan; + +import com.baeldung.redis_scan.client.RedisClient; +import org.junit.*; +import redis.embedded.RedisServer; + +import java.io.IOException; +import java.net.ServerSocket; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class NaiveApproachIntegrationTest { + private static RedisServer redisServer; + private static int port; + private static RedisClient redisClient; + + @BeforeClass + public static void setUp() throws IOException { + + // Take an available port + ServerSocket s = new ServerSocket(0); + port = s.getLocalPort(); + s.close(); + + redisServer = new RedisServer(port); + } + + @AfterClass + public static void destroy() { + if (redisServer.isActive()) { + redisServer.stop(); + redisClient.destroyInstance(); + } + } + + @Before + public void init() { + if (!redisServer.isActive()) { + redisServer.start(); + } + redisClient = RedisClient.getInstance("127.0.0.1", port); + } + + @After + public void flushAll() { + redisClient.flushAll(); + } + + @Test + public void testKeys() { + HashMap keyValues = new HashMap(); + keyValues.put("balls:cricket", "160"); + keyValues.put("balls:football", "450"); + keyValues.put("balls:volleyball", "270"); + redisClient.mset(keyValues); + Set readKeys = redisClient.keys("ball*"); + Assert.assertEquals(keyValues.size(), readKeys.size()); + + } + + @Test + public void testSmembers() { + HashSet setMembers = new HashSet(); + setMembers.add("cricket_160"); + setMembers.add("football_450"); + setMembers.add("volleyball_270"); + redisClient.sadd("balls", setMembers.toArray(new String[setMembers.size()])); + Set readSetMembers = redisClient.smembers("balls"); + Assert.assertEquals(setMembers.size(), readSetMembers.size()); + } + + @Test + public void testHgetAll() { + HashMap keyValues = new HashMap(); + keyValues.put("balls:cricket", "160"); + keyValues.put("balls:football", "450"); + keyValues.put("balls:volleyball", "270"); + redisClient.hmset("balls", keyValues); + Map readHash = redisClient.hgetAll("balls"); + Assert.assertEquals(keyValues.size(), readHash.size()); + } + + @Test + public void testZRange() { + HashMap scoreMembers = new HashMap(); + scoreMembers.put("cricket", (double) 160); + scoreMembers.put("football", (double) 450); + scoreMembers.put("volleyball", (double) 270); + redisClient.zadd("balls", scoreMembers); + Set readSetMembers = redisClient.zrange("balls", 0, -1); + + Assert.assertEquals(readSetMembers.size(), scoreMembers.size()); + } + +} diff --git a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java new file mode 100644 index 0000000000..9bde969b58 --- /dev/null +++ b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java @@ -0,0 +1,130 @@ +package com.baeldung.redis_scan; + +import com.baeldung.redis_scan.client.RedisClient; +import com.baeldung.redis_scan.iterator.RedisIterator; +import com.baeldung.redis_scan.strategy.ScanStrategy; +import com.baeldung.redis_scan.strategy.impl.Hscan; +import com.baeldung.redis_scan.strategy.impl.Scan; +import com.baeldung.redis_scan.strategy.impl.Sscan; +import com.baeldung.redis_scan.strategy.impl.Zscan; +import org.junit.*; +import redis.clients.jedis.Tuple; +import redis.embedded.RedisServer; + +import java.io.IOException; +import java.net.ServerSocket; +import java.util.*; + + +public class ScanStrategyIntegrationTest { + + private static RedisServer redisServer; + private static int port; + private static RedisClient redisClient; + + @BeforeClass + public static void setUp() throws IOException { + + // Take an available port + ServerSocket s = new ServerSocket(0); + String ip = "127.0.0.1"; + port = s.getLocalPort(); + s.close(); + + redisServer = new RedisServer(port); + } + + @AfterClass + public static void destroy() { + if (redisServer.isActive()) { + redisServer.stop(); + redisClient.destroyInstance(); + } + } + + @Before + public void init() { + if (!redisServer.isActive()) { + redisServer.start(); + } + redisClient = RedisClient.getInstance("127.0.0.1", port); + } + + @After + public void flushAll() { + redisClient.flushAll(); + } + + @Test + public void testScanStrategy() { + HashMap keyValues = new HashMap(); + keyValues.put("balls:cricket", "160"); + keyValues.put("balls:football", "450"); + keyValues.put("balls:volleyball", "270"); + redisClient.mset(keyValues); + + ScanStrategy scanStrategy = new Scan(); + int iterationCount = 2; + RedisIterator iterator = redisClient.iterator(iterationCount, "ball*", scanStrategy); + List results = new LinkedList(); + while (iterator.hasNext()) { + results.addAll(iterator.next()); + } + Assert.assertEquals(keyValues.size(), results.size()); + } + + @Test + public void testSscanStrategy() { + HashSet setMembers = new HashSet(); + setMembers.add("cricket_160"); + setMembers.add("football_450"); + setMembers.add("volleyball_270"); + redisClient.sadd("balls", setMembers.toArray(new String[setMembers.size()])); + + Sscan scanStrategy = new Sscan("balls"); + int iterationCount = 2; + RedisIterator iterator = redisClient.iterator(iterationCount, "*", scanStrategy); + List results = new LinkedList(); + while (iterator.hasNext()) { + results.addAll(iterator.next()); + } + Assert.assertEquals(setMembers.size(), results.size()); + } + + @Test + public void testHscanStrategy() { + HashMap hash = new HashMap(); + hash.put("cricket", "160"); + hash.put("football", "450"); + hash.put("volleyball", "270"); + redisClient.hmset("balls", hash); + + Hscan scanStrategy = new Hscan("balls"); + int iterationCount = 2; + RedisIterator iterator = redisClient.iterator(iterationCount, "*", scanStrategy); + List> results = new LinkedList>(); + while (iterator.hasNext()) { + results.addAll(iterator.next()); + } + Assert.assertEquals(hash.size(), results.size()); + } + + @Test + public void testZscanStrategy() { + HashMap memberScores = new HashMap(); + memberScores.put("cricket", (double) 160); + memberScores.put("football", (double) 450); + memberScores.put("volleyball", (double) 270); + redisClient.zadd("balls", memberScores); + + Zscan scanStrategy = new Zscan("balls"); + int iterationCount = 2; + RedisIterator iterator = redisClient.iterator(iterationCount, "*", scanStrategy); + List results = new LinkedList(); + while (iterator.hasNext()) { + results.addAll(iterator.next()); + } + Assert.assertEquals(memberScores.size(), results.size()); + } + +} diff --git a/persistence-modules/redis/src/test/java/com/baeldung/spring/redis/configuration/controller/BooksControllerUnitTest.java b/persistence-modules/redis/src/test/java/com/baeldung/spring/redis/configuration/controller/BooksControllerUnitTest.java new file mode 100644 index 0000000000..a5c3340065 --- /dev/null +++ b/persistence-modules/redis/src/test/java/com/baeldung/spring/redis/configuration/controller/BooksControllerUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.redis.configuration.controller; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.when; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.redis.configuration.entity.Book; +import com.baeldung.spring.redis.configuration.repository.BooksRepository; + +@RunWith(SpringJUnit4ClassRunner.class) +public class BooksControllerUnitTest { + + @Spy + @InjectMocks + private BooksController booksController; + + @Mock + private BooksRepository booksRepository; + + private static final Long BOOK_ID = 1l; + private static final Long OTHER_BOOK_ID = 2l; + private static final String BOOK_NAME = "Ulysses"; + private static final String ADDED = "Added"; + + @Test + public void whenNewBook_thenCorrect() { + assertEquals(ADDED, booksController.newBook(new Book(BOOK_ID, BOOK_NAME))); + } + + @Test + public void whenFindOneFinds_thenCorrect() { + Book book = new Book(BOOK_ID, BOOK_NAME); + when(booksRepository.findById(BOOK_ID)).thenReturn(book); + assertSame(book, booksController.findOne(BOOK_ID)); + } + + @Test + public void whenFindOneNotFound_thenReturnsNull() { + Book book = new Book(BOOK_ID, BOOK_NAME); + when(booksRepository.findById(BOOK_ID)).thenReturn(book); + assertNull(booksController.findOne(OTHER_BOOK_ID)); + } + +} diff --git a/persistence-modules/redis/src/test/java/com/baeldung/spring/redis/configuration/repository/BooksRepositoryUnitTest.java b/persistence-modules/redis/src/test/java/com/baeldung/spring/redis/configuration/repository/BooksRepositoryUnitTest.java new file mode 100644 index 0000000000..1edf9c7e89 --- /dev/null +++ b/persistence-modules/redis/src/test/java/com/baeldung/spring/redis/configuration/repository/BooksRepositoryUnitTest.java @@ -0,0 +1,66 @@ +package com.baeldung.spring.redis.configuration.repository; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.redis.configuration.entity.Book; + +@RunWith(SpringJUnit4ClassRunner.class) +public class BooksRepositoryUnitTest { + + @Spy + @InjectMocks + private BooksRepository booksRepository; + + @Mock + private RedisTemplate redisTemplate; + + @Mock + private ValueOperations valueOperations; + + private static final Long BOOK_ID = 1l; + private static final Long OTHER_BOOK_ID = 2l; + private static final String BOOK_NAME = "Ulysses"; + + @Test + public void whenSave_thenCorrect() { + Book book = new Book(BOOK_ID, BOOK_NAME); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + booksRepository.save(book); + verify(redisTemplate, times(1)).opsForValue(); + verify(valueOperations, times(1)).set(BOOK_ID, book); + } + + @Test + public void whenFindByIdFound_thenReturnsBook() { + Book book = new Book(BOOK_ID, BOOK_NAME); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + when(valueOperations.get(BOOK_ID)).thenReturn(book); + assertSame(book, booksRepository.findById(BOOK_ID)); + verify(redisTemplate, times(1)).opsForValue(); + verify(valueOperations, times(1)).get(BOOK_ID); + } + + @Test + public void whenFindByIdNotFound_thenReturnsNull() { + Book book = new Book(BOOK_ID, BOOK_NAME); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + when(valueOperations.get(BOOK_ID)).thenReturn(book); + assertNull(booksRepository.findById(OTHER_BOOK_ID)); + verify(redisTemplate, times(1)).opsForValue(); + verify(valueOperations, times(1)).get(OTHER_BOOK_ID); + } + +} diff --git a/persistence-modules/sirix/README.md b/persistence-modules/sirix/README.md index ab7fb65e44..923b111e7a 100644 --- a/persistence-modules/sirix/README.md +++ b/persistence-modules/sirix/README.md @@ -1,4 +1,3 @@ ## Relevant articles: -- [Introduction to Sirix](https://www.baeldung.com/introduction-to-sirix) - [A Guide to SirixDB](https://www.baeldung.com/sirix) diff --git a/persistence-modules/sirix/pom.xml b/persistence-modules/sirix/pom.xml index ccaec79775..0f114966f7 100644 --- a/persistence-modules/sirix/pom.xml +++ b/persistence-modules/sirix/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 io.sirix - core-api-tutorial + sirix 1.0-SNAPSHOT core-api-tutorial jar @@ -30,7 +30,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} ${maven.release.version} ${project.build.sourceEncoding} @@ -39,7 +39,7 @@ org.ow2.asm asm - 6.1 + ${asm.version} @@ -50,6 +50,8 @@ UTF-8 11 0.9.3 + 3.8.0 + 6.1 diff --git a/persistence-modules/solr/pom.xml b/persistence-modules/solr/pom.xml index 5902d42a82..fd993e0c67 100644 --- a/persistence-modules/solr/pom.xml +++ b/persistence-modules/solr/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/spring-boot-jdbi/README.md b/persistence-modules/spring-boot-jdbi/README.md deleted file mode 100644 index 5d171fb2ca..0000000000 --- a/persistence-modules/spring-boot-jdbi/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Using JDBI with Spring Boot](https://www.baeldung.com/spring-boot-jdbi) diff --git a/persistence-modules/spring-boot-jdbi/pom.xml b/persistence-modules/spring-boot-jdbi/pom.xml deleted file mode 100644 index db36185acd..0000000000 --- a/persistence-modules/spring-boot-jdbi/pom.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - 4.0.0 - com.baeldung.boot.jdbi - spring-boot-jdbi - 0.0.1-SNAPSHOT - spring-boot-jdbi - Sample SpringBoot JDBI Project - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../pom.xml - - - - - - org.springframework.boot - spring-boot-dependencies - 2.1.8.RELEASE - pom - import - - - - org.jdbi - jdbi3-spring4 - ${jdbi.version} - - - - org.jdbi - jdbi3-sqlobject - ${jdbi.version} - - - - - - - - org.springframework.boot - spring-boot-starter-jdbc - - - - org.jdbi - jdbi3-spring4 - - - - org.jdbi - jdbi3-sqlobject - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - com.h2database - h2 - runtime - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - 1.8 - 3.9.1 - - - diff --git a/persistence-modules/spring-boot-jdbi/src/main/resources/application.yml b/persistence-modules/spring-boot-jdbi/src/main/resources/application.yml deleted file mode 100644 index 8b13789179..0000000000 --- a/persistence-modules/spring-boot-jdbi/src/main/resources/application.yml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/persistence-modules/spring-boot-mysql/pom.xml b/persistence-modules/spring-boot-mysql/pom.xml index e4456b2eaf..9f6ec73522 100644 --- a/persistence-modules/spring-boot-mysql/pom.xml +++ b/persistence-modules/spring-boot-mysql/pom.xml @@ -37,18 +37,7 @@ - - spring-boot-mysql - - - src/main/resources - true - - - - - UTF-8 8.0.12 diff --git a/persistence-modules/spring-boot-jdbi/HELP.md b/persistence-modules/spring-boot-persistence-2/HELP.md similarity index 100% rename from persistence-modules/spring-boot-jdbi/HELP.md rename to persistence-modules/spring-boot-persistence-2/HELP.md diff --git a/persistence-modules/spring-boot-persistence-2/README.md b/persistence-modules/spring-boot-persistence-2/README.md new file mode 100644 index 0000000000..3ea93db4fe --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: + +- [Using JDBI with Spring Boot](https://www.baeldung.com/spring-boot-jdbi) +- [Oracle Connection Pooling With Spring](https://www.baeldung.com/spring-oracle-connection-pooling) diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml new file mode 100644 index 0000000000..9f456fa8af --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -0,0 +1,141 @@ + + + 4.0.0 + com.baeldung.boot.persistence + spring-boot-persistence-2 + 0.0.1-SNAPSHOT + spring-boot-jdbi + Sample SpringBoot JDBI Project + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.dependencies} + pom + import + + + + org.jdbi + jdbi3-spring4 + ${jdbi.version} + + + + org.jdbi + jdbi3-sqlobject + ${jdbi.version} + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.jdbi + jdbi3-spring4 + + + + org.jdbi + jdbi3-sqlobject + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.mchange + c3p0 + ${c3p0.version} + + + + org.apache.commons + commons-dbcp2 + + + + org.apache.tomcat + tomcat-jdbc + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-compiler-plugin + + + com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java + com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java + + + com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java + com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java + + + + + + + + 3.9.1 + 2.1.8.RELEASE + 0.9.5.2 + + + diff --git a/persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java diff --git a/persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/SpringBootJdbiApplication.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/SpringBootJdbiApplication.java similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/SpringBootJdbiApplication.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/SpringBootJdbiApplication.java diff --git a/persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/dao/CarMakerDao.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/dao/CarMakerDao.java similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/dao/CarMakerDao.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/dao/CarMakerDao.java diff --git a/persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/dao/CarModelDao.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/dao/CarModelDao.java similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/dao/CarModelDao.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/dao/CarModelDao.java diff --git a/persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/domain/CarMaker.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarMaker.java similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/domain/CarMaker.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarMaker.java diff --git a/persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java diff --git a/persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/mapper/CarMakerMapper.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarMakerMapper.java similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/mapper/CarMakerMapper.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarMakerMapper.java diff --git a/persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java diff --git a/persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/service/CarMakerService.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/service/CarMakerService.java similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/java/com/baeldung/boot/jdbi/service/CarMakerService.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/service/CarMakerService.java diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplication.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplication.java new file mode 100644 index 0000000000..fa7f884112 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.oracle.pooling; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import lombok.extern.slf4j.Slf4j; + +@SpringBootApplication +@Slf4j +public class SpringOraclePoolingApplication implements CommandLineRunner{ + + @Autowired + private DataSource dataSource; + + public static void main(String[] args) { + SpringApplication.run(SpringOraclePoolingApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + log.info("Connection Polling datasource : "+ dataSource); + + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/C3P0Configuration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/C3P0Configuration.java new file mode 100644 index 0000000000..f357924807 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/C3P0Configuration.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling.configuration; + +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import com.mchange.v2.c3p0.ComboPooledDataSource; + +@Configuration +@Profile("c3p0") +public class C3P0Configuration { + + @Bean + public DataSource dataSource() throws SQLException { + ComboPooledDataSource dataSource = new ComboPooledDataSource(); + dataSource.setUser("books"); + dataSource.setPassword("books"); + dataSource.setJdbcUrl("jdbc:oracle:thin:@//localhost:11521/ORCLPDB1"); + dataSource.setMinPoolSize(5); + dataSource.setMaxPoolSize(10); + return dataSource; + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java new file mode 100644 index 0000000000..9cf7e27c99 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.oracle.pooling.configuration; + +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import oracle.jdbc.pool.OracleDataSource; + +@Configuration +@Profile("oracle") +public class OracleConfiguration { + + @Bean + public DataSource dataSource() throws SQLException { + OracleDataSource dataSource = new OracleDataSource(); + dataSource.setUser("books"); + dataSource.setPassword("books"); + dataSource.setURL("jdbc:oracle:thin:@//localhost:11521/ORCLPDB1"); + dataSource.setFastConnectionFailoverEnabled(true); + dataSource.setImplicitCachingEnabled(true); + // Only with clients prior to v11.2 + // dataSource.setConnectionCachingEnabled(true); + return dataSource; + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java new file mode 100644 index 0000000000..b4c1544149 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.oracle.pooling.configuration; + +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import oracle.ucp.jdbc.PoolDataSource; +import oracle.ucp.jdbc.PoolDataSourceFactory; + +@Configuration +@Profile("oracle-ucp") +public class OracleUCPConfiguration { + + @Bean + public DataSource dataSource() throws SQLException { + PoolDataSource dataSource = PoolDataSourceFactory.getPoolDataSource(); + dataSource.setUser("books"); + dataSource.setPassword("books"); + dataSource.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource"); + dataSource.setURL("jdbc:oracle:thin:@//localhost:11521/ORCLPDB1"); + + dataSource.setFastConnectionFailoverEnabled(true); + dataSource.setInitialPoolSize(5); + dataSource.setMinPoolSize(5); + dataSource.setMaxPoolSize(10); + return dataSource; + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/controller/BookstoreController.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/controller/BookstoreController.java new file mode 100644 index 0000000000..49b998bfb9 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/controller/BookstoreController.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.oracle.pooling.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +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 com.baeldung.spring.oracle.pooling.entity.Book; +import com.baeldung.spring.oracle.pooling.exception.BookstoreException; +import com.baeldung.spring.oracle.pooling.repository.BookRepository; + +@RestController +@RequestMapping("/books") +public class BookstoreController { + + @Autowired + private BookRepository repository; + + @GetMapping(value = "/hello") + public String sayHello() { + return "Hello"; + } + + @GetMapping("/all") + public List findAll() { + return repository.findAll(); + } + + @PostMapping("/create") + public Book newBook(@RequestBody Book newBook) { + return repository.save(newBook); + } + + @GetMapping("/get/{id}") + public Book findOne(@PathVariable Long id) throws BookstoreException { + return repository.findById(id) + .orElseThrow(BookstoreException::new); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java new file mode 100644 index 0000000000..fb2c3fcf6a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.oracle.pooling.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String name; + + public Book() { + } + + public Book(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; + } + + @Override + public String toString() { + return "Book [id=" + id + ", name=" + name + "]"; + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/exception/BookstoreException.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/exception/BookstoreException.java new file mode 100644 index 0000000000..d2fb399ab3 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/exception/BookstoreException.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.oracle.pooling.exception; + +public class BookstoreException extends Exception{ + + /** + * + */ + private static final long serialVersionUID = 1L; + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/repository/BookRepository.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/repository/BookRepository.java new file mode 100644 index 0000000000..a50a1b24a4 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/repository/BookRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.oracle.pooling.repository; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.baeldung.spring.oracle.pooling.entity.Book; + +public interface BookRepository extends JpaRepository{ + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java new file mode 100644 index 0000000000..7fee55be8a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.transactional; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +class TransactionalCompareApplication { + + public static void main(String[] args) { + SpringApplication.run(TransactionalCompareApplication.class, args); + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java new file mode 100644 index 0000000000..1219111ffa --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java @@ -0,0 +1,60 @@ +package com.baeldung.spring.transactional.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Car { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String make; + + private String model; + + public Car() { + } + + public Car(Long id, String make, String model) { + this.id = id; + this.make = make; + this.model = model; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getMake() { + return make; + } + + public void setMake(String make) { + this.make = make; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + @Override + public String toString() { + return "Car{" + + "id=" + id + + ", make='" + make + '\'' + + ", model='" + model + '\'' + + '}'; + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java new file mode 100644 index 0000000000..f8ecc8f550 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.transactional.repository; + +import com.baeldung.spring.transactional.entity.Car; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface CarRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java new file mode 100644 index 0000000000..0821ddb02b --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.transactional.service; + +import com.baeldung.spring.transactional.entity.Car; +import com.baeldung.spring.transactional.repository.CarRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityExistsException; + +@Service +@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.SUPPORTS, readOnly = false, timeout = 30) +public class CarService { + + @Autowired + private CarRepository carRepository; + + @Transactional(rollbackFor = IllegalArgumentException.class, noRollbackFor = EntityExistsException.class, + rollbackForClassName = "IllegalArgumentException", noRollbackForClassName = "EntityExistsException") + public Car save(Car car) { + return carRepository.save(car); + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java new file mode 100644 index 0000000000..0aa0815a98 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java @@ -0,0 +1,22 @@ +package com.baeldung.spring.transactional.service; + +import com.baeldung.spring.transactional.entity.Car; +import com.baeldung.spring.transactional.repository.CarRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.persistence.EntityExistsException; +import javax.transaction.Transactional; + +@Service +@Transactional(Transactional.TxType.SUPPORTS) +public class RentalService { + + @Autowired + private CarRepository carRepository; + + @Transactional(rollbackOn = IllegalArgumentException.class, dontRollbackOn = EntityExistsException.class) + public Car rent(Car car) { + return carRepository.save(car); + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties b/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties new file mode 100644 index 0000000000..9a1c7fc89d --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties @@ -0,0 +1,27 @@ +logging.level.root=INFO + +# OracleDB connection settings +spring.datasource.url=jdbc:oracle:thin:@//localhost:11521/ORCLPDB1 +spring.datasource.username=books +spring.datasource.password=books +spring.datasource.driver-class-name=oracle.jdbc.OracleDriver + +# Comment this line for standard Spring Boot default choosing algorithm +#spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource + +# HikariCP settings +spring.datasource.hikari.minimumIdle=5 +spring.datasource.hikari.maximumPoolSize=20 +spring.datasource.hikari.idleTimeout=30000 +spring.datasource.hikari.maxLifetime=2000000 +spring.datasource.hikari.connectionTimeout=30000 +spring.datasource.hikari.poolName=HikariPoolBooks + +# Tomcat settings +spring.datasource.tomcat.maxActive=15 +spring.datasource.tomcat.minIdle=5 + +# JPA settings +spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect +spring.jpa.hibernate.use-new-id-generator-mappings=false +spring.jpa.hibernate.ddl-auto=create \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/application.yml b/persistence-modules/spring-boot-persistence-2/src/main/resources/application.yml new file mode 100644 index 0000000000..4b792fd5dc --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/application.yml @@ -0,0 +1,9 @@ +# Available profiles +# - none for no profile +# - oracle-pooling-basic - Oracle database with HikariCP. Loads configuration from application-oracle-pooling-basic.properties +# - oracle - Uses OracleDataSource. This profile also needs "oracle-pooling-basic" +# - oracle-ucp - Uses PoolDataSource. This profile also needs "oracle-pooling-basic" +# - c3p0 - Uses ComboPooledDataSource. This profile also needs "oracle-pooling-basic" +spring: + profiles: + active: none \ No newline at end of file diff --git a/persistence-modules/spring-boot-jdbi/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/findById.sql b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/findById.sql similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/findById.sql rename to persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/findById.sql diff --git a/persistence-modules/spring-boot-jdbi/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql rename to persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql diff --git a/persistence-modules/spring-boot-jdbi/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/findByMakerIdAndSku.sql b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/findByMakerIdAndSku.sql similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/findByMakerIdAndSku.sql rename to persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/findByMakerIdAndSku.sql diff --git a/persistence-modules/spring-boot-jdbi/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql rename to persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql diff --git a/persistence-modules/spring-boot-jdbi/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java similarity index 97% rename from persistence-modules/spring-boot-jdbi/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java rename to persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java index e4b623ee2b..93083f6c4c 100644 --- a/persistence-modules/spring-boot-jdbi/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java @@ -5,10 +5,8 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import org.jdbi.v3.core.Jdbi; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -24,7 +22,7 @@ import com.baeldung.boot.jdbi.service.CarMakerService; import lombok.extern.slf4j.Slf4j; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = {SpringBootJdbiApplication.class, JdbiConfiguration.class}) @Slf4j public class SpringBootJdbiApplicationUnitTest { diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationC3P0LiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationC3P0LiveTest.java new file mode 100644 index 0000000000..5a2d3f2d29 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationC3P0LiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +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.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles({"oracle-pooling-basic", "c3p0"}) +public class SpringOraclePoolingApplicationC3P0LiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenC3p0Configuration_thenBuildsComboPooledDataSource() { + assertTrue(dataSource instanceof com.mchange.v2.c3p0.ComboPooledDataSource); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationHikariCPLiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationHikariCPLiveTest.java new file mode 100644 index 0000000000..ab8fc1e121 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationHikariCPLiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +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.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles("oracle-pooling-basic") +public class SpringOraclePoolingApplicationHikariCPLiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenHikariCPConfiguration_thenBuildsHikariCP() { + assertTrue(dataSource instanceof com.zaxxer.hikari.HikariDataSource); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java new file mode 100644 index 0000000000..229375dadd --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +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.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles({"oracle-pooling-basic", "oracle"}) +public class SpringOraclePoolingApplicationOracleLiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenOracleConfiguration_thenBuildsOracleDataSource() { + assertTrue(dataSource instanceof oracle.jdbc.pool.OracleDataSource); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java new file mode 100644 index 0000000000..4fb6aa6bae --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +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.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles({"oracle-pooling-basic", "oracle-ucp"}) +public class SpringOraclePoolingApplicationOracleUCPLiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenOracleUCPConfiguration_thenBuildsOraclePoolDataSource() { + assertTrue(dataSource instanceof oracle.ucp.jdbc.PoolDataSource); + } + +} diff --git a/persistence-modules/spring-boot-jdbi/src/test/resources/data.sql b/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/test/resources/data.sql rename to persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql diff --git a/persistence-modules/spring-boot-jdbi/src/test/resources/schema.sql b/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql similarity index 100% rename from persistence-modules/spring-boot-jdbi/src/test/resources/schema.sql rename to persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql diff --git a/persistence-modules/spring-boot-persistence-h2/README.md b/persistence-modules/spring-boot-persistence-h2/README.md index a0f9c67a33..d11ec1f409 100644 --- a/persistence-modules/spring-boot-persistence-h2/README.md +++ b/persistence-modules/spring-boot-persistence-h2/README.md @@ -1,4 +1,5 @@ ### Relevant Articles: - [Access the Same In-Memory H2 Database in Multiple Spring Boot Applications](https://www.baeldung.com/spring-boot-access-h2-database-multiple-apps) - [Spring Boot With H2 Database](https://www.baeldung.com/spring-boot-h2-database) -- [Hibernate @NotNull vs @Column(nullable = false)](https://www.baeldung.com/hibernate-notnull-vs-nullable) \ No newline at end of file +- [Hibernate @NotNull vs @Column(nullable = false)](https://www.baeldung.com/hibernate-notnull-vs-nullable) +- [Quick Guide to Hibernate enable_lazy_load_no_trans Property](https://www.baeldung.com/hibernate-lazy-loading-workaround) diff --git a/persistence-modules/spring-boot-persistence-h2/pom.xml b/persistence-modules/spring-boot-persistence-h2/pom.xml index 9a0a72ba23..777bc6cb2d 100644 --- a/persistence-modules/spring-boot-persistence-h2/pom.xml +++ b/persistence-modules/spring-boot-persistence-h2/pom.xml @@ -5,7 +5,6 @@ 4.0.0 com.baeldung.h2db spring-boot-persistence-h2 - 0.0.1-SNAPSHOT spring-boot-persistence-h2 jar Demo Spring Boot applications that starts H2 in memory database @@ -30,24 +29,30 @@ com.h2database h2 + + org.projectlombok + lombok + ${lombok.version} + compile + + + org.hibernate + hibernate-core + ${hibernate.version} + + + com.vladmihalcea + db-util + ${db-util.version} + - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - UTF-8 - UTF-8 - 1.8 com.baeldung.h2db.demo.server.SpringBootApp 2.0.4.RELEASE + 5.3.11.Final + 1.0.4 diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/LazyLoadNoTransSpringBootApplication.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/LazyLoadNoTransSpringBootApplication.java new file mode 100644 index 0000000000..a52d9fc2f9 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/LazyLoadNoTransSpringBootApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.h2db.lazy_load_no_trans; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@SpringBootApplication +@EnableTransactionManagement +public class LazyLoadNoTransSpringBootApplication { + public static void main(String[] args) { + SpringApplication.run(LazyLoadNoTransSpringBootApplication.class, args); + } +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java new file mode 100644 index 0000000000..c087427b65 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java @@ -0,0 +1,67 @@ +package com.baeldung.h2db.lazy_load_no_trans.config; + +import net.ttddyy.dsproxy.listener.DataSourceQueryCountListener; +import net.ttddyy.dsproxy.listener.logging.CommonsQueryLoggingListener; +import net.ttddyy.dsproxy.listener.logging.DefaultQueryLogEntryCreator; +import net.ttddyy.dsproxy.listener.logging.SLF4JLogLevel; +import net.ttddyy.dsproxy.listener.logging.SLF4JQueryLoggingListener; +import net.ttddyy.dsproxy.support.ProxyDataSource; +import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.stereotype.Component; +import org.springframework.util.ReflectionUtils; + +import javax.sql.DataSource; +import java.lang.reflect.Method; + +@Component +public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor { + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) { + if (bean instanceof DataSource && !(bean instanceof ProxyDataSource)) { + // Instead of directly returning a less specific datasource bean + // (e.g.: HikariDataSource -> DataSource), return a proxy object. + // See following links for why: + // https://stackoverflow.com/questions/44237787/how-to-use-user-defined-database-proxy-in-datajpatest + // https://gitter.im/spring-projects/spring-boot?at=5983602d2723db8d5e70a904 + // http://blog.arnoldgalovics.com/2017/06/26/configuring-a-datasource-proxy-in-spring-boot/ + final ProxyFactory factory = new ProxyFactory(bean); + factory.setProxyTargetClass(true); + factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean)); + return factory.getProxy(); + } + return bean; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) { + return bean; + } + + private static class ProxyDataSourceInterceptor implements MethodInterceptor { + private final DataSource dataSource; + + public ProxyDataSourceInterceptor(final DataSource dataSource) { + this.dataSource = ProxyDataSourceBuilder.create(dataSource) + .name("MyDS") + .multiline() + .logQueryBySlf4j(SLF4JLogLevel.INFO) + .listener(new DataSourceQueryCountListener()) + .build(); + } + + @Override + public Object invoke(final MethodInvocation invocation) throws Throwable { + final Method proxyMethod = ReflectionUtils.findMethod(this.dataSource.getClass(), + invocation.getMethod().getName()); + if (proxyMethod != null) { + return proxyMethod.invoke(this.dataSource, invocation.getArguments()); + } + return invocation.proceed(); + } + } +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/Document.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/Document.java new file mode 100644 index 0000000000..9d69e7eb58 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/Document.java @@ -0,0 +1,26 @@ +package com.baeldung.h2db.lazy_load_no_trans.entity; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.annotations.Immutable; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Immutable +public class Document { + + @Id + private Long id; + + private String title; + + private Long userId; +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/User.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/User.java new file mode 100644 index 0000000000..ae9cb9e4e8 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/User.java @@ -0,0 +1,37 @@ +package com.baeldung.h2db.lazy_load_no_trans.entity; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.annotations.Fetch; +import org.hibernate.annotations.FetchMode; +import org.hibernate.annotations.Immutable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Immutable +public class User { + + @Id + @GeneratedValue + private Long id; + + private String name; + + private String comment; + + @OneToMany(mappedBy = "userId") + @Fetch(FetchMode.SUBSELECT) + private List docs = new ArrayList<>(); +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/repository/UserRepository.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/repository/UserRepository.java new file mode 100644 index 0000000000..bafe484163 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/repository/UserRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.h2db.lazy_load_no_trans.repository; + +import com.baeldung.h2db.lazy_load_no_trans.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends JpaRepository { +} \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/service/ServiceLayer.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/service/ServiceLayer.java new file mode 100644 index 0000000000..ff3783fd9d --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/service/ServiceLayer.java @@ -0,0 +1,34 @@ +package com.baeldung.h2db.lazy_load_no_trans.service; + +import com.baeldung.h2db.lazy_load_no_trans.entity.User; +import com.baeldung.h2db.lazy_load_no_trans.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collection; + +@Service +public class ServiceLayer { + + @Autowired + private UserRepository userRepository; + + @Transactional(readOnly = true) + public long countAllDocsTransactional() { + return countAllDocs(); + } + + public long countAllDocsNonTransactional() { + return countAllDocs(); + } + + private long countAllDocs() { + return userRepository.findAll() + .stream() + .map(User::getDocs) + .mapToLong(Collection::size) + .sum(); + } + +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties new file mode 100644 index 0000000000..1055806ecf --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties @@ -0,0 +1,14 @@ +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-drop +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console +spring.datasource.data=data-trans.sql + +logging.level.org.hibernate.SQL=INFO +logging.level.org.hibernate.type=TRACE +spring.jpa.properties.hibernate.validator.apply_to_ddl=false +spring.jpa.properties.hibernate.enable_lazy_load_no_trans=false +spring.jpa.open-in-view=false \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties new file mode 100644 index 0000000000..77aacf0d77 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties @@ -0,0 +1,14 @@ +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-drop +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console +spring.datasource.data=data-trans.sql + +logging.level.org.hibernate.SQL=INFO +logging.level.org.hibernate.type=TRACE +spring.jpa.properties.hibernate.validator.apply_to_ddl=false +spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true +spring.jpa.open-in-view=false \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql b/persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql new file mode 100644 index 0000000000..b8835e70cb --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql @@ -0,0 +1,26 @@ +DROP TABLE IF EXISTS billionaires; + +CREATE TABLE billionaires ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +INSERT INTO billionaires (first_name, last_name, career) VALUES +('Aliko', 'Dangote', 'Billionaire Industrialist'), +('Bill', 'Gates', 'Billionaire Tech Entrepreneur'), +('Folrunsho', 'Alakija', 'Billionaire Oil Magnate'); + +insert into USER values (101, 'user1', 'comment1'); +insert into USER values (102, 'user2', 'comment2'); +insert into USER values (103, 'user3', 'comment3'); +insert into USER values (104, 'user4', 'comment4'); +insert into USER values (105, 'user5', 'comment5'); + +insert into DOCUMENT values (1, 'doc1', 101); +insert into DOCUMENT values (2, 'doc2', 101); +insert into DOCUMENT values (3, 'doc3', 101); +insert into DOCUMENT values (4, 'doc4', 101); +insert into DOCUMENT values (5, 'doc5', 102); +insert into DOCUMENT values (6, 'doc6', 102); \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql b/persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql deleted file mode 100644 index 2d7b446005..0000000000 --- a/persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql +++ /dev/null @@ -1,13 +0,0 @@ -DROP TABLE IF EXISTS billionaires; - -CREATE TABLE billionaires ( - id INT AUTO_INCREMENT PRIMARY KEY, - first_name VARCHAR(250) NOT NULL, - last_name VARCHAR(250) NOT NULL, - career VARCHAR(250) DEFAULT NULL -); - -INSERT INTO billionaires (first_name, last_name, career) VALUES -('Aliko', 'Dangote', 'Billionaire Industrialist'), -('Bill', 'Gates', 'Billionaire Tech Entrepreneur'), -('Folrunsho', 'Alakija', 'Billionaire Oil Magnate'); \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOffIntegrationTest.java b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOffIntegrationTest.java new file mode 100644 index 0000000000..cb5063d8a4 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOffIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.lazy_load_no_trans; + +import com.baeldung.h2db.lazy_load_no_trans.LazyLoadNoTransSpringBootApplication; +import com.baeldung.h2db.lazy_load_no_trans.service.ServiceLayer; +import com.vladmihalcea.sql.SQLStatementCountValidator; +import org.hibernate.LazyInitializationException; +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.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = LazyLoadNoTransSpringBootApplication.class) +@ActiveProfiles("lazy-load-no-trans-off") +public class LazyLoadNoTransPropertyOffIntegrationTest { + + @Autowired + private ServiceLayer serviceLayer; + + private static final long EXPECTED_DOCS_COLLECTION_SIZE = 6; + + @Test(expected = LazyInitializationException.class) + public void whenCallNonTransactionalMethodWithPropertyOff_thenThrowException() { + serviceLayer.countAllDocsNonTransactional(); + } + + @Test + public void whenCallTransactionalMethodWithPropertyOff_thenTestPass() { + SQLStatementCountValidator.reset(); + + long docsCount = serviceLayer.countAllDocsTransactional(); + + assertEquals(EXPECTED_DOCS_COLLECTION_SIZE, docsCount); + + SQLStatementCountValidator.assertSelectCount(2); + } +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOnIntegrationTest.java b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOnIntegrationTest.java new file mode 100644 index 0000000000..5968fde7b7 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/lazy_load_no_trans/LazyLoadNoTransPropertyOnIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.lazy_load_no_trans; + +import com.baeldung.h2db.lazy_load_no_trans.LazyLoadNoTransSpringBootApplication; +import com.baeldung.h2db.lazy_load_no_trans.service.ServiceLayer; +import com.vladmihalcea.sql.SQLStatementCountValidator; +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.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = LazyLoadNoTransSpringBootApplication.class) +@ActiveProfiles("lazy-load-no-trans-on") +public class LazyLoadNoTransPropertyOnIntegrationTest { + + @Autowired + private ServiceLayer serviceLayer; + + private static final long EXPECTED_DOCS_COLLECTION_SIZE = 6; + private static final long EXPECTED_USERS_COUNT = 5; + + @Test + public void whenCallNonTransactionalMethodWithPropertyOn_thenGetNplusOne() { + SQLStatementCountValidator.reset(); + + long docsCount = serviceLayer.countAllDocsNonTransactional(); + + assertEquals(EXPECTED_DOCS_COLLECTION_SIZE, docsCount); + + SQLStatementCountValidator.assertSelectCount(EXPECTED_USERS_COUNT + 1); + } + + @Test + public void whenCallTransactionalMethodWithPropertyOn_thenTestPass() { + SQLStatementCountValidator.reset(); + + long docsCount = serviceLayer.countAllDocsTransactional(); + + assertEquals(EXPECTED_DOCS_COLLECTION_SIZE, docsCount); + + SQLStatementCountValidator.assertSelectCount(2); + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/pom.xml b/persistence-modules/spring-boot-persistence-mongodb/pom.xml index da48f066f9..de52a4b2d6 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb/pom.xml @@ -34,80 +34,6 @@ 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-test - test - - - spring-boot-persistence-mongodb - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-war-plugin - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - json - - - - - - - - - + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties index 6548f2b28a..65e65cc96c 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties @@ -3,7 +3,7 @@ server.port=8082 #spring boot mongodb spring.data.mongodb.host=localhost -spring.data.mongodb.port=27017 +spring.data.mongodb.port=0 spring.data.mongodb.database=springboot-mongo spring.thymeleaf.cache=false diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index 049e7225ac..c58e8dbf86 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 spring-boot-persistence 0.1.0 @@ -17,17 +18,14 @@ org.springframework.boot spring-boot-starter-web - ${spring-boot.version} org.springframework.boot spring-boot-starter-thymeleaf - ${spring-boot.version} org.springframework.boot spring-boot-starter-data-jpa - ${spring-boot.version} com.zaxxer @@ -38,7 +36,6 @@ org.springframework.boot spring-boot-starter-test - ${spring-boot.version} org.mockito @@ -61,7 +58,6 @@ javax.validation validation-api - ${validation-api.version} org.xerial @@ -70,39 +66,17 @@ org.apache.derby derby - ${derby.version} org.hsqldb hsqldb - ${hsqldb.version} - - spring-boot-persistence - - - src/main/resources - true - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - UTF-8 - 8.0.12 - 9.0.10 2.23.0 2.0.1.Final - 10.13.1.1 - 2.3.4 2.1.7.RELEASE diff --git a/persistence-modules/spring-data-cassandra-reactive/pom.xml b/persistence-modules/spring-data-cassandra-reactive/pom.xml index a57ebbe703..70a5f556e2 100644 --- a/persistence-modules/spring-data-cassandra-reactive/pom.xml +++ b/persistence-modules/spring-data-cassandra-reactive/pom.xml @@ -1,10 +1,8 @@ - + 4.0.0 spring-data-cassandra-reactive - 0.0.1-SNAPSHOT spring-data-cassandra-reactive jar Spring Data Cassandra reactive @@ -20,7 +18,6 @@ org.springframework.data spring-data-cassandra - ${spring-data-cassandra.version} io.projectreactor @@ -54,10 +51,6 @@ - UTF-8 - UTF-8 - - 2.1.2.RELEASE 3.11.2.0 diff --git a/persistence-modules/spring-data-cassandra/README.md b/persistence-modules/spring-data-cassandra/README.md index 456eefcf18..9c6745470b 100644 --- a/persistence-modules/spring-data-cassandra/README.md +++ b/persistence-modules/spring-data-cassandra/README.md @@ -1,8 +1,8 @@ ## Spring Data Cassandra ### Relevant Articles: -- [Introduction to Spring Data Cassandra](http://www.baeldung.com/spring-data-cassandra-tutorial) -- [Using the CassandraTemplate from Spring Data](http://www.baeldung.com/spring-data-cassandratemplate-cqltemplate) +- [Introduction to Spring Data Cassandra](https://www.baeldung.com/spring-data-cassandra-tutorial) +- [Using the CassandraTemplate from Spring Data](https://www.baeldung.com/spring-data-cassandratemplate-cqltemplate) ### Build the Project with Tests Running ``` diff --git a/persistence-modules/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml index 9ea39f3f55..0f0aae4ebf 100644 --- a/persistence-modules/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -3,7 +3,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-data-cassandra - 0.0.1-SNAPSHOT spring-data-cassandra jar @@ -80,7 +79,6 @@ 2.1.9.2 2.1.9.2 2.0-0 - 19.0 diff --git a/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java b/persistence-modules/spring-data-cassandra/src/main/java/com/baeldung/spring/data/cassandra/config/CassandraConfig.java similarity index 94% rename from persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java rename to persistence-modules/spring-data-cassandra/src/main/java/com/baeldung/spring/data/cassandra/config/CassandraConfig.java index 2edd5551a5..3614c2a9f6 100644 --- a/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java +++ b/persistence-modules/spring-data-cassandra/src/main/java/com/baeldung/spring/data/cassandra/config/CassandraConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.cassandra.config; +package com.baeldung.spring.data.cassandra.config; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -15,7 +15,7 @@ import org.springframework.data.cassandra.repository.config.EnableCassandraRepos @Configuration @PropertySource(value = { "classpath:cassandra.properties" }) -@EnableCassandraRepositories(basePackages = "org.baeldung.spring.data.cassandra.repository") +@EnableCassandraRepositories(basePackages = "com.baeldung.spring.data.cassandra.repository") public class CassandraConfig extends AbstractCassandraConfiguration { private static final Log LOGGER = LogFactory.getLog(CassandraConfig.class); diff --git a/persistence-modules/spring-data-cassandra/src/main/java/com/baeldung/spring/data/cassandra/model/Book.java b/persistence-modules/spring-data-cassandra/src/main/java/com/baeldung/spring/data/cassandra/model/Book.java new file mode 100644 index 0000000000..d347a36184 --- /dev/null +++ b/persistence-modules/spring-data-cassandra/src/main/java/com/baeldung/spring/data/cassandra/model/Book.java @@ -0,0 +1,67 @@ +package com.baeldung.spring.data.cassandra.model; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +import org.springframework.cassandra.core.Ordering; +import org.springframework.cassandra.core.PrimaryKeyType; +import org.springframework.data.cassandra.mapping.Column; +import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; +import org.springframework.data.cassandra.mapping.Table; + +@Table +public class Book { + + @PrimaryKeyColumn(name = "id", ordinal = 0, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING) + private UUID id; + + @PrimaryKeyColumn(name = "title", ordinal = 1, type = PrimaryKeyType.PARTITIONED) + private String title; + + @PrimaryKeyColumn(name = "publisher", ordinal = 2, type = PrimaryKeyType.PARTITIONED) + private String publisher; + + @Column + private Set tags = new HashSet<>(); + + public Book(final UUID id, final String title, final String publisher, final Set tags) { + this.id = id; + this.title = title; + this.publisher = publisher; + this.tags.addAll(tags); + } + + public UUID getId() { + return id; + } + + public String getTitle() { + return title; + } + + public String getPublisher() { + return publisher; + } + + public Set getTags() { + return tags; + } + + public void setId(final UUID id) { + this.id = id; + } + + public void setTitle(final String title) { + this.title = title; + } + + public void setPublisher(final String publisher) { + this.publisher = publisher; + } + + public void setTags(final Set tags) { + this.tags = tags; + } + +} diff --git a/persistence-modules/spring-data-cassandra/src/main/java/com/baeldung/spring/data/cassandra/repository/BookRepository.java b/persistence-modules/spring-data-cassandra/src/main/java/com/baeldung/spring/data/cassandra/repository/BookRepository.java new file mode 100644 index 0000000000..ad144f3125 --- /dev/null +++ b/persistence-modules/spring-data-cassandra/src/main/java/com/baeldung/spring/data/cassandra/repository/BookRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.data.cassandra.repository; + +import com.baeldung.spring.data.cassandra.model.Book; +import org.springframework.data.cassandra.repository.CassandraRepository; +import org.springframework.data.cassandra.repository.Query; +import org.springframework.stereotype.Repository; + +@Repository +public interface BookRepository extends CassandraRepository { + + @Query("select * from book where title = ?0 and publisher=?1") + Iterable findByTitleAndPublisher(String title, String publisher); + +} diff --git a/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java b/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java deleted file mode 100644 index a8ec81d6b5..0000000000 --- a/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.baeldung.spring.data.cassandra.model; - -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - -import org.springframework.cassandra.core.Ordering; -import org.springframework.cassandra.core.PrimaryKeyType; -import org.springframework.data.cassandra.mapping.Column; -import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; -import org.springframework.data.cassandra.mapping.Table; - -@Table -public class Book { - - @PrimaryKeyColumn(name = "id", ordinal = 0, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING) - private UUID id; - - @PrimaryKeyColumn(name = "title", ordinal = 1, type = PrimaryKeyType.PARTITIONED) - private String title; - - @PrimaryKeyColumn(name = "publisher", ordinal = 2, type = PrimaryKeyType.PARTITIONED) - private String publisher; - - @Column - private Set tags = new HashSet<>(); - - public Book(final UUID id, final String title, final String publisher, final Set tags) { - this.id = id; - this.title = title; - this.publisher = publisher; - this.tags.addAll(tags); - } - - public UUID getId() { - return id; - } - - public String getTitle() { - return title; - } - - public String getPublisher() { - return publisher; - } - - public Set getTags() { - return tags; - } - - public void setId(final UUID id) { - this.id = id; - } - - public void setTitle(final String title) { - this.title = title; - } - - public void setPublisher(final String publisher) { - this.publisher = publisher; - } - - public void setTags(final Set tags) { - this.tags = tags; - } - -} diff --git a/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java b/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java deleted file mode 100644 index 66d656ac3a..0000000000 --- a/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.spring.data.cassandra.repository; - -import org.baeldung.spring.data.cassandra.model.Book; -import org.springframework.data.cassandra.repository.CassandraRepository; -import org.springframework.data.cassandra.repository.Query; -import org.springframework.stereotype.Repository; - -@Repository -public interface BookRepository extends CassandraRepository { - - @Query("select * from book where title = ?0 and publisher=?1") - Iterable findByTitleAndPublisher(String title, String publisher); - -} diff --git a/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..22bd5c6551 --- /dev/null +++ b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,67 @@ +package com.baeldung; + +import java.io.IOException; +import java.util.HashMap; + +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; +import com.baeldung.spring.data.cassandra.config.CassandraConfig; +import com.baeldung.spring.data.cassandra.model.Book; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +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.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class SpringContextTest { + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private CassandraAdminOperations adminTemplate; + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + final Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + Thread.sleep(5000); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} diff --git a/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java new file mode 100644 index 0000000000..55e968d6f2 --- /dev/null +++ b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java @@ -0,0 +1,121 @@ +package com.baeldung.spring.data.cassandra.repository; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.io.IOException; +import java.util.HashMap; + +import com.baeldung.spring.data.cassandra.model.Book; +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.thrift.transport.TTransportException; +import com.baeldung.spring.data.cassandra.config.CassandraConfig; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +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.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class BookRepositoryIntegrationTest { + private static final Log LOGGER = LogFactory.getLog(BookRepositoryIntegrationTest.class); + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private BookRepository bookRepository; + + @Autowired + private CassandraAdminOperations adminTemplate; + + // + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + LOGGER.info("Server Started at 127.0.0.1:9142... "); + final Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + LOGGER.info("KeySpace created and activated."); + Thread.sleep(5000); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSavingBook_thenAvailableOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + bookRepository.save(ImmutableSet.of(javaBook)); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + assertEquals(javaBook.getId(), books.iterator().next().getId()); + } + + @Test + public void whenUpdatingBooks_thenAvailableOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + bookRepository.save(ImmutableSet.of(javaBook)); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + javaBook.setTitle("Head First Java Second Edition"); + bookRepository.save(ImmutableSet.of(javaBook)); + final Iterable updateBooks = bookRepository.findByTitleAndPublisher("Head First Java Second Edition", "O'Reilly Media"); + assertEquals(javaBook.getTitle(), updateBooks.iterator().next().getTitle()); + } + + @Test(expected = java.util.NoSuchElementException.class) + public void whenDeletingExistingBooks_thenNotAvailableOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + bookRepository.save(ImmutableSet.of(javaBook)); + bookRepository.delete(javaBook); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + assertNotEquals(javaBook.getId(), books.iterator().next().getId()); + } + + @Test + public void whenSavingBooks_thenAllShouldAvailableOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + bookRepository.save(ImmutableSet.of(javaBook)); + bookRepository.save(ImmutableSet.of(dPatternBook)); + final Iterable books = bookRepository.findAll(); + int bookCount = 0; + for (final Book book : books) { + bookCount++; + } + assertEquals(bookCount, 2); + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } + +} diff --git a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java similarity index 97% rename from persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java rename to persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java index e331ac3cd4..90ae68ba98 100644 --- a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java +++ b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.cassandra.repository; +package com.baeldung.spring.data.cassandra.repository; import static junit.framework.TestCase.assertNull; import static org.hamcrest.CoreMatchers.is; @@ -10,12 +10,12 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import com.baeldung.spring.data.cassandra.config.CassandraConfig; +import com.baeldung.spring.data.cassandra.model.Book; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.thrift.transport.TTransportException; -import org.baeldung.spring.data.cassandra.config.CassandraConfig; -import org.baeldung.spring.data.cassandra.model.Book; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; import org.junit.After; import org.junit.AfterClass; diff --git a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java similarity index 96% rename from persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java rename to persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java index f7e42ae23b..f948218807 100644 --- a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java +++ b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.cassandra.repository; +package com.baeldung.spring.data.cassandra.repository; import static junit.framework.TestCase.assertEquals; @@ -12,8 +12,8 @@ import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.thrift.transport.TTransportException; -import org.baeldung.spring.data.cassandra.config.CassandraConfig; -import org.baeldung.spring.data.cassandra.model.Book; +import com.baeldung.spring.data.cassandra.config.CassandraConfig; +import com.baeldung.spring.data.cassandra.model.Book; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; import org.junit.After; import org.junit.AfterClass; diff --git a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 89e729da86..0000000000 --- a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.baeldung; - -import java.io.IOException; -import java.util.HashMap; - -import org.apache.cassandra.exceptions.ConfigurationException; -import org.apache.thrift.transport.TTransportException; -import org.baeldung.spring.data.cassandra.config.CassandraConfig; -import org.baeldung.spring.data.cassandra.model.Book; -import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -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.springframework.beans.factory.annotation.Autowired; -import org.springframework.cassandra.core.cql.CqlIdentifier; -import org.springframework.data.cassandra.core.CassandraAdminOperations; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = CassandraConfig.class) -public class SpringContextTest { - - public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; - - public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; - - public static final String DATA_TABLE_NAME = "book"; - - @Autowired - private CassandraAdminOperations adminTemplate; - - @BeforeClass - public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { - EmbeddedCassandraServerHelper.startEmbeddedCassandra(); - final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); - final Session session = cluster.connect(); - session.execute(KEYSPACE_CREATION_QUERY); - session.execute(KEYSPACE_ACTIVATE_QUERY); - Thread.sleep(5000); - } - - @Before - public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { - adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); - } - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } - - @After - public void dropTable() { - adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); - } - - @AfterClass - public static void stopCassandraEmbedded() { - EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); - } -} diff --git a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java deleted file mode 100644 index 8cbcdc3195..0000000000 --- a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.baeldung.spring.data.cassandra.repository; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -import java.io.IOException; -import java.util.HashMap; - -import org.apache.cassandra.exceptions.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.thrift.transport.TTransportException; -import org.baeldung.spring.data.cassandra.config.CassandraConfig; -import org.baeldung.spring.data.cassandra.model.Book; -import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -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.springframework.beans.factory.annotation.Autowired; -import org.springframework.cassandra.core.cql.CqlIdentifier; -import org.springframework.data.cassandra.core.CassandraAdminOperations; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.utils.UUIDs; -import com.google.common.collect.ImmutableSet; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = CassandraConfig.class) -public class BookRepositoryIntegrationTest { - private static final Log LOGGER = LogFactory.getLog(BookRepositoryIntegrationTest.class); - - public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; - - public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; - - public static final String DATA_TABLE_NAME = "book"; - - @Autowired - private BookRepository bookRepository; - - @Autowired - private CassandraAdminOperations adminTemplate; - - // - - @BeforeClass - public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { - EmbeddedCassandraServerHelper.startEmbeddedCassandra(); - final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); - LOGGER.info("Server Started at 127.0.0.1:9142... "); - final Session session = cluster.connect(); - session.execute(KEYSPACE_CREATION_QUERY); - session.execute(KEYSPACE_ACTIVATE_QUERY); - LOGGER.info("KeySpace created and activated."); - Thread.sleep(5000); - } - - @Before - public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { - adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); - } - - @Test - public void whenSavingBook_thenAvailableOnRetrieval() { - final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - bookRepository.save(ImmutableSet.of(javaBook)); - final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); - assertEquals(javaBook.getId(), books.iterator().next().getId()); - } - - @Test - public void whenUpdatingBooks_thenAvailableOnRetrieval() { - final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - bookRepository.save(ImmutableSet.of(javaBook)); - final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); - javaBook.setTitle("Head First Java Second Edition"); - bookRepository.save(ImmutableSet.of(javaBook)); - final Iterable updateBooks = bookRepository.findByTitleAndPublisher("Head First Java Second Edition", "O'Reilly Media"); - assertEquals(javaBook.getTitle(), updateBooks.iterator().next().getTitle()); - } - - @Test(expected = java.util.NoSuchElementException.class) - public void whenDeletingExistingBooks_thenNotAvailableOnRetrieval() { - final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - bookRepository.save(ImmutableSet.of(javaBook)); - bookRepository.delete(javaBook); - final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); - assertNotEquals(javaBook.getId(), books.iterator().next().getId()); - } - - @Test - public void whenSavingBooks_thenAllShouldAvailableOnRetrieval() { - final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - bookRepository.save(ImmutableSet.of(javaBook)); - bookRepository.save(ImmutableSet.of(dPatternBook)); - final Iterable books = bookRepository.findAll(); - int bookCount = 0; - for (final Book book : books) { - bookCount++; - } - assertEquals(bookCount, 2); - } - - @After - public void dropTable() { - adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); - } - - @AfterClass - public static void stopCassandraEmbedded() { - EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); - } - -} diff --git a/persistence-modules/spring-data-couchbase-2/README.md b/persistence-modules/spring-data-couchbase-2/README.md index 3145fc653a..aa6f7375cb 100644 --- a/persistence-modules/spring-data-couchbase-2/README.md +++ b/persistence-modules/spring-data-couchbase-2/README.md @@ -1,9 +1,9 @@ ## Spring Data Couchbase Tutorial Project ### Relevant Articles: -- [Intro to Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase) -- [Entity Validation, Optimistic Locking, and Query Consistency in Spring Data Couchbase](http://www.baeldung.com/entity-validation-locking-and-query-consistency-in-spring-data-couchbase) -- [Multiple Buckets and Spatial View Queries in Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase-buckets-and-spatial-view-queries) +- [Intro to Spring Data Couchbase](https://www.baeldung.com/spring-data-couchbase) +- [Entity Validation, Optimistic Locking, and Query Consistency in Spring Data Couchbase](https://www.baeldung.com/entity-validation-locking-and-query-consistency-in-spring-data-couchbase) +- [Multiple Buckets and Spatial View Queries in Spring Data Couchbase](https://www.baeldung.com/spring-data-couchbase-buckets-and-spatial-view-queries) ### Overview This Maven project contains the Java code for Spring Data Couchbase @@ -25,14 +25,14 @@ mvn clean install ### Package Organization Java classes for the first two tutorials listed above are in src/main/java in the package hierarchy -org.baeldung.spring.data.couchbase +com.baeldung.spring.data.couchbase Java classes for the multiple-bucket tutorials are in src/main/java in the package hierarchy -org.baeldung.spring.data.couchbase2b +com.baeldung.spring.data.couchbase2b ### Running the tests The test classes for the single-bucket tutorials are in src/test/java in the package -org.baeldung.spring.data.couchbase.service: +com.baeldung.spring.data.couchbase.service: - PersonServiceTest (abstract) - PersonRepositoryTest (concrete) - PersonTemplateServiceTest (concrete) @@ -41,7 +41,7 @@ org.baeldung.spring.data.couchbase.service: - StudentTemplateServiceTest (concrete) The concrete test classes for the multiple-bucket tutorial are in src/test/java in the package -org.baeldung.spring.data.couchbase2b.service: +com.baeldung.spring.data.couchbase2b.service: - CampusRepositoryServiceImplTest - PersonRepositoryServiceImplTest - StudentRepositoryServiceImplTest diff --git a/persistence-modules/spring-data-couchbase-2/pom.xml b/persistence-modules/spring-data-couchbase-2/pom.xml index 56456fc04b..0a20a3ff0e 100644 --- a/persistence-modules/spring-data-couchbase-2/pom.xml +++ b/persistence-modules/spring-data-couchbase-2/pom.xml @@ -3,7 +3,7 @@ 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 - org.baeldung + com.baeldung spring-data-couchbase-2 0.1-SNAPSHOT spring-data-couchbase-2 @@ -11,9 +11,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Campus.java similarity index 97% rename from persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Campus.java index c357ab8596..d710a35796 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Campus.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.model; +package com.baeldung.spring.data.couchbase.model; import javax.validation.constraints.NotNull; diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Person.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Person.java new file mode 100644 index 0000000000..1e081f01da --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Person.java @@ -0,0 +1,98 @@ +package com.baeldung.spring.data.couchbase.model; + +import javax.validation.constraints.NotNull; + +import org.joda.time.DateTime; +import org.springframework.data.annotation.Id; +import org.springframework.data.couchbase.core.mapping.Document; + +import com.couchbase.client.java.repository.annotation.Field; + +@Document +public class Person { + + @Id + private String id; + @Field + @NotNull + private String firstName; + @Field + @NotNull + private String lastName; + @Field + @NotNull + private DateTime created; + @Field + private DateTime updated; + + public Person(String id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public String getId() { + return id; + } + + public void setId(String 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 DateTime getCreated() { + return created; + } + + public void setCreated(DateTime created) { + this.created = created; + } + + public DateTime getUpdated() { + return updated; + } + + public void setUpdated(DateTime updated) { + this.updated = updated; + } + + @Override + public int hashCode() { + int hash = 1; + if (id != null) { + hash = hash * 31 + id.hashCode(); + } + if (firstName != null) { + hash = hash * 31 + firstName.hashCode(); + } + if (lastName != null) { + hash = hash * 31 + lastName.hashCode(); + } + return hash; + } + + @Override + public boolean equals(Object obj) { + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; + Person other = (Person) obj; + return this.hashCode() == other.hashCode(); + } +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Student.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Student.java new file mode 100644 index 0000000000..e979eca864 --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Student.java @@ -0,0 +1,127 @@ +package com.baeldung.spring.data.couchbase.model; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Past; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +import org.joda.time.DateTime; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; +import org.springframework.data.couchbase.core.mapping.Document; + +import com.couchbase.client.java.repository.annotation.Field; + +@Document +public class Student { + private static final String NAME_REGEX = "^[a-zA-Z .'-]+$"; + + @Id + private String id; + @Field + @NotNull + @Size(min = 1, max = 20) + @Pattern(regexp = NAME_REGEX) + private String firstName; + @Field + @NotNull + @Size(min = 1, max = 20) + @Pattern(regexp = NAME_REGEX) + private String lastName; + @Field + @Past + private DateTime dateOfBirth; + @Field + @NotNull + private DateTime created; + @Field + private DateTime updated; + @Version + private long version; + + public Student() { + } + + public Student(String id, String firstName, String lastName, DateTime dateOfBirth) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.dateOfBirth = dateOfBirth; + } + + public String getId() { + return id; + } + + public void setId(String 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 DateTime getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(DateTime dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public DateTime getCreated() { + return created; + } + + public void setCreated(DateTime created) { + this.created = created; + } + + public DateTime getUpdated() { + return updated; + } + + public void setUpdated(DateTime updated) { + this.updated = updated; + } + + @Override + public int hashCode() { + int hash = 1; + if (id != null) { + hash = hash * 31 + id.hashCode(); + } + if (firstName != null) { + hash = hash * 31 + firstName.hashCode(); + } + if (lastName != null) { + hash = hash * 31 + lastName.hashCode(); + } + if (dateOfBirth != null) { + hash = hash * 31 + dateOfBirth.hashCode(); + } + return hash; + } + + @Override + public boolean equals(Object obj) { + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; + Student other = (Student) obj; + return this.hashCode() == other.hashCode(); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/CustomStudentRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/CustomStudentRepository.java new file mode 100644 index 0000000000..2aef524caf --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/CustomStudentRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.data.couchbase.repos; + +import java.util.List; + +import com.baeldung.spring.data.couchbase.model.Student; + +public interface CustomStudentRepository { + List findByFirstNameStartsWith(String s); +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java similarity index 85% rename from persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java index 751895502c..c4742ac44a 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java @@ -1,8 +1,8 @@ -package org.baeldung.spring.data.couchbase.repos; +package com.baeldung.spring.data.couchbase.repos; import java.util.List; -import org.baeldung.spring.data.couchbase.model.Student; +import com.baeldung.spring.data.couchbase.model.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.couchbase.core.CouchbaseTemplate; diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/PersonRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/PersonRepository.java new file mode 100644 index 0000000000..dc9a20ffa2 --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/PersonRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.data.couchbase.repos; + +import java.util.List; + +import com.baeldung.spring.data.couchbase.model.Person; +import org.springframework.data.repository.CrudRepository; + +public interface PersonRepository extends CrudRepository { + List findByFirstName(String firstName); + + List findByLastName(String lastName); +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/StudentRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/StudentRepository.java new file mode 100644 index 0000000000..7ea9433f21 --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/StudentRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.data.couchbase.repos; + +import java.util.List; + +import com.baeldung.spring.data.couchbase.model.Student; +import org.springframework.data.repository.CrudRepository; + +public interface StudentRepository extends CrudRepository, CustomStudentRepository { + List findByFirstName(String firstName); + + List findByLastName(String lastName); +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonRepositoryService.java similarity index 89% rename from persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonRepositoryService.java index 49548bdbfb..4051585e31 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonRepositoryService.java @@ -1,11 +1,11 @@ -package org.baeldung.spring.data.couchbase.service; +package com.baeldung.spring.data.couchbase.service; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.baeldung.spring.data.couchbase.model.Person; -import org.baeldung.spring.data.couchbase.repos.PersonRepository; +import com.baeldung.spring.data.couchbase.model.Person; +import com.baeldung.spring.data.couchbase.repos.PersonRepository; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonService.java new file mode 100644 index 0000000000..f321eba94e --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonService.java @@ -0,0 +1,22 @@ +package com.baeldung.spring.data.couchbase.service; + +import java.util.List; + +import com.baeldung.spring.data.couchbase.model.Person; + +public interface PersonService { + + Person findOne(String id); + + List findAll(); + + List findByFirstName(String firstName); + + List findByLastName(String lastName); + + void create(Person person); + + void update(Person person); + + void delete(Person person); +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonTemplateService.java similarity index 93% rename from persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonTemplateService.java index 8398847f65..5e49465a25 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonTemplateService.java @@ -1,8 +1,8 @@ -package org.baeldung.spring.data.couchbase.service; +package com.baeldung.spring.data.couchbase.service; import java.util.List; -import org.baeldung.spring.data.couchbase.model.Person; +import com.baeldung.spring.data.couchbase.model.Person; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentRepositoryService.java similarity index 89% rename from persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentRepositoryService.java index 65f5a6e78e..ff9657260a 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentRepositoryService.java @@ -1,11 +1,11 @@ -package org.baeldung.spring.data.couchbase.service; +package com.baeldung.spring.data.couchbase.service; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.baeldung.spring.data.couchbase.model.Student; -import org.baeldung.spring.data.couchbase.repos.StudentRepository; +import com.baeldung.spring.data.couchbase.model.Student; +import com.baeldung.spring.data.couchbase.repos.StudentRepository; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentService.java new file mode 100644 index 0000000000..aa99a770cd --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentService.java @@ -0,0 +1,22 @@ +package com.baeldung.spring.data.couchbase.service; + +import java.util.List; + +import com.baeldung.spring.data.couchbase.model.Student; + +public interface StudentService { + + Student findOne(String id); + + List findAll(); + + List findByFirstName(String firstName); + + List findByLastName(String lastName); + + void create(Student student); + + void update(Student student); + + void delete(Student student); +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentTemplateService.java similarity index 93% rename from persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentTemplateService.java index 8d1292b5e4..9110f68276 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentTemplateService.java @@ -1,8 +1,8 @@ -package org.baeldung.spring.data.couchbase.service; +package com.baeldung.spring.data.couchbase.service; import java.util.List; -import org.baeldung.spring.data.couchbase.model.Student; +import com.baeldung.spring.data.couchbase.model.Student; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/repos/CampusRepository.java similarity index 85% rename from persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/repos/CampusRepository.java index b1857222c5..1120b7c55d 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/repos/CampusRepository.java @@ -1,8 +1,8 @@ -package org.baeldung.spring.data.couchbase2b.repos; +package com.baeldung.spring.data.couchbase2b.repos; import java.util.Set; -import org.baeldung.spring.data.couchbase.model.Campus; +import com.baeldung.spring.data.couchbase.model.Campus; import org.springframework.data.couchbase.core.query.Dimensional; import org.springframework.data.couchbase.core.query.View; import org.springframework.data.geo.Distance; diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/repos/PersonRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/repos/PersonRepository.java new file mode 100644 index 0000000000..ec50dec471 --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/repos/PersonRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.data.couchbase2b.repos; + +import java.util.List; + +import com.baeldung.spring.data.couchbase.model.Person; +import org.springframework.data.repository.CrudRepository; + +public interface PersonRepository extends CrudRepository { + List findByFirstName(String firstName); + + List findByLastName(String lastName); +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/repos/StudentRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/repos/StudentRepository.java new file mode 100644 index 0000000000..3fd4a717f9 --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/repos/StudentRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.data.couchbase2b.repos; + +import java.util.List; + +import com.baeldung.spring.data.couchbase.model.Student; +import org.springframework.data.repository.CrudRepository; + +public interface StudentRepository extends CrudRepository { + List findByFirstName(String firstName); + + List findByLastName(String lastName); +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusService.java similarity index 75% rename from persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusService.java index 58f00dda25..567ffa2a7f 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusService.java @@ -1,8 +1,8 @@ -package org.baeldung.spring.data.couchbase2b.service; +package com.baeldung.spring.data.couchbase2b.service; import java.util.Set; -import org.baeldung.spring.data.couchbase.model.Campus; +import com.baeldung.spring.data.couchbase.model.Campus; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java similarity index 87% rename from persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java index 586f5f0dc1..03e2dced1b 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java @@ -1,11 +1,11 @@ -package org.baeldung.spring.data.couchbase2b.service; +package com.baeldung.spring.data.couchbase2b.service; import java.util.HashSet; import java.util.Iterator; import java.util.Set; -import org.baeldung.spring.data.couchbase.model.Campus; -import org.baeldung.spring.data.couchbase2b.repos.CampusRepository; +import com.baeldung.spring.data.couchbase2b.repos.CampusRepository; +import com.baeldung.spring.data.couchbase.model.Campus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonService.java new file mode 100644 index 0000000000..7dc30ead11 --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonService.java @@ -0,0 +1,22 @@ +package com.baeldung.spring.data.couchbase2b.service; + +import java.util.List; + +import com.baeldung.spring.data.couchbase.model.Person; + +public interface PersonService { + + Person findOne(String id); + + List findAll(); + + List findByFirstName(String firstName); + + List findByLastName(String lastName); + + void create(Person person); + + void update(Person person); + + void delete(Person person); +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java new file mode 100644 index 0000000000..af08bd4ca8 --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java @@ -0,0 +1,57 @@ +package com.baeldung.spring.data.couchbase2b.service; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import com.baeldung.spring.data.couchbase2b.repos.PersonRepository; +import com.baeldung.spring.data.couchbase.model.Person; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class PersonServiceImpl implements PersonService { + + private PersonRepository repo; + + @Autowired + public void setPersonRepository(PersonRepository repo) { + this.repo = repo; + } + + public Person findOne(String id) { + return repo.findOne(id); + } + + public List findAll() { + List people = new ArrayList(); + Iterator it = repo.findAll().iterator(); + while (it.hasNext()) { + people.add(it.next()); + } + return people; + } + + public List findByFirstName(String firstName) { + return repo.findByFirstName(firstName); + } + + public List findByLastName(String lastName) { + return repo.findByLastName(lastName); + } + + public void create(Person person) { + person.setCreated(DateTime.now()); + repo.save(person); + } + + public void update(Person person) { + person.setUpdated(DateTime.now()); + repo.save(person); + } + + public void delete(Person person) { + repo.delete(person); + } +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentService.java new file mode 100644 index 0000000000..3f318e1af1 --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentService.java @@ -0,0 +1,22 @@ +package com.baeldung.spring.data.couchbase2b.service; + +import java.util.List; + +import com.baeldung.spring.data.couchbase.model.Student; + +public interface StudentService { + + Student findOne(String id); + + List findAll(); + + List findByFirstName(String firstName); + + List findByLastName(String lastName); + + void create(Student student); + + void update(Student student); + + void delete(Student student); +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java new file mode 100644 index 0000000000..53feaead10 --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java @@ -0,0 +1,57 @@ +package com.baeldung.spring.data.couchbase2b.service; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import com.baeldung.spring.data.couchbase2b.repos.StudentRepository; +import com.baeldung.spring.data.couchbase.model.Student; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class StudentServiceImpl implements StudentService { + + private StudentRepository repo; + + @Autowired + public void setStudentRepository(StudentRepository repo) { + this.repo = repo; + } + + public Student findOne(String id) { + return repo.findOne(id); + } + + public List findAll() { + List people = new ArrayList(); + Iterator it = repo.findAll().iterator(); + while (it.hasNext()) { + people.add(it.next()); + } + return people; + } + + public List findByFirstName(String firstName) { + return repo.findByFirstName(firstName); + } + + public List findByLastName(String lastName) { + return repo.findByLastName(lastName); + } + + public void create(Student student) { + student.setCreated(DateTime.now()); + repo.save(student); + } + + public void update(Student student) { + student.setUpdated(DateTime.now()); + repo.save(student); + } + + public void delete(Student student) { + repo.delete(student); + } +} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java deleted file mode 100644 index fd41427d20..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.baeldung.spring.data.couchbase.model; - -import javax.validation.constraints.NotNull; - -import org.joda.time.DateTime; -import org.springframework.data.annotation.Id; -import org.springframework.data.couchbase.core.mapping.Document; - -import com.couchbase.client.java.repository.annotation.Field; - -@Document -public class Person { - - @Id - private String id; - @Field - @NotNull - private String firstName; - @Field - @NotNull - private String lastName; - @Field - @NotNull - private DateTime created; - @Field - private DateTime updated; - - public Person(String id, String firstName, String lastName) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - } - - public String getId() { - return id; - } - - public void setId(String 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 DateTime getCreated() { - return created; - } - - public void setCreated(DateTime created) { - this.created = created; - } - - public DateTime getUpdated() { - return updated; - } - - public void setUpdated(DateTime updated) { - this.updated = updated; - } - - @Override - public int hashCode() { - int hash = 1; - if (id != null) { - hash = hash * 31 + id.hashCode(); - } - if (firstName != null) { - hash = hash * 31 + firstName.hashCode(); - } - if (lastName != null) { - hash = hash * 31 + lastName.hashCode(); - } - return hash; - } - - @Override - public boolean equals(Object obj) { - if ((obj == null) || (obj.getClass() != this.getClass())) - return false; - if (obj == this) - return true; - Person other = (Person) obj; - return this.hashCode() == other.hashCode(); - } -} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java deleted file mode 100644 index 726ed2347e..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.baeldung.spring.data.couchbase.model; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Past; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; - -import org.joda.time.DateTime; -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.Version; -import org.springframework.data.couchbase.core.mapping.Document; - -import com.couchbase.client.java.repository.annotation.Field; - -@Document -public class Student { - private static final String NAME_REGEX = "^[a-zA-Z .'-]+$"; - - @Id - private String id; - @Field - @NotNull - @Size(min = 1, max = 20) - @Pattern(regexp = NAME_REGEX) - private String firstName; - @Field - @NotNull - @Size(min = 1, max = 20) - @Pattern(regexp = NAME_REGEX) - private String lastName; - @Field - @Past - private DateTime dateOfBirth; - @Field - @NotNull - private DateTime created; - @Field - private DateTime updated; - @Version - private long version; - - public Student() { - } - - public Student(String id, String firstName, String lastName, DateTime dateOfBirth) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - this.dateOfBirth = dateOfBirth; - } - - public String getId() { - return id; - } - - public void setId(String 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 DateTime getDateOfBirth() { - return dateOfBirth; - } - - public void setDateOfBirth(DateTime dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } - - public DateTime getCreated() { - return created; - } - - public void setCreated(DateTime created) { - this.created = created; - } - - public DateTime getUpdated() { - return updated; - } - - public void setUpdated(DateTime updated) { - this.updated = updated; - } - - @Override - public int hashCode() { - int hash = 1; - if (id != null) { - hash = hash * 31 + id.hashCode(); - } - if (firstName != null) { - hash = hash * 31 + firstName.hashCode(); - } - if (lastName != null) { - hash = hash * 31 + lastName.hashCode(); - } - if (dateOfBirth != null) { - hash = hash * 31 + dateOfBirth.hashCode(); - } - return hash; - } - - @Override - public boolean equals(Object obj) { - if ((obj == null) || (obj.getClass() != this.getClass())) - return false; - if (obj == this) - return true; - Student other = (Student) obj; - return this.hashCode() == other.hashCode(); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepository.java deleted file mode 100644 index 9a5bf21492..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.spring.data.couchbase.repos; - -import java.util.List; - -import org.baeldung.spring.data.couchbase.model.Student; - -public interface CustomStudentRepository { - List findByFirstNameStartsWith(String s); -} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java deleted file mode 100644 index 717feb858f..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.spring.data.couchbase.repos; - -import java.util.List; - -import org.baeldung.spring.data.couchbase.model.Person; -import org.springframework.data.repository.CrudRepository; - -public interface PersonRepository extends CrudRepository { - List findByFirstName(String firstName); - - List findByLastName(String lastName); -} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java deleted file mode 100644 index 9bbdeec642..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.spring.data.couchbase.repos; - -import java.util.List; - -import org.baeldung.spring.data.couchbase.model.Student; -import org.springframework.data.repository.CrudRepository; - -public interface StudentRepository extends CrudRepository, CustomStudentRepository { - List findByFirstName(String firstName); - - List findByLastName(String lastName); -} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java deleted file mode 100644 index a823908b01..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.spring.data.couchbase.service; - -import java.util.List; - -import org.baeldung.spring.data.couchbase.model.Person; - -public interface PersonService { - - Person findOne(String id); - - List findAll(); - - List findByFirstName(String firstName); - - List findByLastName(String lastName); - - void create(Person person); - - void update(Person person); - - void delete(Person person); -} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java deleted file mode 100644 index f483ef0fb6..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.spring.data.couchbase.service; - -import java.util.List; - -import org.baeldung.spring.data.couchbase.model.Student; - -public interface StudentService { - - Student findOne(String id); - - List findAll(); - - List findByFirstName(String firstName); - - List findByLastName(String lastName); - - void create(Student student); - - void update(Student student); - - void delete(Student student); -} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java deleted file mode 100644 index ef37106c6d..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.spring.data.couchbase2b.repos; - -import java.util.List; - -import org.baeldung.spring.data.couchbase.model.Person; -import org.springframework.data.repository.CrudRepository; - -public interface PersonRepository extends CrudRepository { - List findByFirstName(String firstName); - - List findByLastName(String lastName); -} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java deleted file mode 100644 index 0d790d2f39..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.spring.data.couchbase2b.repos; - -import java.util.List; - -import org.baeldung.spring.data.couchbase.model.Student; -import org.springframework.data.repository.CrudRepository; - -public interface StudentRepository extends CrudRepository { - List findByFirstName(String firstName); - - List findByLastName(String lastName); -} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java deleted file mode 100644 index c2c96ffb9c..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.spring.data.couchbase2b.service; - -import java.util.List; - -import org.baeldung.spring.data.couchbase.model.Person; - -public interface PersonService { - - Person findOne(String id); - - List findAll(); - - List findByFirstName(String firstName); - - List findByLastName(String lastName); - - void create(Person person); - - void update(Person person); - - void delete(Person person); -} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java deleted file mode 100644 index fe0a9e48cd..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.baeldung.spring.data.couchbase2b.service; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.baeldung.spring.data.couchbase.model.Person; -import org.baeldung.spring.data.couchbase2b.repos.PersonRepository; -import org.joda.time.DateTime; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class PersonServiceImpl implements PersonService { - - private PersonRepository repo; - - @Autowired - public void setPersonRepository(PersonRepository repo) { - this.repo = repo; - } - - public Person findOne(String id) { - return repo.findOne(id); - } - - public List findAll() { - List people = new ArrayList(); - Iterator it = repo.findAll().iterator(); - while (it.hasNext()) { - people.add(it.next()); - } - return people; - } - - public List findByFirstName(String firstName) { - return repo.findByFirstName(firstName); - } - - public List findByLastName(String lastName) { - return repo.findByLastName(lastName); - } - - public void create(Person person) { - person.setCreated(DateTime.now()); - repo.save(person); - } - - public void update(Person person) { - person.setUpdated(DateTime.now()); - repo.save(person); - } - - public void delete(Person person) { - repo.delete(person); - } -} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java deleted file mode 100644 index 5b83b403bb..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.spring.data.couchbase2b.service; - -import java.util.List; - -import org.baeldung.spring.data.couchbase.model.Student; - -public interface StudentService { - - Student findOne(String id); - - List findAll(); - - List findByFirstName(String firstName); - - List findByLastName(String lastName); - - void create(Student student); - - void update(Student student); - - void delete(Student student); -} diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java deleted file mode 100644 index 248d824081..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.baeldung.spring.data.couchbase2b.service; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.baeldung.spring.data.couchbase.model.Student; -import org.baeldung.spring.data.couchbase2b.repos.StudentRepository; -import org.joda.time.DateTime; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class StudentServiceImpl implements StudentService { - - private StudentRepository repo; - - @Autowired - public void setStudentRepository(StudentRepository repo) { - this.repo = repo; - } - - public Student findOne(String id) { - return repo.findOne(id); - } - - public List findAll() { - List people = new ArrayList(); - Iterator it = repo.findAll().iterator(); - while (it.hasNext()) { - people.add(it.next()); - } - return people; - } - - public List findByFirstName(String firstName) { - return repo.findByFirstName(firstName); - } - - public List findByLastName(String lastName) { - return repo.findByLastName(lastName); - } - - public void create(Student student) { - student.setCreated(DateTime.now()); - repo.save(student); - } - - public void update(Student student) { - student.setUpdated(DateTime.now()); - repo.save(student); - } - - public void delete(Student student) { - repo.delete(student); - } -} diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/SpringContextLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..553520e6e6 --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,59 @@ +package com.baeldung; + +import com.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; +import com.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTestConfig; +import org.junit.Test; +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; + +/** + * This LiveTest requires: + * + * 1- Couchbase instance running (e.g. with `docker run -d --name db -p 8091-8096:8091-8096 -p 11210-11211:11210-11211 couchbase`) + * + * + * 2- Couchbase configured with (we can use the console in localhost:8091): + * + * 2.1- Buckets: named 'baeldung' and 'baeldung2' + * + * 2.2- Security: users 'baeldung' and 'baeldung2'. Note: in newer versions an empty password is not allowed, then we have to change the passwords in the project) + * + * 2.3- Spacial View: Add new spacial view (in Index tab) in document 'campus_spatial', view 'byLocation' with the following function: + * {@code + * function (doc) { + * if (doc.location && + * doc._class == "com.baeldung.spring.data.couchbase.model.Campus") { + * emit([doc.location.x, doc.location.y], null); + * } + * }} + * + * 2.4- MapReduce Views: Add new views in document 'campus': + * 2.4.1- view 'all' with function: + * {@code + * function (doc, meta) { + * if(doc._class == "com.baeldung.spring.data.couchbase.model.Campus") { + * emit(meta.id, null); + * } + * }} + * + * 2.4.2- view 'byName' with function: + * {@code + * function (doc, meta) { + * if(doc._class == "com.baeldung.spring.data.couchbase.model.Campus" && + * doc.name) { + * emit(doc.name, null); + * } + * }} + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MultiBucketCouchbaseConfig.class, MultiBucketIntegrationTestConfig.class }) +@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java similarity index 86% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java index 0e2e8d5dd3..403c012194 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase; +package com.baeldung.spring.data.couchbase; import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/IntegrationTest.java similarity index 92% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/IntegrationTest.java index ce2daa92cd..df2802a15c 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/IntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase; +package com.baeldung.spring.data.couchbase; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/IntegrationTestConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/IntegrationTestConfig.java new file mode 100644 index 0000000000..6abb879236 --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/IntegrationTestConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.data.couchbase; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = "com.baeldung.spring.data.couchbase") +public class IntegrationTestConfig { +} diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/MyCouchbaseConfig.java similarity index 93% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/MyCouchbaseConfig.java index a37e918101..5a2180f4b8 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/MyCouchbaseConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase; +package com.baeldung.spring.data.couchbase; import java.util.Arrays; import java.util.List; @@ -12,7 +12,7 @@ import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepos import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; @Configuration -@EnableCouchbaseRepositories(basePackages = { "org.baeldung.spring.data.couchbase" }) +@EnableCouchbaseRepositories(basePackages = { "com.baeldung.spring.data.couchbase" }) public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration { public static final List NODE_LIST = Arrays.asList("localhost"); diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java similarity index 85% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java index b4a372487e..b989bb39d8 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase; +package com.baeldung.spring.data.couchbase; import org.springframework.data.couchbase.core.query.Consistency; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonRepositoryServiceLiveTest.java similarity index 87% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceLiveTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonRepositoryServiceLiveTest.java index 899c21691d..ee3716030f 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonRepositoryServiceLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package com.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonServiceLiveTest.java similarity index 95% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceLiveTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonServiceLiveTest.java index 08d641dc2c..804bbdd2c8 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonServiceLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package com.baeldung.spring.data.couchbase.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -7,9 +7,9 @@ import static org.junit.Assert.assertTrue; import java.util.List; -import org.baeldung.spring.data.couchbase.IntegrationTest; -import org.baeldung.spring.data.couchbase.MyCouchbaseConfig; -import org.baeldung.spring.data.couchbase.model.Person; +import com.baeldung.spring.data.couchbase.IntegrationTest; +import com.baeldung.spring.data.couchbase.MyCouchbaseConfig; +import com.baeldung.spring.data.couchbase.model.Person; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonTemplateServiceLiveTest.java similarity index 87% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceLiveTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonTemplateServiceLiveTest.java index 3bc99d28df..a665fd756d 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonTemplateServiceLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package com.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentRepositoryServiceLiveTest.java similarity index 87% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceLiveTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentRepositoryServiceLiveTest.java index 162619db3e..9abf93b003 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentRepositoryServiceLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package com.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentServiceLiveTest.java similarity index 96% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceLiveTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentServiceLiveTest.java index 6a18922007..c13b4930ca 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentServiceLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package com.baeldung.spring.data.couchbase.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -9,9 +9,9 @@ import java.util.List; import javax.validation.ConstraintViolationException; -import org.baeldung.spring.data.couchbase.IntegrationTest; -import org.baeldung.spring.data.couchbase.MyCouchbaseConfig; -import org.baeldung.spring.data.couchbase.model.Student; +import com.baeldung.spring.data.couchbase.IntegrationTest; +import com.baeldung.spring.data.couchbase.MyCouchbaseConfig; +import com.baeldung.spring.data.couchbase.model.Student; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentTemplateServiceLiveTest.java similarity index 87% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceLiveTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentTemplateServiceLiveTest.java index c666e004af..92a4a23baf 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentTemplateServiceLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package com.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java similarity index 93% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java index fe32305feb..488819aaf5 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java @@ -1,9 +1,9 @@ -package org.baeldung.spring.data.couchbase2b; +package com.baeldung.spring.data.couchbase2b; import java.util.Arrays; import java.util.List; -import org.baeldung.spring.data.couchbase.model.Campus; +import com.baeldung.spring.data.couchbase.model.Campus; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration; @@ -17,7 +17,7 @@ import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import com.couchbase.client.java.Bucket; @Configuration -@EnableCouchbaseRepositories(basePackages = { "org.baeldung.spring.data.couchbase2b" }) +@EnableCouchbaseRepositories(basePackages = { "com.baeldung.spring.data.couchbase2b" }) public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration { public static final List NODE_LIST = Arrays.asList("localhost"); diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java new file mode 100644 index 0000000000..c082a0d77c --- /dev/null +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.data.couchbase2b; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = { "com.baeldung.spring.data.couchbase2b" }) +public class MultiBucketIntegrationTestConfig { + +} diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketLiveTest.java similarity index 92% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketLiveTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketLiveTest.java index 3b406a851e..334af40866 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase2b; +package com.baeldung.spring.data.couchbase2b; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImplLiveTest.java similarity index 94% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplLiveTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImplLiveTest.java index 5e7a12f292..e94c09e6cd 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImplLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase2b.service; +package com.baeldung.spring.data.couchbase2b.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -9,9 +9,9 @@ import java.util.Set; import javax.annotation.PostConstruct; -import org.baeldung.spring.data.couchbase.model.Campus; -import org.baeldung.spring.data.couchbase2b.MultiBucketLiveTest; -import org.baeldung.spring.data.couchbase2b.repos.CampusRepository; +import com.baeldung.spring.data.couchbase.model.Campus; +import com.baeldung.spring.data.couchbase2b.MultiBucketLiveTest; +import com.baeldung.spring.data.couchbase2b.repos.CampusRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.geo.Distance; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImplLiveTest.java similarity index 95% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplLiveTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImplLiveTest.java index 9543d8fe12..3f98c1950a 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImplLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase2b.service; +package com.baeldung.spring.data.couchbase2b.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -7,9 +7,9 @@ import static org.junit.Assert.assertTrue; 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.MultiBucketLiveTest; +import com.baeldung.spring.data.couchbase.model.Person; +import com.baeldung.spring.data.couchbase2b.MultiBucketLiveTest; +import com.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImplLiveTest.java similarity index 96% rename from persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplLiveTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImplLiveTest.java index 52b9113e8f..004258a37e 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImplLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase2b.service; +package com.baeldung.spring.data.couchbase2b.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -9,9 +9,9 @@ import java.util.List; 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.MultiBucketLiveTest; +import com.baeldung.spring.data.couchbase.model.Student; +import com.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; +import com.baeldung.spring.data.couchbase2b.MultiBucketLiveTest; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index 5e20a98a1d..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; -import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTestConfig; -import org.junit.Test; -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; - -/** - * This LiveTest requires: - * - * 1- Couchbase instance running (e.g. with `docker run -d --name db -p 8091-8096:8091-8096 -p 11210-11211:11210-11211 couchbase`) - * - * - * 2- Couchbase configured with (we can use the console in localhost:8091): - * - * 2.1- Buckets: named 'baeldung' and 'baeldung2' - * - * 2.2- Security: users 'baeldung' and 'baeldung2'. Note: in newer versions an empty password is not allowed, then we have to change the passwords in the project) - * - * 2.3- Spacial View: Add new spacial view (in Index tab) in document 'campus_spatial', view 'byLocation' with the following function: - * {@code - * function (doc) { - * if (doc.location && - * doc._class == "org.baeldung.spring.data.couchbase.model.Campus") { - * emit([doc.location.x, doc.location.y], null); - * } - * }} - * - * 2.4- MapReduce Views: Add new views in document 'campus': - * 2.4.1- view 'all' with function: - * {@code - * function (doc, meta) { - * if(doc._class == "org.baeldung.spring.data.couchbase.model.Campus") { - * emit(meta.id, null); - * } - * }} - * - * 2.4.2- view 'byName' with function: - * {@code - * function (doc, meta) { - * if(doc._class == "org.baeldung.spring.data.couchbase.model.Campus" && - * doc.name) { - * emit(doc.name, null); - * } - * }} - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MultiBucketCouchbaseConfig.class, MultiBucketIntegrationTestConfig.class }) -@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java deleted file mode 100644 index 6f040c34db..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.spring.data.couchbase; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan(basePackages = "org.baeldung.spring.data.couchbase") -public class IntegrationTestConfig { -} diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java deleted file mode 100644 index 94a95b06bb..0000000000 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.spring.data.couchbase2b; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan(basePackages = { "org.baeldung.spring.data.couchbase2b" }) -public class MultiBucketIntegrationTestConfig { - -} diff --git a/persistence-modules/spring-data-dynamodb/pom.xml b/persistence-modules/spring-data-dynamodb/pom.xml index 7b936817d1..377e35b635 100644 --- a/persistence-modules/spring-data-dynamodb/pom.xml +++ b/persistence-modules/spring-data-dynamodb/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -19,7 +19,7 @@ org.springframework.data spring-data-releasetrain - Hopper-SR10 + Lovelace-SR16 pom import @@ -138,18 +138,25 @@ - spring-data-dynamodb - - - src/main/resources - true - - - org.apache.maven.plugins - maven-war-plugin + maven-dependency-plugin + ${maven-dependency-plugin.version} + + + copy-dependencies + test-compile + + copy-dependencies + + + test + so,dll,dylib + ${project.basedir}/native-libs + + + @@ -167,13 +174,14 @@ com.baeldung.Application 4.3.4.RELEASE 4.5.2 - 4.4.1 + 5.1.0 1.11.64 3.3.7-1 1.0.392 1.11.106 1.11.86 https://s3-us-west-2.amazonaws.com/dynamodb-local/release + 3.1.1 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 9278c0a12e..7e97e6b383 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 @@ -44,8 +44,8 @@ public class DynamoDBConfig { return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey); } - @Bean(name = "mvcHandlerMappingIntrospector") - public HandlerMappingIntrospector mvcHandlerMappingIntrospector() { + @Bean(name = "mvcHandlerMappingIntrospectorCustom") + public HandlerMappingIntrospector mvcHandlerMappingIntrospectorCustom() { return new HandlerMappingIntrospector(context); } } diff --git a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java index da47f033b6..6e8b493c3b 100644 --- a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java +++ b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java @@ -1,12 +1,13 @@ package com.baeldung.spring.data.dynamodb.repositories; -import com.baeldung.spring.data.dynamodb.model.ProductInfo; +import java.util.Optional; + import org.socialsignin.spring.data.dynamodb.repository.EnableScan; import org.springframework.data.repository.CrudRepository; -import java.util.List; +import com.baeldung.spring.data.dynamodb.model.ProductInfo; @EnableScan public interface ProductInfoRepository extends CrudRepository { - List findById(String id); + Optional findById(String id); } diff --git a/persistence-modules/spring-data-dynamodb/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-dynamodb/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3ad54e2267 --- /dev/null +++ b/persistence-modules/spring-data-dynamodb/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 5e68a8e64f..0000000000 --- a/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-eclipselink/README.md b/persistence-modules/spring-data-eclipselink/README.md index 3bad63d7ef..2056031c45 100644 --- a/persistence-modules/spring-data-eclipselink/README.md +++ b/persistence-modules/spring-data-eclipselink/README.md @@ -4,5 +4,5 @@ This module contains articles about Spring Data with EclipseLink. ### Relevant articles -- [A Guide to EclipseLink with Spring](http://www.baeldung.com/spring-eclipselink) +- [A Guide to EclipseLink with Spring](https://www.baeldung.com/spring-eclipselink) - [Pessimistic Locking in JPA](https://www.baeldung.com/jpa-pessimistic-locking) diff --git a/persistence-modules/spring-data-eclipselink/pom.xml b/persistence-modules/spring-data-eclipselink/pom.xml index bb596d4a8a..4ae43de07a 100644 --- a/persistence-modules/spring-data-eclipselink/pom.xml +++ b/persistence-modules/spring-data-eclipselink/pom.xml @@ -7,9 +7,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..842c61ffbd --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.eclipselink.springdata.EclipselinkSpringDataApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = EclipselinkSpringDataApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 4c69245f65..0000000000 --- a/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.eclipselink.springdata.EclipselinkSpringDataApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = EclipselinkSpringDataApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-elasticsearch/README.md b/persistence-modules/spring-data-elasticsearch/README.md index 840db617f6..22126c2f00 100644 --- a/persistence-modules/spring-data-elasticsearch/README.md +++ b/persistence-modules/spring-data-elasticsearch/README.md @@ -1,11 +1,11 @@ ## Spring Data Elasticsearch ### Relevant Articles: -- [Introduction to Spring Data Elasticsearch](http://www.baeldung.com/spring-data-elasticsearch-tutorial) -- [Elasticsearch Queries with Spring Data](http://www.baeldung.com/spring-data-elasticsearch-queries) -- [Guide to Elasticsearch in Java](http://www.baeldung.com/elasticsearch-java) -- [Geospatial Support in ElasticSearch](http://www.baeldung.com/elasticsearch-geo-spatial) -- [A Simple Tagging Implementation with Elasticsearch](http://www.baeldung.com/elasticsearch-tagging) +- [Introduction to Spring Data Elasticsearch](https://www.baeldung.com/spring-data-elasticsearch-tutorial) +- [Elasticsearch Queries with Spring Data](https://www.baeldung.com/spring-data-elasticsearch-queries) +- [Guide to Elasticsearch in Java](https://www.baeldung.com/elasticsearch-java) +- [Geospatial Support in ElasticSearch](https://www.baeldung.com/elasticsearch-geo-spatial) +- [A Simple Tagging Implementation with Elasticsearch](https://www.baeldung.com/elasticsearch-tagging) ### Build the Project with Tests Running ``` diff --git a/persistence-modules/spring-data-elasticsearch/pom.xml b/persistence-modules/spring-data-elasticsearch/pom.xml index ccd2f94e59..3446528323 100644 --- a/persistence-modules/spring-data-elasticsearch/pom.xml +++ b/persistence-modules/spring-data-elasticsearch/pom.xml @@ -2,7 +2,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-data-elasticsearch - 0.0.1-SNAPSHOT spring-data-elasticsearch jar @@ -89,8 +88,6 @@ - 1.8 - 1.8 3.0.8.RELEASE 4.5.2 5.6.0 diff --git a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/SpringContextManualTest.java b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/SpringContextManualTest.java new file mode 100644 index 0000000000..c69deeb77c --- /dev/null +++ b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/SpringContextManualTest.java @@ -0,0 +1,23 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.es.config.Config; + +/** + * + * This Manual test requires: + * * Elasticsearch instance running on host + * + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = Config.class) +public class SpringContextManualTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextManualTest.java b/persistence-modules/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextManualTest.java deleted file mode 100644 index c6f095eae9..0000000000 --- a/persistence-modules/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextManualTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.spring.data.es.config.Config; - -/** - * - * This Manual test requires: - * * Elasticsearch instance running on host - * - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = Config.class) -public class SpringContextManualTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-gemfire/README.md b/persistence-modules/spring-data-gemfire/README.md index 78199e90d0..4eb28c1678 100644 --- a/persistence-modules/spring-data-gemfire/README.md +++ b/persistence-modules/spring-data-gemfire/README.md @@ -1,3 +1,3 @@ ### Relevant articles -- [A Guide to GemFire with Spring Data](http://www.baeldung.com/spring-data-gemfire) +- [A Guide to GemFire with Spring Data](https://www.baeldung.com/spring-data-gemfire) diff --git a/persistence-modules/spring-data-gemfire/pom.xml b/persistence-modules/spring-data-gemfire/pom.xml index 6bd689192c..a0cc4d5360 100644 --- a/persistence-modules/spring-data-gemfire/pom.xml +++ b/persistence-modules/spring-data-gemfire/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ diff --git a/persistence-modules/spring-data-gemfire/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-gemfire/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..53ab8800d9 --- /dev/null +++ b/persistence-modules/spring-data-gemfire/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.data.gemfire.function.GemfireConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes=GemfireConfiguration.class, loader=AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 3772e22137..0000000000 --- a/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.spring.data.gemfire.function.GemfireConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes=GemfireConfiguration.class, loader=AnnotationConfigContextLoader.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-geode/pom.xml b/persistence-modules/spring-data-geode/pom.xml index 2a9cbe35e9..557d09376a 100644 --- a/persistence-modules/spring-data-geode/pom.xml +++ b/persistence-modules/spring-data-geode/pom.xml @@ -9,16 +9,15 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ org.springframework.boot spring-boot-starter - 2.1.9.RELEASE + ${spring.boot.starter.version} org.springframework.boot @@ -89,6 +88,7 @@ UTF-8 com.baeldung.springdatageode.app.ClientCacheApp 1.1.1.RELEASE + 2.1.9.RELEASE \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/pom.xml b/persistence-modules/spring-data-jpa-3/pom.xml index 8a949b3008..d02d089ba3 100644 --- a/persistence-modules/spring-data-jpa-3/pom.xml +++ b/persistence-modules/spring-data-jpa-3/pom.xml @@ -52,34 +52,6 @@ runtime - - - org.springframework.boot - spring-boot-starter-test - test - - - junit - junit - - - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-launcher - test - - org.testcontainers @@ -94,9 +66,6 @@ 1.4.1 21.0 1.12.2 - 42.2.8 - 1.12.2 - 1.4.200 diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java index 022099eed0..6ce9bcad45 100644 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java @@ -5,9 +5,9 @@ import java.util.List; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; -import com.baeldung.multipledb.model.product.ProductMultipleDB; +import com.baeldung.multipledb.model.product.Product; -public interface ProductRepository extends PagingAndSortingRepository { +public interface ProductRepository extends PagingAndSortingRepository { - List findAllByPrice(double price, Pageable pageable); + List findAllByPrice(double price, Pageable pageable); } diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java new file mode 100644 index 0000000000..eaf471043c --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java @@ -0,0 +1,67 @@ +package com.baeldung.multipledb.model.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(); + } + + private Product(int id, String name, double price) { + super(); + this.id = id; + this.name = name; + this.price = price; + } + + public static Product from(int id, String name, double price) { + return new Product(id, name, price); + } + + 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-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java deleted file mode 100644 index 8bdff340ac..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.multipledb.model.product; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(schema = "products") -public class ProductMultipleDB { - - @Id - private int id; - - private String name; - - private double price; - - public ProductMultipleDB() { - super(); - } - - private ProductMultipleDB(int id, String name, double price) { - super(); - this.id = id; - this.name = name; - this.price = price; - } - - public static ProductMultipleDB from(int id, String name, double price) { - return new ProductMultipleDB(id, name, price); - } - - 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-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java index 17ee6a94ba..b2581b8034 100644 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java +++ b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java @@ -266,7 +266,7 @@ public class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); assertThat(usersSortByName.get(0) .getName()).isEqualTo(USER_NAME_ADAM); @@ -278,7 +278,7 @@ public class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java index cdbb307d7f..831790af95 100644 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; import com.baeldung.multipledb.dao.product.ProductRepository; -import com.baeldung.multipledb.model.product.ProductMultipleDB; +import com.baeldung.multipledb.model.product.Product; @RunWith(SpringRunner.class) @SpringBootTest(classes=MultipleDbApplication.class) @@ -36,22 +36,22 @@ public class ProductRepositoryIntegrationTest { @Before @Transactional("productTransactionManager") public void setUp() { - productRepository.save(ProductMultipleDB.from(1001, "Book", 21)); - productRepository.save(ProductMultipleDB.from(1002, "Coffee", 10)); - productRepository.save(ProductMultipleDB.from(1003, "Jeans", 30)); - productRepository.save(ProductMultipleDB.from(1004, "Shirt", 32)); - productRepository.save(ProductMultipleDB.from(1005, "Bacon", 10)); + productRepository.save(Product.from(1001, "Book", 21)); + productRepository.save(Product.from(1002, "Coffee", 10)); + productRepository.save(Product.from(1003, "Jeans", 30)); + productRepository.save(Product.from(1004, "Shirt", 32)); + productRepository.save(Product.from(1005, "Bacon", 10)); } @Test public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { Pageable pageRequest = PageRequest.of(0, 2); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(2)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1001, 1002) .contains(id))); } @@ -60,11 +60,11 @@ public class ProductRepositoryIntegrationTest { public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { Pageable pageRequest = PageRequest.of(1, 2); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(2)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1003, 1004) .contains(id))); } @@ -73,11 +73,11 @@ public class ProductRepositoryIntegrationTest { public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { Pageable pageRequest = PageRequest.of(2, 2); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(1)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1005) .contains(id))); } @@ -86,12 +86,12 @@ public class ProductRepositoryIntegrationTest { public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(3)); assertThat(result.getContent() .stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002))); } @@ -101,12 +101,12 @@ public class ProductRepositoryIntegrationTest { Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") .descending()); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(3)); assertThat(result.getContent() .stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001))); } @@ -117,12 +117,12 @@ public class ProductRepositoryIntegrationTest { .descending() .and(Sort.by("name"))); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(5)); assertThat(result.getContent() .stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002))); } @@ -131,11 +131,11 @@ public class ProductRepositoryIntegrationTest { public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { Pageable pageRequest = PageRequest.of(0, 2); - List result = productRepository.findAllByPrice(10, pageRequest); + List result = productRepository.findAllByPrice(10, pageRequest); assertThat(result, hasSize(2)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1002, 1005) .contains(id))); } diff --git a/persistence-modules/spring-data-jpa-4/README.md b/persistence-modules/spring-data-jpa-4/README.md index 63aec5c46b..085dfcb366 100644 --- a/persistence-modules/spring-data-jpa-4/README.md +++ b/persistence-modules/spring-data-jpa-4/README.md @@ -3,6 +3,10 @@ - [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) - [A Guide to Spring’s Open Session In View](https://www.baeldung.com/spring-open-session-in-view) - [Programmatic Transaction Management in Spring](https://www.baeldung.com/spring-programmatic-transaction-management) +- [JPA Entity Lifecycle Events](https://www.baeldung.com/jpa-entity-lifecycle-events) +- [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections) +- [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) +- [Custom Naming Convention with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-custom-naming) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-data-jpa-4/create.sql b/persistence-modules/spring-data-jpa-4/create.sql new file mode 100644 index 0000000000..1bbe1640a7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/create.sql @@ -0,0 +1,2 @@ +create table PERSON (ID int8 not null, FIRST_NAME varchar(255), LAST_NAME varchar(255), primary key (ID)) +create table person (id int8 not null, first_name varchar(255), last_name varchar(255), primary key (id)) diff --git a/persistence-modules/spring-data-jpa-4/pom.xml b/persistence-modules/spring-data-jpa-4/pom.xml index 44b7c3c268..71fc21527f 100644 --- a/persistence-modules/spring-data-jpa-4/pom.xml +++ b/persistence-modules/spring-data-jpa-4/pom.xml @@ -24,14 +24,23 @@ - com.h2database - h2 + org.springframework.boot + spring-boot-starter-data-jdbc - org.springframework.boot - spring-boot-starter-test - test + mysql + mysql-connector-java + + + + org.postgresql + postgresql + + + + com.h2database + h2 diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java new file mode 100644 index 0000000000..3f152a6ffc --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.elementcollection; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ElementCollectionApplication { + public static void main(String[] args) { + SpringApplication.run(ElementCollectionApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java new file mode 100644 index 0000000000..8b98164d63 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java @@ -0,0 +1,68 @@ +package com.baeldung.elementcollection.model; + +import javax.persistence.*; +import java.util.List; +import java.util.Objects; + +@Entity +public class Employee { + @Id + private int id; + private String name; + @ElementCollection + @CollectionTable(name = "employee_phone", joinColumns = @JoinColumn(name = "employee_id")) + private List phones; + + public Employee() { + } + + public Employee(int id) { + this.id = id; + } + + public Employee(int id, String name) { + 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 List getPhones() { + return phones; + } + + public void setPhones(List phones) { + this.phones = phones; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Employee)) { + return false; + } + Employee user = (Employee) o; + return getId() == user.getId(); + } + + @Override + public int hashCode() { + return Objects.hash(getId()); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java new file mode 100644 index 0000000000..d73d30c47a --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java @@ -0,0 +1,62 @@ +package com.baeldung.elementcollection.model; + +import javax.persistence.Embeddable; +import java.util.Objects; + +@Embeddable +public class Phone { + private String type; + private String areaCode; + private String number; + + public Phone() { + } + + public Phone(String type, String areaCode, String number) { + this.type = type; + this.areaCode = areaCode; + this.number = number; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getAreaCode() { + return areaCode; + } + + public void setAreaCode(String areaCode) { + this.areaCode = areaCode; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Phone)) { + return false; + } + Phone phone = (Phone) o; + return getType().equals(phone.getType()) && getAreaCode().equals(phone.getAreaCode()) + && getNumber().equals(phone.getNumber()); + } + + @Override + public int hashCode() { + return Objects.hash(getType(), getAreaCode(), getNumber()); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java new file mode 100644 index 0000000000..49180c35eb --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java @@ -0,0 +1,46 @@ +package com.baeldung.elementcollection.repository; + +import com.baeldung.elementcollection.model.Employee; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityGraph; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import java.util.HashMap; +import java.util.Map; + +@Repository +public class EmployeeRepository { + + @PersistenceContext + private EntityManager em; + + @Transactional + public void save(Employee employee) { + em.persist(employee); + } + + @Transactional + public void remove(int id) { + Employee employee = findById(id); + em.remove(employee); + } + + public Employee findById(int id) { + return em.find(Employee.class, id); + } + + public Employee findByJPQL(int id) { + return em.createQuery("SELECT u FROM Employee AS u JOIN FETCH u.phones WHERE u.id=:id", Employee.class) + .setParameter("id", id).getSingleResult(); + } + + public Employee findByEntityGraph(int id) { + EntityGraph entityGraph = em.createEntityGraph(Employee.class); + entityGraph.addAttributeNodes("name", "phones"); + Map properties = new HashMap<>(); + properties.put("javax.persistence.fetchgraph", entityGraph); + return em.find(Employee.class, id, properties); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java new file mode 100644 index 0000000000..fbc861c5fe --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.lifecycleevents; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootLifecycleEventApplication { + public static void main(String[] args) { + SpringApplication.run(SpringBootLifecycleEventApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java new file mode 100644 index 0000000000..26ebff42e4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java @@ -0,0 +1,39 @@ +package com.baeldung.lifecycleevents.model; + +import javax.persistence.PostLoad; +import javax.persistence.PostPersist; +import javax.persistence.PostRemove; +import javax.persistence.PostUpdate; +import javax.persistence.PrePersist; +import javax.persistence.PreRemove; +import javax.persistence.PreUpdate; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class AuditTrailListener { + private static Log log = LogFactory.getLog(AuditTrailListener.class); + + @PrePersist + @PreUpdate + @PreRemove + private void beforeAnyUpdate(User user) { + if (user.getId() == 0) { + log.info("[USER AUDIT] About to add a user"); + } else { + log.info("[USER AUDIT] About to update/delete user: " + user.getId()); + } + } + + @PostPersist + @PostUpdate + @PostRemove + private void afterAnyUpdate(User user) { + log.info("[USER AUDIT] add/update/delete complete for user: " + user.getId()); + } + + @PostLoad + private void afterLoad(User user) { + log.info("[USER AUDIT] user loaded from database: " + user.getId()); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/User.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/User.java new file mode 100644 index 0000000000..a080cb3bf2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/User.java @@ -0,0 +1,104 @@ +package com.baeldung.lifecycleevents.model; + +import javax.persistence.Entity; +import javax.persistence.EntityListeners; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.PostLoad; +import javax.persistence.PostPersist; +import javax.persistence.PostRemove; +import javax.persistence.PostUpdate; +import javax.persistence.PrePersist; +import javax.persistence.PreRemove; +import javax.persistence.PreUpdate; +import javax.persistence.Transient; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +@Entity +@EntityListeners(AuditTrailListener.class) +public class User { + private static Log log = LogFactory.getLog(User.class); + + @Id + @GeneratedValue + private int id; + + private String userName; + private String firstName; + private String lastName; + @Transient + private String fullName; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFullName() { + return fullName; + } + + @PrePersist + public void logNewUserAttempt() { + log.info("Attempting to add new user with username: " + userName); + } + + @PostPersist + public void logNewUserAdded() { + log.info("Added user '" + userName + "' with ID: " + id); + } + + @PreRemove + public void logUserRemovalAttempt() { + log.info("Attempting to delete user: " + userName); + } + + @PostRemove + public void logUserRemoval() { + log.info("Deleted user: " + userName); + } + + @PreUpdate + public void logUserUpdateAttempt() { + log.info("Attempting to update user: " + userName); + } + + @PostUpdate + public void logUserUpdate() { + log.info("Updated user: " + userName); + } + + @PostLoad + public void logUserLoad() { + fullName = firstName + " " + lastName; + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java new file mode 100644 index 0000000000..af14117ebb --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.lifecycleevents.repository; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.baeldung.lifecycleevents.model.User; + +public interface UserRepository extends JpaRepository { + public User findByUserName(String userName); +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java new file mode 100644 index 0000000000..cfb6e67c2c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java @@ -0,0 +1,35 @@ +package com.baeldung.namingstrategy; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Person { + @Id + private Long id; + + private String firstName; + + private String lastName; + + public Person() {} + + public Person(Long id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public Long id() { + return id; + } + + public String firstName() { + return firstName; + } + + public String lastName() { + return lastName; + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java new file mode 100644 index 0000000000..3c7c25bbcb --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.namingstrategy; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PersonRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java new file mode 100644 index 0000000000..16b01e50e3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class QuotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toLowerCase(), true); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java new file mode 100644 index 0000000000..3cb62aa5a2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class QuotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toUpperCase(), true); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java new file mode 100644 index 0000000000..f223015db8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java @@ -0,0 +1,7 @@ +package com.baeldung.namingstrategy; + +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringDataJpaNamingConventionApplication { +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java new file mode 100644 index 0000000000..69e96aee27 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class UnquotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toLowerCase(), false); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java new file mode 100644 index 0000000000..cb87af10f4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class UnquotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toUpperCase(), false); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java new file mode 100644 index 0000000000..5f05764e21 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.storedprocedure; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class StoredProcedureApplication { + + public static void main(String[] args) { + SpringApplication.run(StoredProcedureApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/controller/CarController.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/controller/CarController.java new file mode 100644 index 0000000000..6aef600d01 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/controller/CarController.java @@ -0,0 +1,47 @@ +package com.baeldung.storedprocedure.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.storedprocedure.entity.Car; +import com.baeldung.storedprocedure.service.CarService; + +@RestController +public class CarController { + @Autowired + private CarService carService; + + @GetMapping(path = "/modelcount") + public long getTotalCarsByModel(@RequestParam("model") String model) { + return carService.getTotalCarsByModel(model); + } + + @GetMapping(path = "/modelcountP") + public long getTotalCarsByModelProcedureName(@RequestParam("model") String model) { + return carService.getTotalCarsByModelProcedureName(model); + } + + @GetMapping(path = "/modelcountV") + public long getTotalCarsByModelVaue(@RequestParam("model") String model) { + return carService.getTotalCarsByModelValue(model); + } + + @GetMapping(path = "/modelcountEx") + public long getTotalCarsByModelExplicit(@RequestParam("model") String model) { + return carService.getTotalCarsByModelExplicit(model); + } + + @GetMapping(path = "/modelcountEn") + public long getTotalCarsByModelEntity(@RequestParam("model") String model) { + return carService.getTotalCarsByModelEntity(model); + } + + @GetMapping(path = "/carsafteryear") + public List findCarsAfterYear(@RequestParam("year") Integer year) { + return carService.findCarsAfterYear(year); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/entity/Car.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/entity/Car.java new file mode 100644 index 0000000000..2817c25ff7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/entity/Car.java @@ -0,0 +1,41 @@ +package com.baeldung.storedprocedure.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.NamedStoredProcedureQuery; +import javax.persistence.StoredProcedureParameter; +import javax.persistence.ParameterMode; + +@Entity +@NamedStoredProcedureQuery(name = "Car.getTotalCardsbyModelEntity", procedureName = "GET_TOTAL_CARS_BY_MODEL", parameters = { + @StoredProcedureParameter(mode = ParameterMode.IN, name = "model_in", type = String.class), + @StoredProcedureParameter(mode = ParameterMode.OUT, name = "count_out", type = Integer.class) }) + +public class Car { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column + private long id; + + @Column + private String model; + + @Column + private Integer year; + + public long getId() { + return id; + } + + public String getModel() { + return model; + } + + public Integer getYear() { + return year; + } + +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java new file mode 100644 index 0000000000..3d9428628e --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java @@ -0,0 +1,34 @@ +package com.baeldung.storedprocedure.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +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; + +import com.baeldung.storedprocedure.entity.Car; + +@Repository +public interface CarRepository extends JpaRepository { + + @Procedure + int GET_TOTAL_CARS_BY_MODEL(String model); + + @Procedure("GET_TOTAL_CARS_BY_MODEL") + int getTotalCarsByModel(String model); + + @Procedure(procedureName = "GET_TOTAL_CARS_BY_MODEL") + int getTotalCarsByModelProcedureName(String model); + + @Procedure(value = "GET_TOTAL_CARS_BY_MODEL") + int getTotalCarsByModelValue(String model); + + @Procedure(name = "Car.getTotalCardsbyModelEntity") + int getTotalCarsByModelEntiy(@Param("model_in") String model); + + @Query(value = "CALL FIND_CARS_AFTER_YEAR(:year_in);", nativeQuery = true) + List findCarsAfterYear(@Param("year_in") Integer year_in); + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/service/CarService.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/service/CarService.java new file mode 100644 index 0000000000..104f46e324 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/service/CarService.java @@ -0,0 +1,39 @@ +package com.baeldung.storedprocedure.service; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.storedprocedure.entity.Car; +import com.baeldung.storedprocedure.repository.CarRepository; + +@Service +public class CarService { + @Autowired + private CarRepository carRepository; + + public int getTotalCarsByModel(String model) { + return carRepository.getTotalCarsByModel(model); + } + + public int getTotalCarsByModelProcedureName(String model) { + return carRepository.getTotalCarsByModelProcedureName(model); + } + + public int getTotalCarsByModelValue(String model) { + return carRepository.getTotalCarsByModelValue(model); + } + + public int getTotalCarsByModelExplicit(String model) { + return carRepository.GET_TOTAL_CARS_BY_MODEL(model); + } + + public int getTotalCarsByModelEntity(String model) { + return carRepository.getTotalCarsByModelEntiy(model); + } + + public List findCarsAfterYear(Integer year) { + return carRepository.findCarsAfterYear(year); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-4/src/main/resources/application.properties index 72fc330767..65d7b0bf29 100644 --- a/persistence-modules/spring-data-jpa-4/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa-4/src/main/resources/application.properties @@ -1 +1,5 @@ -spring.jpa.show-sql=true \ No newline at end of file +spring.jpa.show-sql=true +#MySql +#spring.datasource.url=jdbc:mysql://localhost:3306/baeldung +#spring.datasource.username=baeldung +#spring.datasource.password=baeldung \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/main/resources/car-mysql.sql b/persistence-modules/spring-data-jpa-4/src/main/resources/car-mysql.sql new file mode 100644 index 0000000000..bb4ab2a86e --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/resources/car-mysql.sql @@ -0,0 +1,27 @@ +DROP TABLE IF EXISTS car; + +CREATE TABLE car (id int(10) NOT NULL AUTO_INCREMENT, + model varchar(50) NOT NULL, + year int(4) NOT NULL, + PRIMARY KEY (id)); + +INSERT INTO car (model, year) VALUES ('BMW', 2000); +INSERT INTO car (model, year) VALUES ('BENZ', 2010); +INSERT INTO car (model, year) VALUES ('PORCHE', 2005); +INSERT INTO car (model, year) VALUES ('PORCHE', 2004); + +DELIMITER $$ + +DROP PROCEDURE IF EXISTS FIND_CARS_AFTER_YEAR$$ +CREATE PROCEDURE FIND_CARS_AFTER_YEAR(IN year_in INT) +BEGIN + SELECT * FROM car WHERE year >= year_in ORDER BY year; +END$$ + +DROP PROCEDURE IF EXISTS GET_TOTAL_CARS_BY_MODEL$$ +CREATE PROCEDURE GET_TOTAL_CARS_BY_MODEL(IN model_in VARCHAR(50), OUT count_out INT) +BEGIN + SELECT COUNT(*) into count_out from car WHERE model = model_in; +END$$ + +DELIMITER ; diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java new file mode 100644 index 0000000000..306798aa68 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java @@ -0,0 +1,64 @@ +package com.baeldung.elementcollection; + +import com.baeldung.elementcollection.model.Employee; +import com.baeldung.elementcollection.model.Phone; +import com.baeldung.elementcollection.repository.EmployeeRepository; +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.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ElementCollectionApplication.class) +public class ElementCollectionIntegrationTest { + + @Autowired + private EmployeeRepository employeeRepository; + + @Before + public void init() { + Employee employee = new Employee(1, "Fred"); + employee.setPhones( + Arrays.asList(new Phone("work", "+55", "99999-9999"), new Phone("home", "+55", "98888-8888"))); + employeeRepository.save(employee); + } + + @After + public void clean() { + employeeRepository.remove(1); + } + + @Test(expected = org.hibernate.LazyInitializationException.class) + public void whenAccessLazyCollection_thenThrowLazyInitializationException() { + Employee employee = employeeRepository.findById(1); + assertThat(employee.getPhones().size(), is(2)); + } + + @Test + public void whenUseJPAQL_thenFetchResult() { + Employee employee = employeeRepository.findByJPQL(1); + assertThat(employee.getPhones().size(), is(2)); + } + + @Test + public void whenUseEntityGraph_thenFetchResult() { + Employee employee = employeeRepository.findByEntityGraph(1); + assertThat(employee.getPhones().size(), is(2)); + } + + @Test + @Transactional + public void whenUseTransaction_thenFetchResult() { + Employee employee = employeeRepository.findById(1); + assertThat(employee.getPhones().size(), is(2)); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..71a4dbda3f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,81 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-lower-case-naming-strategy.properties") +class QuotedLowerCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..6b1c984600 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-lower-case-naming-strategy-on-postgres.properties") +class QuotedLowerCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..f819327a5c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-upper-case-naming-strategy.properties") +class QuotedUpperCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..bd23b81b4b --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,81 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties") +class QuotedUpperCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..1850fea173 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("spring-physical-naming-strategy.properties") +class SpringPhysicalNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Unexpected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..e26ebb148d --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("spring-physical-naming-strategy-on-postgres.properties") +class SpringPhysicalNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..6311c42e93 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,86 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-lower-case-naming-strategy.properties") +class UnquotedLowerCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Unexpected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..033a213cf5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties") +class UnquotedLowerCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..7af8001854 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-upper-case-naming-strategy.properties") +class UnquotedUpperCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..0151e7ece4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-upper-case-naming-strategy-on-postgres.properties") +class UnquotedUpperCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Unexpected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..078f437474 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java @@ -0,0 +1,80 @@ +package lifecycleevents; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +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.test.context.junit4.SpringRunner; + +import com.baeldung.lifecycleevents.SpringBootLifecycleEventApplication; +import com.baeldung.lifecycleevents.model.User; +import com.baeldung.lifecycleevents.repository.UserRepository; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootLifecycleEventApplication.class) +public class UserRepositoryIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Before + public void setup() { + User user = new User(); + user.setFirstName("Jane"); + user.setLastName("Smith"); + user.setUserName("jsmith123"); + userRepository.save(user); + } + + @After + public void cleanup() { + userRepository.deleteAll(); + } + + @Test + public void whenNewUserProvided_userIsAdded() { + User user = new User(); + user.setFirstName("John"); + user.setLastName("Doe"); + user.setUserName("jdoe123"); + user = userRepository.save(user); + assertTrue(user.getId() > 0); + } + + @Test + public void whenUserNameProvided_userIsLoaded() { + User user = userRepository.findByUserName("jsmith123"); + assertNotNull(user); + assertEquals("jsmith123", user.getUserName()); + } + + @Test + public void whenExistingUserProvided_userIsUpdated() { + User user = userRepository.findByUserName("jsmith123"); + user.setFirstName("Joe"); + user = userRepository.save(user); + assertEquals("Joe", user.getFirstName()); + } + + @Test + public void whenExistingUserDeleted_userIsDeleted() { + User user = userRepository.findByUserName("jsmith123"); + userRepository.delete(user); + user = userRepository.findByUserName("jsmith123"); + assertNull(user); + } + + @Test + public void whenExistingUserLoaded_fullNameIsAvailable() { + String expectedFullName = "Jane Smith"; + User user = userRepository.findByUserName("jsmith123"); + assertEquals(expectedFullName, user.getFullName()); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..04b29de41f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-lower-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties new file mode 100644 index 0000000000..6643c12c8a --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:quoted-lower-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..36898d5b4f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-upper-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties new file mode 100644 index 0000000000..6d56d58749 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:quoted-upper-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..706b12b1b6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/spring-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties new file mode 100644 index 0000000000..c9a0c6f24c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:spring-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..b22472bd8f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-lower-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties new file mode 100644 index 0000000000..8083515b4b --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:unquoted-lower-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..da03a0d7b5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-upper-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties new file mode 100644 index 0000000000..d1b63e008c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:unquoted-upper-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-5/README.md b/persistence-modules/spring-data-jpa-5/README.md new file mode 100644 index 0000000000..e8f83654df --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/README.md @@ -0,0 +1,13 @@ +### Relevant Articles: + +- [Spring JPA @Embedded and @EmbeddedId](TBD) + +### 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/persistence-modules/spring-data-jpa-5/pom.xml b/persistence-modules/spring-data-jpa-5/pom.xml index df1cc6c0c4..6a5cdc86c2 100644 --- a/persistence-modules/spring-data-jpa-5/pom.xml +++ b/persistence-modules/spring-data-jpa-5/pom.xml @@ -1,8 +1,7 @@ - + + 4.0.0 spring-data-jpa-5 spring-data-jpa-5 @@ -15,24 +14,38 @@ + + org.springframework.boot + spring-boot-starter-web + + org.springframework.boot spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-data-jdbc + + + + org.springframework.boot + spring-boot-starter-cache + + com.h2database h2 + org.mapstruct mapstruct-jdk8 1.3.1.Final provided - - org.springframework.boot - spring-boot-starter-cache - + @@ -55,4 +68,4 @@ - \ No newline at end of file + diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/BookApplication.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/BookApplication.java new file mode 100644 index 0000000000..52f06058aa --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/BookApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.composite; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BookApplication { + + public static void main(String[] args) { + SpringApplication.run(BookApplication.class); + } +} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/Book.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/Book.java new file mode 100644 index 0000000000..e4f1727654 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/Book.java @@ -0,0 +1,47 @@ +package com.baeldung.composite.entity; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; + +@Entity +public class Book { + + @EmbeddedId + private BookId id; + private String genre; + private Integer price; + + public Book() { + } + + public Book(String author, String name, String genre, Integer price) { + BookId id = new BookId(author, name); + this.id = id; + this.genre = genre; + this.price = price; + } + + public BookId getId() { + return id; + } + + public void setId(BookId id) { + this.id = id; + } + + public String getGenre() { + return genre; + } + + public void setGenre(String genre) { + this.genre = genre; + } + + public Integer getPrice() { + return price; + } + + public void setPrice(Integer price) { + this.price = price; + } +} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/BookId.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/BookId.java new file mode 100644 index 0000000000..1524452412 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/BookId.java @@ -0,0 +1,51 @@ +package com.baeldung.composite.entity; + +import javax.persistence.Embeddable; +import java.io.Serializable; +import java.util.Objects; + +@Embeddable +public class BookId implements Serializable { + + private String author; + private String name; + + public BookId() { + } + + public BookId(String author, String name) { + this.author = author; + this.name = name; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + 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; + BookId bookId = (BookId) o; + return Objects.equals(author, bookId.author) && Objects.equals(name, bookId.name); + } + + @Override + public int hashCode() { + return Objects.hash(author, name); + } +} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/repository/BookRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/repository/BookRepository.java new file mode 100644 index 0000000000..d5993eaf79 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/repository/BookRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.composite.repository; + +import com.baeldung.composite.entity.Book; +import com.baeldung.composite.entity.BookId; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface BookRepository extends JpaRepository { + + List findByIdName(String name); + + List findByIdAuthor(String author); + + List findByGenre(String genre); +} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/AccountApplication.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/AccountApplication.java new file mode 100644 index 0000000000..547992a6c1 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/AccountApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.schemageneration; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AccountApplication { + + public static void main(String[] args) { + SpringApplication.run(AccountApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/HibernateUtil.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/HibernateUtil.java new file mode 100644 index 0000000000..7d69d65705 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/HibernateUtil.java @@ -0,0 +1,39 @@ +package com.baeldung.schemageneration; + +import com.baeldung.schemageneration.model.Account; +import com.baeldung.schemageneration.model.AccountSetting; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Environment; +import org.hibernate.tool.hbm2ddl.SchemaExport; +import org.hibernate.tool.schema.TargetType; + +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; + +public class HibernateUtil { + + /** + * Generates database create commands for the specified entities using Hibernate native API, SchemaExport. + * Creation commands are exported into the create.sql file. + */ + public static void generateSchema() { + Map settings = new HashMap<>(); + settings.put(Environment.URL, "jdbc:h2:mem:schema"); + + StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build(); + + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Account.class); + metadataSources.addAnnotatedClass(AccountSetting.class); + Metadata metadata = metadataSources.buildMetadata(); + + SchemaExport schemaExport = new SchemaExport(); + schemaExport.setFormat(true); + schemaExport.setOutputFile("create.sql"); + schemaExport.createOnly(EnumSet.of(TargetType.SCRIPT), metadata); + } +} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/Account.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/Account.java new file mode 100644 index 0000000000..785e275e26 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/Account.java @@ -0,0 +1,74 @@ +package com.baeldung.schemageneration.model; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Table(name = "accounts") +public class Account { + + @Id + @GeneratedValue + private Long id; + + @Column(nullable = false, length = 100) + private String name; + + @Column(name = "email_address") + private String emailAddress; + + @OneToMany(mappedBy = "account", cascade = CascadeType.ALL) + private List accountSettings = new ArrayList<>(); + + public Account() { + } + + public Account(String name, String emailAddress) { + this.name = name; + this.emailAddress = emailAddress; + } + + 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 getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + public List getAccountSettings() { + return accountSettings; + } + + public void setAccountSettings(List accountSettings) { + this.accountSettings = accountSettings; + } + + public void addAccountSetting(AccountSetting setting) { + this.accountSettings.add(setting); + setting.setAccount(this); + } +} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java new file mode 100644 index 0000000000..61e43894a8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java @@ -0,0 +1,68 @@ +package com.baeldung.schemageneration.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "account_settings") +public class AccountSetting { + + @Id + @GeneratedValue + private Long id; + + @Column(name = "name", nullable = false) + private String settingName; + + @Column(name = "value", nullable = false) + private String settingValue; + + @ManyToOne() + @JoinColumn(name ="account_id", nullable = false) + private Account account; + + public AccountSetting() { + } + + public AccountSetting(String settingName, String settingValue) { + this.settingName = settingName; + this.settingValue = settingValue; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getSettingName() { + return settingName; + } + + public void setSettingName(String settingName) { + this.settingName = settingName; + } + + public String getSettingValue() { + return settingValue; + } + + public void setSettingValue(String settingValue) { + this.settingValue = settingValue; + } + + public Account getAccount() { + return account; + } + + public void setAccount(Account account) { + this.account = account; + } +} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java new file mode 100644 index 0000000000..dc57ffe6d3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.schemageneration.repository; + +import com.baeldung.schemageneration.model.Account; +import org.springframework.data.repository.CrudRepository; + +public interface AccountRepository extends CrudRepository { + Account findByName(String name); +} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java new file mode 100644 index 0000000000..c2b8ff7398 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.schemageneration.repository; + +import com.baeldung.schemageneration.model.AccountSetting; +import org.springframework.data.repository.CrudRepository; + +public interface AccountSettingRepository extends CrudRepository { + AccountSetting findByAccountId(Long accountId); +} diff --git a/persistence-modules/spring-data-jpa-5/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-5/src/main/resources/application.properties new file mode 100644 index 0000000000..f55ad438ff --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/main/resources/application.properties @@ -0,0 +1,13 @@ + +spring.datasource.url=jdbc:h2:mem:baeldung + +# JPA-Schema-Generation +# Use below configuration to generate database schema create commands based on the entity models +# and export them into the create.sql file +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-source=metadata +#spring.jpa.properties.hibernate.format_sql=true + +spring.jpa.show-sql=true + diff --git a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9d25acbd96 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java @@ -0,0 +1,64 @@ +package com.baeldung.composite.repository; + +import com.baeldung.composite.BookApplication; +import com.baeldung.composite.entity.Book; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookApplication.class) +public class BookRepositoryIntegrationTest { + + public static final String JAVA_101 = "Java101"; + public static final String JANE = "Jane"; + public static final String TECH = "Tech"; + @Autowired + BookRepository repository; + + @Before + public void setUp() { + Book book1 = new Book("John", JAVA_101, TECH, 20); + Book book2 = new Book(JANE, JAVA_101, "Arch", 25); + Book book3 = new Book(JANE, "Scala101", TECH, 23); + + repository.saveAll(Arrays.asList(book1, book2, book3)); + } + + @After + public void tearDown() { + repository.deleteAll(); + } + + @Test + public void testFindByName() { + List books = repository.findByIdName(JAVA_101); + + assertEquals(2, books.size()); + } + + @Test + public void testFindByAuthor() { + List books = repository.findByIdAuthor(JANE); + + assertEquals(2, books.size()); + } + + @Test + public void testFindByGenre() { + List books = repository.findByGenre(TECH); + + assertEquals(2, books.size()); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java new file mode 100644 index 0000000000..86a7671fe4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java @@ -0,0 +1,72 @@ +package com.baeldung.schemageneration; + +import com.baeldung.schemageneration.model.Account; +import com.baeldung.schemageneration.model.AccountSetting; +import com.baeldung.schemageneration.repository.AccountRepository; +import com.baeldung.schemageneration.repository.AccountSettingRepository; +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.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AccountApplication.class) +public class AccountRepositoryIntegrationTest { + + private static final String USER_NAME = "Eduard"; + private static final String USER_EMAIL_ADDRESS = "eduard@gmx.com"; + private static final String ACCOUNT_SETTING_NAME = "Timezone"; + private static final String ACCOUNT_SETTING_VALUE = "UTC+02"; + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private AccountSettingRepository accountSettingRepository; + + @After + public void tearDown() { + accountRepository.deleteAll(); + } + + @Test + public void givenNewAccount_whenSave_thenSuccess() { + Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); + accountRepository.save(account); + + assertEquals(1, accountRepository.count()); + } + + @Test + public void givenSavedAccount_whenFindByName_thenFound() { + Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); + accountRepository.save(account); + + Account accountFound = accountRepository.findByName(USER_NAME); + + assertNotNull(accountFound); + assertEquals(USER_NAME, accountFound.getName()); + assertEquals(USER_EMAIL_ADDRESS, accountFound.getEmailAddress()); + } + + @Test + public void givenSavedAccount_whenAccountSettingIsAdded_thenPersisted() { + Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); + account.addAccountSetting(new AccountSetting(ACCOUNT_SETTING_NAME, ACCOUNT_SETTING_VALUE)); + accountRepository.save(account); + + Account accountFound = accountRepository.findByName(USER_NAME); + assertNotNull(accountFound); + AccountSetting accountSetting = accountSettingRepository.findByAccountId(accountFound.getId()); + + assertNotNull(accountSetting); + assertEquals(ACCOUNT_SETTING_NAME, accountSetting.getSettingName()); + assertEquals(ACCOUNT_SETTING_VALUE, accountSetting.getSettingValue()); + } + +} diff --git a/persistence-modules/spring-data-jpa-5/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-5/src/test/resources/application-test.properties new file mode 100644 index 0000000000..e3d39fe1e2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-5/src/test/resources/application-test.properties @@ -0,0 +1,3 @@ +spring.jpa.hibernate.ddl-auto=update +spring.datasource.url=jdbc:h2:mem:baeldung + diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml index 27b8ce5eaf..ddd7e17dcd 100644 --- a/persistence-modules/spring-data-jpa/pom.xml +++ b/persistence-modules/spring-data-jpa/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 spring-data-jpa spring-data-jpa @@ -43,7 +42,6 @@ org.postgresql postgresql - ${postgresql.version} @@ -67,26 +65,6 @@ guava ${guava.version} - - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - - - org.junit.platform - junit-platform-launcher - ${junit-platform.version} - test - diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java index 9b235776dc..f1256e2c72 100755 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java @@ -1,9 +1,14 @@ package com.baeldung.multipledb.dao.product; +import java.util.List; + +import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; -import com.baeldung.multipledb.model.product.ProductMultipleDB; +import com.baeldung.multipledb.model.product.Product; -public interface ProductRepository extends PagingAndSortingRepository { +public interface ProductRepository extends PagingAndSortingRepository { -} \ No newline at end of file + + List findAllByPrice(double price, Pageable pageable); +} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/Product.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/Product.java new file mode 100755 index 0000000000..eaf471043c --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/Product.java @@ -0,0 +1,67 @@ +package com.baeldung.multipledb.model.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(); + } + + private Product(int id, String name, double price) { + super(); + this.id = id; + this.name = name; + this.price = price; + } + + public static Product from(int id, String name, double price) { + return new Product(id, name, price); + } + + 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-data-jpa/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java deleted file mode 100755 index 8bdff340ac..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.multipledb.model.product; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(schema = "products") -public class ProductMultipleDB { - - @Id - private int id; - - private String name; - - private double price; - - public ProductMultipleDB() { - super(); - } - - private ProductMultipleDB(int id, String name, double price) { - super(); - this.id = id; - this.name = name; - this.price = price; - } - - public static ProductMultipleDB from(int id, String name, double price) { - return new ProductMultipleDB(id, name, price); - } - - 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-data-jpa/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..eaccf4acba --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java similarity index 97% rename from persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java rename to persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java index 4a36407884..f3697bf39f 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java index 17ee6a94ba..b2581b8034 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java @@ -266,7 +266,7 @@ public class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); assertThat(usersSortByName.get(0) .getName()).isEqualTo(USER_NAME_ADAM); @@ -278,7 +278,7 @@ public class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java index 6ba10a4d49..a1f4a3fa2c 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java @@ -19,7 +19,7 @@ import org.springframework.transaction.annotation.Transactional; import com.baeldung.multipledb.dao.product.ProductRepository; import com.baeldung.multipledb.dao.user.PossessionRepository; import com.baeldung.multipledb.dao.user.UserRepository; -import com.baeldung.multipledb.model.product.ProductMultipleDB; +import com.baeldung.multipledb.model.product.Product; import com.baeldung.multipledb.model.user.PossessionMultipleDB; import com.baeldung.multipledb.model.user.UserMultipleDB; @@ -84,7 +84,7 @@ public class JpaMultipleDBIntegrationTest { @Test @Transactional("productTransactionManager") public void whenCreatingProduct_thenCreated() { - ProductMultipleDB product = new ProductMultipleDB(); + Product product = new Product(); product.setName("Book"); product.setId(2); product.setPrice(20); diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9bfba61a3b --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java @@ -0,0 +1,144 @@ +package com.baeldung.multipledb; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +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.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +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.multipledb.PersistenceProductConfiguration; +import com.baeldung.multipledb.dao.product.ProductRepository; +import com.baeldung.multipledb.model.product.Product; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes=MultipleDbApplication.class) +@EnableTransactionManagement +public class ProductRepositoryIntegrationTest { + + @Autowired + private ProductRepository productRepository; + + @Before + @Transactional("productTransactionManager") + public void setUp() { + productRepository.save(Product.from(1001, "Book", 21)); + productRepository.save(Product.from(1002, "Coffee", 10)); + productRepository.save(Product.from(1003, "Jeans", 30)); + productRepository.save(Product.from(1004, "Shirt", 32)); + productRepository.save(Product.from(1005, "Bacon", 10)); + } + + @Test + public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { + Pageable pageRequest = PageRequest.of(0, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1001, 1002) + .contains(id))); + } + + @Test + public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { + Pageable pageRequest = PageRequest.of(1, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1003, 1004) + .contains(id))); + } + + @Test + public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { + Pageable pageRequest = PageRequest.of(2, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(1)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1005) + .contains(id))); + } + + @Test + public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(3)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002))); + + } + + @Test + public void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") + .descending()); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(3)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001))); + + } + + @Test + public void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 5, Sort.by("price") + .descending() + .and(Sort.by("name"))); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(5)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002))); + + } + + @Test + public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { + Pageable pageRequest = PageRequest.of(0, 2); + + List result = productRepository.findAllByPrice(10, pageRequest); + + assertThat(result, hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1002, 1005) + .contains(id))); + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index db7b156415..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-keyvalue/README.md b/persistence-modules/spring-data-keyvalue/README.md index 9f53a11b2c..93cde8ce93 100644 --- a/persistence-modules/spring-data-keyvalue/README.md +++ b/persistence-modules/spring-data-keyvalue/README.md @@ -3,4 +3,4 @@ This module contains articles about Spring Data Key-Value ### Relevant Articles: -- [A Guide to Spring Data Key Value](http://www.baeldung.com/spring-data-key-value) +- [A Guide to Spring Data Key Value](https://www.baeldung.com/spring-data-key-value) diff --git a/persistence-modules/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java b/persistence-modules/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java index 3eb1d0f66a..fe3c332f33 100644 --- a/persistence-modules/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java +++ b/persistence-modules/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java @@ -49,7 +49,7 @@ public class EmployeeServicesWithKeyValueTemplate implements EmployeeService { @Override public Iterable getSortedListOfEmployeesBySalary() { KeyValueQuery query = new KeyValueQuery(); - query.setSort(new Sort(Sort.Direction.DESC, "salary")); + query.setSort(Sort.by(Sort.Direction.DESC, "salary")); return keyValueTemplate.find(query, Employee.class); } diff --git a/persistence-modules/spring-data-keyvalue/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-keyvalue/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..aca177d1a7 --- /dev/null +++ b/persistence-modules/spring-data-keyvalue/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.data.keyvalue.SpringDataKeyValueApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataKeyValueApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e6cc5c15af..0000000000 --- a/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.data.keyvalue.SpringDataKeyValueApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringDataKeyValueApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-mongodb/README.md b/persistence-modules/spring-data-mongodb/README.md index c4f21dffc0..381bf83fa8 100644 --- a/persistence-modules/spring-data-mongodb/README.md +++ b/persistence-modules/spring-data-mongodb/README.md @@ -13,3 +13,12 @@ - [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) - [Spring Data MongoDB Transactions](https://www.baeldung.com/spring-data-mongodb-transactions ) - [ZonedDateTime with Spring Data MongoDB](https://www.baeldung.com/spring-data-mongodb-zoneddatetime) + + +## Spring Data MongoDB Live Testing + + +There are 3 scripts to simplify running live tests: +1. [`live-test-setup.sh`](src/live-test/resources/live-test-setup.sh) builds a docker image with the necessary setup and runs it. The environment is ready, when the log stops - it takes approximately 30 seconds. +2. [`live-test.sh`](src/live-test/resources/live-test.sh) runs the live tests (but no other tests). +3. [`live-test-teardown.sh`](src/live-test/resources/live-test-teardown.sh) stops and removes the docker image. diff --git a/persistence-modules/spring-data-mongodb/src/live-test/resources/Dockerfile b/persistence-modules/spring-data-mongodb/src/live-test/resources/Dockerfile new file mode 100644 index 0000000000..9e3634feb0 --- /dev/null +++ b/persistence-modules/spring-data-mongodb/src/live-test/resources/Dockerfile @@ -0,0 +1,8 @@ +FROM mongo:4.2.1 + +COPY init-session.js /docker-entrypoint-initdb.d/ + +EXPOSE 27017 + +HEALTHCHECK --interval=5s --timeout=3s --start-period=10s CMD mongo db.stats() +CMD ["mongod", "--replSet", "rs0"] diff --git a/persistence-modules/spring-data-mongodb/src/live-test/resources/init-session.js b/persistence-modules/spring-data-mongodb/src/live-test/resources/init-session.js new file mode 100644 index 0000000000..2e968884cc --- /dev/null +++ b/persistence-modules/spring-data-mongodb/src/live-test/resources/init-session.js @@ -0,0 +1 @@ +rs.initiate(); diff --git a/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test-setup.sh b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test-setup.sh new file mode 100644 index 0000000000..78968d51aa --- /dev/null +++ b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test-setup.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +docker image build -t spring-data-mongodb:live-test . + +docker run -p 27017:27017 --name spring-data-mongodb-live-test spring-data-mongodb:live-test diff --git a/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test-teardown.sh b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test-teardown.sh new file mode 100644 index 0000000000..a29163bc7a --- /dev/null +++ b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test-teardown.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +docker stop spring-data-mongodb-live-test +docker rm spring-data-mongodb-live-test diff --git a/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test.sh b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test.sh new file mode 100644 index 0000000000..307a68a3bd --- /dev/null +++ b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +mvn clean compile test -P live-all -f ../../../pom.xml diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java index bafcd770ec..6cd9657006 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java @@ -62,24 +62,6 @@ public class MongoTransactionalLiveTest { } } - @Test(expected = MongoCommandException.class) - @Transactional - public void whenCountDuringMongoTransaction_thenException() { - userRepository.save(new User("John", 30)); - userRepository.save(new User("Ringo", 35)); - userRepository.count(); - } - - @Test - @Transactional - public void whenQueryDuringMongoTransaction_thenSuccess() { - userRepository.save(new User("Jane", 20)); - userRepository.save(new User("Nick", 33)); - List users = mongoTemplate.find(new Query(), User.class); - - assertTrue(users.size() > 1); - } - // ==== Using test instead of before and after due to @transactional doesn't allow list collection @Test diff --git a/persistence-modules/spring-data-neo4j/README.md b/persistence-modules/spring-data-neo4j/README.md index 03c9ed333d..dc54de0e31 100644 --- a/persistence-modules/spring-data-neo4j/README.md +++ b/persistence-modules/spring-data-neo4j/README.md @@ -1,8 +1,8 @@ ## Spring Data Neo4j ### Relevant Articles: -- [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-intro) -- [A Guide to Neo4J with Java](http://www.baeldung.com/java-neo4j) +- [Introduction to Spring Data Neo4j](https://www.baeldung.com/spring-data-neo4j-intro) +- [A Guide to Neo4J with Java](https://www.baeldung.com/java-neo4j) ### Build the Project with Tests Running ``` diff --git a/persistence-modules/spring-data-neo4j/pom.xml b/persistence-modules/spring-data-neo4j/pom.xml index 625e2c5fc1..d827c32a3c 100644 --- a/persistence-modules/spring-data-neo4j/pom.xml +++ b/persistence-modules/spring-data-neo4j/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ 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 9bbc571aee..4e87c24614 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 @@ -16,8 +16,7 @@ public class MovieDatabaseNeo4jConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { - org.neo4j.ogm.config.Configuration config = new Builder().uri(URL).build(); - return config; + return new Builder().uri(URL).build(); } @Bean diff --git a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7029905c49 --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class) +@ActiveProfiles(profiles = "test") +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 5bf54fc0bd..0000000000 --- a/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class) -@ActiveProfiles(profiles = "test") -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-redis/README.md b/persistence-modules/spring-data-redis/README.md index a20f5052f0..175634376b 100644 --- a/persistence-modules/spring-data-redis/README.md +++ b/persistence-modules/spring-data-redis/README.md @@ -1,9 +1,10 @@ ## Spring Data Redis ### Relevant Articles: -- [Introduction to Spring Data Redis](http://www.baeldung.com/spring-data-redis-tutorial) -- [PubSub Messaging with Spring Data Redis](http://www.baeldung.com/spring-data-redis-pub-sub) +- [Introduction to Spring Data Redis](https://www.baeldung.com/spring-data-redis-tutorial) +- [PubSub Messaging with Spring Data Redis](https://www.baeldung.com/spring-data-redis-pub-sub) - [An Introduction to Spring Data Redis Reactive](https://www.baeldung.com/spring-data-redis-reactive) +- [Delete Everything in Redis](https://www.baeldung.com/redis-delete-data) ### Build the Project with Tests Running ``` diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index a304108fee..d2bf074d03 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -4,7 +4,7 @@ 4.0.0 spring-data-redis 1.0 - spring-data-redis + spring-data-redis jar @@ -62,7 +62,6 @@ redis.clients jedis - ${jedis.version} jar @@ -97,10 +96,9 @@ 3.2.4 - 2.9.0 0.10.0 - 2.0.3.RELEASE 0.6 + 2.1.9.RELEASE 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 6fdb3c5bef..fdc279be42 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,13 +1,11 @@ package com.baeldung.spring.data.redis.config; -import com.baeldung.spring.data.redis.queue.MessagePublisher; -import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; -import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; 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.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; @@ -15,6 +13,10 @@ import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; import org.springframework.data.redis.serializer.GenericToStringSerializer; +import com.baeldung.spring.data.redis.queue.MessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; + @Configuration @ComponentScan("com.baeldung.spring.data.redis") @EnableRedisRepositories(basePackages = "com.baeldung.spring.data.redis.repo") @@ -33,6 +35,18 @@ public class RedisConfig { template.setValueSerializer(new GenericToStringSerializer(Object.class)); return template; } + + @Bean + public LettuceConnectionFactory lettuceConnectionFactory() { + return new LettuceConnectionFactory(); + } + + @Bean(name = "flushRedisTemplate") + public RedisTemplate flushRedisTemplate() { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(lettuceConnectionFactory()); + return template; + } @Bean MessageListenerAdapter messageListener() { diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4df0cbd0ad --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.redis.config.RedisConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RedisConfig.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/delete/RedisFlushDatabaseIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/delete/RedisFlushDatabaseIntegrationTest.java new file mode 100644 index 0000000000..1f56cbb25d --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/delete/RedisFlushDatabaseIntegrationTest.java @@ -0,0 +1,92 @@ +package com.baeldung.spring.data.redis.delete; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; + +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.beans.factory.annotation.Qualifier; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +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 redis.embedded.RedisServer; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { RedisConfig.class }) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) +public class RedisFlushDatabaseIntegrationTest { + + private RedisServer redisServer; + + @Autowired + @Qualifier("flushRedisTemplate") + private RedisTemplate flushRedisTemplate; + + @Before + public void setup() throws IOException { + redisServer = new RedisServer(6390); + redisServer.start(); + } + + @After + public void tearDown() { + redisServer.stop(); + } + + @Test + public void whenFlushDB_thenAllKeysInDatabaseAreCleared() { + + ValueOperations simpleValues = flushRedisTemplate.opsForValue(); + String key = "key"; + String value = "value"; + simpleValues.set(key, value); + assertThat(simpleValues.get(key)).isEqualTo(value); + + flushRedisTemplate.execute(new RedisCallback() { + + @Override + public Void doInRedis(RedisConnection connection) throws DataAccessException { + connection.flushDb(); + return null; + } + }); + + assertThat(simpleValues.get(key)).isNull(); + + } + + @Test + public void whenFlushAll_thenAllKeysInDatabasesAreCleared() { + + ValueOperations simpleValues = flushRedisTemplate.opsForValue(); + String key = "key"; + String value = "value"; + simpleValues.set(key, value); + assertThat(simpleValues.get(key)).isEqualTo(value); + + flushRedisTemplate.execute(new RedisCallback() { + + @Override + public Void doInRedis(RedisConnection connection) throws DataAccessException { + connection.flushAll(); + return null; + } + }); + + assertThat(simpleValues.get(key)).isNull(); + + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 6652345595..0000000000 --- a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.spring.data.redis.config.RedisConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = RedisConfig.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-solr/README.md b/persistence-modules/spring-data-solr/README.md index c282fd2ce7..3d58d2d44c 100644 --- a/persistence-modules/spring-data-solr/README.md +++ b/persistence-modules/spring-data-solr/README.md @@ -3,4 +3,4 @@ This module contains articles about Spring Data with Solr. ### Relevant Articles: -- [Introduction to Spring Data Solr](http://www.baeldung.com/spring-data-solr) +- [Introduction to Spring Data Solr](https://www.baeldung.com/spring-data-solr) diff --git a/persistence-modules/spring-data-solr/pom.xml b/persistence-modules/spring-data-solr/pom.xml index 1a17a2e321..9d96c75082 100644 --- a/persistence-modules/spring-data-solr/pom.xml +++ b/persistence-modules/spring-data-solr/pom.xml @@ -3,7 +3,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-data-solr - 0.0.1-SNAPSHOT spring-data-solr jar diff --git a/persistence-modules/spring-data-solr/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-solr/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f445a550a3 --- /dev/null +++ b/persistence-modules/spring-data-solr/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.solr.config.SolrConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = SolrConfig.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 09bf0255a0..0000000000 --- a/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.spring.data.solr.config.SolrConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = SolrConfig.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-hibernate-3/README.md b/persistence-modules/spring-hibernate-3/README.md index 898c6522a9..610d586f85 100644 --- a/persistence-modules/spring-hibernate-3/README.md +++ b/persistence-modules/spring-hibernate-3/README.md @@ -4,8 +4,8 @@ This module contains articles about Spring with Hibernate 3 ### Relevant Articles: -- [Hibernate 3 with Spring](http://www.baeldung.com/hibernate3-spring) -- [HibernateException: No Hibernate Session Bound to Thread in Hibernate 3](http://www.baeldung.com/no-hibernate-session-bound-to-thread-exception) +- [Hibernate 3 with Spring](https://www.baeldung.com/hibernate3-spring) +- [HibernateException: No Hibernate Session Bound to Thread in Hibernate 3](https://www.baeldung.com/no-hibernate-session-bound-to-thread-exception) ### Quick Start diff --git a/persistence-modules/spring-hibernate-3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml index e677776a95..b28895f86d 100644 --- a/persistence-modules/spring-hibernate-3/pom.xml +++ b/persistence-modules/spring-hibernate-3/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ @@ -73,16 +72,6 @@ - - spring-hibernate-3 - - - src/main/resources - true - - - - 4.3.4.RELEASE diff --git a/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/AbstractHibernateDao.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/AbstractHibernateDao.java new file mode 100644 index 0000000000..701c6c43c7 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/AbstractHibernateDao.java @@ -0,0 +1,64 @@ +package com.baeldung.persistence.dao; + +import java.io.Serializable; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.base.Preconditions; + +@SuppressWarnings("unchecked") +public abstract class AbstractHibernateDao implements IOperations { + private Class clazz; + + @Autowired + private SessionFactory sessionFactory; + + // API + + protected final void setClazz(final Class clazzToSet) { + clazz = clazzToSet; + } + + @Override + public final T findOne(final long id) { + return ((T) getCurrentSession().get(clazz, id)); + } + + @Override + public final List findAll() { + return getCurrentSession().createQuery("from " + clazz.getName()).list(); + } + + @Override + public final void create(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().persist(entity); + } + + @Override + public final T update(final T entity) { + Preconditions.checkNotNull(entity); + return (T) getCurrentSession().merge(entity); + } + + @Override + public final void delete(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().delete(entity); + } + + @Override + public final void deleteById(final long entityId) { + final T entity = findOne(entityId); + Preconditions.checkState(entity != null); + delete(entity); + } + + protected final Session getCurrentSession() { + return sessionFactory.getCurrentSession(); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/EventDao.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/EventDao.java new file mode 100644 index 0000000000..e6519d54c8 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/EventDao.java @@ -0,0 +1,18 @@ +package com.baeldung.persistence.dao; + + +import com.baeldung.persistence.model.Event; +import org.springframework.stereotype.Repository; + +@Repository +public class EventDao extends AbstractHibernateDao implements IEventDao { + + public EventDao() { + super(); + + setClazz(Event.class); + } + + // API + +} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/FooDao.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/FooDao.java new file mode 100644 index 0000000000..afcd958bc2 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/FooDao.java @@ -0,0 +1,17 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.Foo; +import org.springframework.stereotype.Repository; + +@Repository +public class FooDao extends AbstractHibernateDao implements IFooDao { + + public FooDao() { + super(); + + setClazz(Foo.class); + } + + // API + +} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/IEventDao.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/IEventDao.java new file mode 100644 index 0000000000..da2be1ce1e --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/IEventDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.Event; + + +public interface IEventDao extends IOperations { + // +} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/IFooDao.java new file mode 100644 index 0000000000..f79883980a --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/IFooDao.java @@ -0,0 +1,7 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.Foo; + +public interface IFooDao extends IOperations { + // +} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/IOperations.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/IOperations.java new file mode 100644 index 0000000000..66f8008f27 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/dao/IOperations.java @@ -0,0 +1,20 @@ +package com.baeldung.persistence.dao; + +import java.io.Serializable; +import java.util.List; + +public interface IOperations { + + T findOne(final long id); + + List findAll(); + + void create(final T entity); + + T update(final T entity); + + void delete(final T entity); + + void deleteById(final long entityId); + +} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Event.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/model/Event.java similarity index 89% rename from persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Event.java rename to persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/model/Event.java index 1d659ed75c..37a9758cd5 100644 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Event.java +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/model/Event.java @@ -1,45 +1,45 @@ -package org.baeldung.persistence.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "EVENTS") -public class Event implements Serializable { - - @Id - @GeneratedValue - private Long id; - - private String description; - - public Event() { - } - - - public Event(String description) { - this.description = description; - } - - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - +package com.baeldung.persistence.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "EVENTS") +public class Event implements Serializable { + + @Id + @GeneratedValue + private Long id; + + private String description; + + public Event() { + } + + + public Event(String description) { + this.description = description; + } + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + } \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/model/Foo.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/model/Foo.java new file mode 100644 index 0000000000..9af3d07bed --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/model/Foo.java @@ -0,0 +1,83 @@ +package com.baeldung.persistence.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false) + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + 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; + } + + // + + @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/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/service/EventService.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/service/EventService.java new file mode 100644 index 0000000000..bf9afed38b --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/service/EventService.java @@ -0,0 +1,27 @@ +package com.baeldung.persistence.service; + + +import com.baeldung.persistence.model.Event; +import com.baeldung.persistence.dao.IEventDao; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class EventService { + + @Autowired + private IEventDao dao; + + public EventService() { + super(); + } + + // API + + public void create(final Event entity) { + dao.create(entity); + } + +} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/service/FooService.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/service/FooService.java new file mode 100644 index 0000000000..ad88062216 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/persistence/service/FooService.java @@ -0,0 +1,26 @@ +package com.baeldung.persistence.service; + +import com.baeldung.persistence.dao.IFooDao; +import com.baeldung.persistence.model.Foo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class FooService { + + @Autowired + private IFooDao dao; + + public FooService() { + super(); + } + + // API + + public void create(final Foo entity) { + dao.create(entity); + } + +} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/spring/PersistenceConfig.java new file mode 100644 index 0000000000..29472174b2 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -0,0 +1,78 @@ +package com.baeldung.spring; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.orm.hibernate3.HibernateTransactionManager; +import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-h2.properties" }) +@ComponentScan({ "com.baeldung.persistence.dao", "com.baeldung.persistence.service" }) +public class PersistenceConfig { + + @Autowired + private Environment env; + + public PersistenceConfig() { + super(); + } + + @Bean + public AnnotationSessionFactoryBean sessionFactory() { + final AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean(); + sessionFactory.setDataSource(dataSource()); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public DataSource dataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + @Autowired + public HibernateTransactionManager transactionManager(final SessionFactory sessionFactory) { + final HibernateTransactionManager txManager = new HibernateTransactionManager(); + txManager.setSessionFactory(sessionFactory); + + return txManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + +} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/spring/PersistenceConfigHibernate3.java similarity index 97% rename from persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java rename to persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/spring/PersistenceConfigHibernate3.java index f38da21dc0..08ae9a76df 100644 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/spring/PersistenceConfigHibernate3.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import java.util.Properties; @@ -24,7 +24,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "org.baeldung.persistence.dao", "org.baeldung.persistence.service" }) +@ComponentScan({ "com.baeldung.persistence.dao", "com.baeldung.persistence.service" }) public class PersistenceConfigHibernate3 { @Autowired diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceXmlConfig.java b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java similarity index 81% rename from persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceXmlConfig.java rename to persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java index 5831d2745c..798fb740a7 100644 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceXmlConfig.java +++ b/persistence-modules/spring-hibernate-3/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ImportResource; @@ -6,7 +6,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; // @Configuration @EnableTransactionManagement -@ComponentScan({ "org.baeldung.persistence.dao", "org.baeldung.persistence.service" }) +@ComponentScan({ "com.baeldung.persistence.dao", "com.baeldung.persistence.service" }) @ImportResource({ "classpath:persistenceConfig.xml" }) public class PersistenceXmlConfig { diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/AbstractHibernateDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/AbstractHibernateDao.java deleted file mode 100644 index 0f8b132891..0000000000 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/AbstractHibernateDao.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.baeldung.persistence.dao; - -import java.io.Serializable; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.google.common.base.Preconditions; - -@SuppressWarnings("unchecked") -public abstract class AbstractHibernateDao implements IOperations { - private Class clazz; - - @Autowired - private SessionFactory sessionFactory; - - // API - - protected final void setClazz(final Class clazzToSet) { - clazz = clazzToSet; - } - - @Override - public final T findOne(final long id) { - return ((T) getCurrentSession().get(clazz, id)); - } - - @Override - public final List findAll() { - return getCurrentSession().createQuery("from " + clazz.getName()).list(); - } - - @Override - public final void create(final T entity) { - Preconditions.checkNotNull(entity); - getCurrentSession().persist(entity); - } - - @Override - public final T update(final T entity) { - Preconditions.checkNotNull(entity); - return (T) getCurrentSession().merge(entity); - } - - @Override - public final void delete(final T entity) { - Preconditions.checkNotNull(entity); - getCurrentSession().delete(entity); - } - - @Override - public final void deleteById(final long entityId) { - final T entity = findOne(entityId); - Preconditions.checkState(entity != null); - delete(entity); - } - - protected final Session getCurrentSession() { - return sessionFactory.getCurrentSession(); - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/EventDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/EventDao.java deleted file mode 100644 index 74da643f35..0000000000 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/EventDao.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.persistence.dao; - - -import org.baeldung.persistence.model.Event; -import org.springframework.stereotype.Repository; - -@Repository -public class EventDao extends AbstractHibernateDao implements IEventDao { - - public EventDao() { - super(); - - setClazz(Event.class); - } - - // API - -} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/FooDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/FooDao.java deleted file mode 100644 index 23de04169e..0000000000 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/FooDao.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.Foo; -import org.springframework.stereotype.Repository; - -@Repository -public class FooDao extends AbstractHibernateDao implements IFooDao { - - public FooDao() { - super(); - - setClazz(Foo.class); - } - - // API - -} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IEventDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IEventDao.java deleted file mode 100644 index f7be705905..0000000000 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IEventDao.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.Event; - - - -public interface IEventDao extends IOperations { - // -} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IFooDao.java deleted file mode 100644 index 6a3bd95d71..0000000000 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IFooDao.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.Foo; - -public interface IFooDao extends IOperations { - // -} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IOperations.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IOperations.java deleted file mode 100644 index 8c5a5e1aed..0000000000 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IOperations.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung.persistence.dao; - -import java.io.Serializable; -import java.util.List; - -public interface IOperations { - - T findOne(final long id); - - List findAll(); - - void create(final T entity); - - T update(final T entity); - - void delete(final T entity); - - void deleteById(final long entityId); - -} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Foo.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Foo.java deleted file mode 100644 index 8e1dee33e8..0000000000 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Foo.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.baeldung.persistence.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Foo implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - @Column(nullable = false) - private String name; - - public Foo() { - super(); - } - - public Foo(final String name) { - super(); - - 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; - } - - // - - @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/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/EventService.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/EventService.java deleted file mode 100644 index 6171751cc5..0000000000 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/EventService.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.baeldung.persistence.service; - - -import org.baeldung.persistence.dao.IEventDao; -import org.baeldung.persistence.model.Event; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class EventService { - - @Autowired - private IEventDao dao; - - public EventService() { - super(); - } - - // API - - public void create(final Event entity) { - dao.create(entity); - } - -} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/FooService.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/FooService.java deleted file mode 100644 index b07698c438..0000000000 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/FooService.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.persistence.service; - -import org.baeldung.persistence.dao.IFooDao; -import org.baeldung.persistence.model.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class FooService { - - @Autowired - private IFooDao dao; - - public FooService() { - super(); - } - - // API - - public void create(final Foo entity) { - dao.create(entity); - } - -} diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfig.java deleted file mode 100644 index 03b9bfac33..0000000000 --- a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.baeldung.spring; - -import java.util.Properties; - -import javax.sql.DataSource; - -import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; -import org.hibernate.SessionFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.orm.hibernate3.HibernateTransactionManager; -import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.google.common.base.Preconditions; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "org.baeldung.persistence.dao", "org.baeldung.persistence.service" }) -public class PersistenceConfig { - - @Autowired - private Environment env; - - public PersistenceConfig() { - super(); - } - - @Bean - public AnnotationSessionFactoryBean sessionFactory() { - final AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean(); - sessionFactory.setDataSource(dataSource()); - sessionFactory.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); - sessionFactory.setHibernateProperties(hibernateProperties()); - - return sessionFactory; - } - - @Bean - public DataSource dataSource() { - final BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - @Autowired - public HibernateTransactionManager transactionManager(final SessionFactory sessionFactory) { - final HibernateTransactionManager txManager = new HibernateTransactionManager(); - txManager.setSessionFactory(sessionFactory); - - return txManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - final Properties hibernateProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); - return hibernateProperties; - } - -} diff --git a/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemo.cfg.xml b/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemo.cfg.xml index 8a710cc559..896c080983 100644 --- a/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemo.cfg.xml +++ b/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemo.cfg.xml @@ -4,6 +4,6 @@ "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd"> - + 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 263e902e7c..5f9e8c0107 100644 --- a/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemoPersistenceConfig.xml +++ b/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemoPersistenceConfig.xml @@ -16,7 +16,7 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> - + 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 f39817383b..03d4d022e6 100644 --- a/persistence-modules/spring-hibernate-3/src/main/resources/persistenceConfig.xml +++ b/persistence-modules/spring-hibernate-3/src/main/resources/persistenceConfig.xml @@ -9,7 +9,7 @@ - + ${hibernate.hbm2ddl.auto} diff --git a/persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/web.xml b/persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/web.xml index ad56bf28c7..69ce04fe06 100644 --- a/persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/web.xml +++ b/persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/web.xml @@ -11,7 +11,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring org.springframework.web.context.ContextLoaderListener diff --git a/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8b352b490d --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.spring.PersistenceConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..7874f7c679 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java @@ -0,0 +1,58 @@ +package com.baeldung.persistence.service; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +import com.baeldung.spring.PersistenceConfig; +import com.baeldung.persistence.model.Foo; +import org.junit.Test; +import org.junit.runner.RunWith; +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.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class FooServicePersistenceIntegrationTest { + + @Autowired + private FooService 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))); + } + + @Test(expected = InvalidDataAccessApiUsageException.class) + public final void whenSameEntityIsCreatedTwice_thenDataException() { + final Foo entity = new Foo(randomAlphabetic(8)); + service.create(entity); + service.create(entity); + } + + @Test(expected = DataAccessException.class) + public final void temp_whenInvalidEntityIsCreated_thenDataException() { + service.create(new Foo(randomAlphabetic(2048))); + } + +} diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java similarity index 90% rename from persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java index 08032660c0..99dc7b42be 100644 --- a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java +++ b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java @@ -1,7 +1,7 @@ -package org.baeldung.persistence.service; +package com.baeldung.persistence.service; -import org.baeldung.persistence.model.Event; -import org.baeldung.spring.PersistenceConfigHibernate3; +import com.baeldung.persistence.model.Event; +import com.baeldung.spring.PersistenceConfigHibernate3; import org.hamcrest.core.IsInstanceOf; import org.hibernate.HibernateException; import org.junit.Ignore; diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java similarity index 91% rename from persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java index 44cc6ca010..d3e475a244 100644 --- a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java +++ b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java @@ -1,7 +1,7 @@ -package org.baeldung.persistence.service; +package com.baeldung.persistence.service; -import org.baeldung.persistence.model.Event; -import org.baeldung.spring.PersistenceConfig; +import com.baeldung.persistence.model.Event; +import com.baeldung.spring.PersistenceConfig; import org.hamcrest.core.IsInstanceOf; import org.hibernate.HibernateException; import org.junit.Ignore; diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java similarity index 88% rename from persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java index 2b29dcb7a9..d1c5cc04e6 100644 --- a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java +++ b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java @@ -1,42 +1,42 @@ -package org.baeldung.persistence.service; - -import org.baeldung.persistence.model.Event; -import org.baeldung.spring.PersistenceXmlConfig; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.orm.hibernate3.HibernateSystemException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceXmlConfig.class }, loader = AnnotationConfigContextLoader.class) -public class NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest { - - @Autowired - EventService service; - - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @Test - public final void whenEntityIsCreated_thenNoExceptions() { - service.create(new Event("from Annotation Session Bean Factory")); - } - - @Test - @Ignore - public final void whenNoTransBoundToSession_thenException() { - expectedEx.expect(HibernateSystemException.class); - expectedEx.expectMessage("No Hibernate Session bound to thread, " - + "and configuration does not allow creation of " - + "non-transactional one here"); - service.create(new Event("from Annotation Session Bean Factory")); - } - -} +package com.baeldung.persistence.service; + +import com.baeldung.persistence.model.Event; +import com.baeldung.spring.PersistenceXmlConfig; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.orm.hibernate3.HibernateSystemException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceXmlConfig.class }, loader = AnnotationConfigContextLoader.class) +public class NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest { + + @Autowired + EventService service; + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Event("from Annotation Session Bean Factory")); + } + + @Test + @Ignore + public final void whenNoTransBoundToSession_thenException() { + expectedEx.expect(HibernateSystemException.class); + expectedEx.expectMessage("No Hibernate Session bound to thread, " + + "and configuration does not allow creation of " + + "non-transactional one here"); + service.create(new Event("from Annotation Session Bean Factory")); + } + +} diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java similarity index 86% rename from persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java index 1bc6c07b18..1df6aa172c 100644 --- a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java +++ b/persistence-modules/spring-hibernate-3/src/test/java/com/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java @@ -1,39 +1,38 @@ -package org.baeldung.persistence.service; - -import org.baeldung.persistence.model.Event; -import org.hibernate.HibernateException; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.orm.hibernate3.HibernateSystemException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "classpath:exceptionDemoPersistenceConfig.xml" }) -public class NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest { - - @Autowired - EventService service; - - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @Test - public final void whenEntityIsCreated_thenNoExceptions() { - service.create(new Event("from local session bean factory")); - } - - @Test - @Ignore - public final void whenNoTransBoundToSession_thenException() { - expectedEx.expect(HibernateException.class); - expectedEx.expectMessage("No Hibernate Session bound to thread, " - + "and configuration does not allow creation " - + "of non-transactional one here"); - service.create(new Event("from local session bean factory")); - } -} +package com.baeldung.persistence.service; + +import com.baeldung.persistence.model.Event; +import org.hibernate.HibernateException; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:exceptionDemoPersistenceConfig.xml" }) +public class NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest { + + @Autowired + EventService service; + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Event("from local session bean factory")); + } + + @Test + @Ignore + public final void whenNoTransBoundToSession_thenException() { + expectedEx.expect(HibernateException.class); + expectedEx.expectMessage("No Hibernate Session bound to thread, " + + "and configuration does not allow creation " + + "of non-transactional one here"); + service.create(new Event("from local session bean factory")); + } +} diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 956d5279a3..0000000000 --- a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.PersistenceConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java deleted file mode 100644 index b6e4a5592f..0000000000 --- a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; - -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.FooService; -import org.baeldung.spring.PersistenceConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -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.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class FooServicePersistenceIntegrationTest { - - @Autowired - private FooService 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))); - } - - @Test(expected = InvalidDataAccessApiUsageException.class) - public final void whenSameEntityIsCreatedTwice_thenDataException() { - final Foo entity = new Foo(randomAlphabetic(8)); - service.create(entity); - service.create(entity); - } - - @Test(expected = DataAccessException.class) - public final void temp_whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - -} diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index a74600a47f..6d7526a13b 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -4,11 +4,12 @@ This module contains articles about Hibernate 5 with Spring. ### Relevant articles -- [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) -- [JPA Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) -- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search) +- [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many) +- [Programmatic Transactions in the Spring TestContext Framework](https://www.baeldung.com/spring-test-programmatic-transactions) +- [JPA Criteria Queries](https://www.baeldung.com/hibernate-criteria-queries) +- [Introduction to Hibernate Search](https://www.baeldung.com/hibernate-search) - [@DynamicUpdate with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-dynamicupdate) - [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) - [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) - [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) +- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml index 546dcb1ce0..8a8b6c15e3 100644 --- a/persistence-modules/spring-hibernate-5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ @@ -125,16 +124,6 @@ - - spring-hibernate-5 - - - src/main/resources - true - - - - 5.0.2.RELEASE diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e19965773e --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index 31877255b2..7d95e0f342 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -8,6 +8,7 @@ import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; +import org.junit.Ignore; import org.junit.Test; import com.baeldung.hibernate.criteria.model.Item; @@ -24,6 +25,7 @@ public class HibernateCriteriaIntegrationTest { final private ApplicationView av = new ApplicationView(); @Test + @Ignore public void testPerformanceOfCriteria() { assertFalse(av.checkIfCriteriaTimeLower()); } diff --git a/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 6815ebf304..0000000000 --- a/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.spring.PersistenceConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index c9e2b5abfc..a5a72a9b7e 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -3,13 +3,12 @@ This module contains articles about Spring with Hibernate 4 ### Relevant Articles: -- [Guide to Hibernate 4 with Spring](http://www.baeldung.com/hibernate-4-spring) -- [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination) -- [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort) -- [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) -- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) +- [Guide to Hibernate 4 with Spring](https://www.baeldung.com/hibernate-4-spring) +- [Hibernate Pagination](https://www.baeldung.com/hibernate-pagination) +- [Sorting with Hibernate](https://www.baeldung.com/hibernate-sort) +- [Stored Procedures with Hibernate](https://www.baeldung.com/stored-procedures-with-hibernate-tutorial) +- [Hibernate: save, persist, update, merge, saveOrUpdate](https://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) +- [Eager/Lazy Loading In Hibernate](https://www.baeldung.com/hibernate-lazy-eager-loading) - [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) ### Quick Start diff --git a/persistence-modules/spring-hibernate4/pom.xml b/persistence-modules/spring-hibernate4/pom.xml index 41c7fdb098..5e931d5cff 100644 --- a/persistence-modules/spring-hibernate4/pom.xml +++ b/persistence-modules/spring-hibernate4/pom.xml @@ -136,16 +136,6 @@ - - spring-hibernate4 - - - src/main/resources - true - - - - 4.3.4.RELEASE @@ -166,15 +156,6 @@ 19.0 - - 4.4.1 - 4.5 - - 2.9.0 - - - 2.7 - diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java new file mode 100644 index 0000000000..7aef08b2ce --- /dev/null +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java @@ -0,0 +1,19 @@ +package com.baeldung.hibernate.audit; + +import java.util.Optional; + +import org.springframework.data.domain.AuditorAware; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +public class AuditorAwareImpl implements AuditorAware { + + @Override + public String getCurrentAuditor() { + return Optional.ofNullable(SecurityContextHolder.getContext()) + .map(e -> e.getAuthentication()) + .map(Authentication::getName) + .orElse(null); + } + +} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java index b7cf0fadf2..6ae133ca7a 100644 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -23,6 +23,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; +import com.baeldung.hibernate.audit.AuditorAwareImpl; import com.baeldung.persistence.dao.IBarAuditableDao; import com.baeldung.persistence.dao.IBarDao; import com.baeldung.persistence.dao.IFooAuditableDao; @@ -46,7 +47,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") -@EnableJpaAuditing +@EnableJpaAuditing(auditorAwareRef = "auditorProvider") @PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "com.baeldung.persistence" }) public class PersistenceConfig { @@ -58,6 +59,11 @@ public class PersistenceConfig { super(); } + @Bean("auditorProvider") + public AuditorAwareImpl auditorAwareImpl() { + return new AuditorAwareImpl(); + } + @Bean public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e19965773e --- /dev/null +++ b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 6815ebf304..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.spring.PersistenceConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index 489d990fc3..599a667a13 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -4,13 +4,13 @@ ### Relevant Articles: -- [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) -- [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database) -- [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source) -- [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) +- [The DAO with JPA and Spring](https://www.baeldung.com/spring-dao-jpa) +- [JPA Pagination](https://www.baeldung.com/jpa-pagination) +- [Sorting with JPA](https://www.baeldung.com/jpa-sort) +- [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database) +- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source) +- [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys) +- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) - [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many) - [Spring Persistence (Hibernate and JPA) with a JNDI datasource](https://www.baeldung.com/spring-persistence-hibernate-and-jpa-with-a-jndi-datasource/) diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 4972a20cf6..ef05269c92 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ @@ -129,27 +128,6 @@ - - spring-jpa - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - src/main/webapp - false - - - - - 5.1.5.RELEASE diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/annotations/MyUtilityRepository.java similarity index 90% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/annotations/MyUtilityRepository.java index 5fe54b80d9..a23e9d9fe4 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/annotations/MyUtilityRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.annotations; +package com.baeldung.annotations; import java.io.Serializable; import java.util.Optional; diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/annotations/Person.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/annotations/Person.java new file mode 100644 index 0000000000..b881535e05 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/annotations/Person.java @@ -0,0 +1,54 @@ +package com.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 com.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/com/baeldung/annotations/PersonRepository.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/annotations/PersonRepository.java new file mode 100644 index 0000000000..77b7067f11 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/annotations/PersonRepository.java @@ -0,0 +1,32 @@ +package com.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/com/baeldung/config/PersistenceJPAConfig.java similarity index 94% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/config/PersistenceJPAConfig.java index ec0d4bca3c..4eda4d9274 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/config/PersistenceJPAConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import java.util.Properties; @@ -25,8 +25,8 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "org.baeldung.persistence" }) -@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") +@ComponentScan({ "com.baeldung.persistence" }) +@EnableJpaRepositories(basePackages = "com.baeldung.persistence.dao") public class PersistenceJPAConfig { @Autowired @@ -42,7 +42,7 @@ public class PersistenceJPAConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigXml.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/config/PersistenceJPAConfigXml.java similarity index 83% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigXml.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/config/PersistenceJPAConfigXml.java index 3df36e62ee..95224a4662 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigXml.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/config/PersistenceJPAConfigXml.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ImportResource; @@ -6,7 +6,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; // @Configuration @EnableTransactionManagement -@ComponentScan({ "org.baeldung.persistence" }) +@ComponentScan({ "com.baeldung.persistence" }) @ImportResource({ "classpath:jpaConfig.xml" }) public class PersistenceJPAConfigXml { diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/config/SpringWebConfig.java similarity index 92% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/config/SpringWebConfig.java index 6afb271b10..475970d1f0 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/config/SpringWebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -10,7 +10,7 @@ import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration -@ComponentScan({ "org.baeldung.web" }) +@ComponentScan({ "com.baeldung.web" }) public class SpringWebConfig extends WebMvcConfigurerAdapter { @Bean diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJpaConfig.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/config/StudentJpaConfig.java similarity index 94% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJpaConfig.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/config/StudentJpaConfig.java index 17047cbab2..08f37ea806 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJpaConfig.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/config/StudentJpaConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import java.util.Properties; @@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = "org.baeldung.inmemory.persistence.dao") +@EnableJpaRepositories(basePackages = "com.baeldung.inmemory.persistence.dao") @PropertySource("persistence-student.properties") @EnableTransactionManagement public class StudentJpaConfig { @@ -41,7 +41,7 @@ public class StudentJpaConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.inmemory.persistence.model" }); + em.setPackagesToScan(new String[] { "com.baeldung.inmemory.persistence.model" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/config/WebInitializer.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/config/WebInitializer.java new file mode 100644 index 0000000000..be81cca76b --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/config/WebInitializer.java @@ -0,0 +1,20 @@ +package com.baeldung.config; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + @Override + protected Class[] getRootConfigClasses() { + return new Class[] { PersistenceJPAConfig.class }; + } + + @Override + protected Class[] getServletConfigClasses() { + return new Class[] { SpringWebConfig.class }; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDao.java similarity index 95% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDao.java index 9e19cf4ed9..e8117ba4fa 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDao.java @@ -1,4 +1,4 @@ -package org.baeldung.dsrouting; +package com.baeldung.dsrouting; import javax.sql.DataSource; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDataSourceRouter.java similarity index 91% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDataSourceRouter.java index 997e461cde..a9f5d83b55 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDataSourceRouter.java @@ -1,4 +1,4 @@ -package org.baeldung.dsrouting; +package com.baeldung.dsrouting; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDatabase.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDatabase.java new file mode 100644 index 0000000000..d8d178a4d5 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDatabase.java @@ -0,0 +1,7 @@ +package com.baeldung.dsrouting; + +public enum ClientDatabase { + + CLIENT_A, CLIENT_B + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDatabaseContextHolder.java similarity index 95% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDatabaseContextHolder.java index c08559e877..ae5d16cad2 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientDatabaseContextHolder.java @@ -1,4 +1,4 @@ -package org.baeldung.dsrouting; +package com.baeldung.dsrouting; import org.springframework.util.Assert; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientService.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientService.java similarity index 94% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientService.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientService.java index 4b63c6333c..59b3d1660a 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientService.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/dsrouting/ClientService.java @@ -1,4 +1,4 @@ -package org.baeldung.dsrouting; +package com.baeldung.dsrouting; /** * Service layer code for datasource routing example. Here, the service methods are responsible diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/dao/ManyStudentRepository.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/dao/ManyStudentRepository.java new file mode 100644 index 0000000000..a2aa0c5780 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/dao/ManyStudentRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.inmemory.persistence.dao; + +import com.baeldung.inmemory.persistence.model.ManyStudent; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface ManyStudentRepository extends JpaRepository { + List findByManyTags_Name(String name); +} diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/dao/ManyTagRepository.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/dao/ManyTagRepository.java new file mode 100644 index 0000000000..63337f3cb9 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/dao/ManyTagRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.inmemory.persistence.dao; + +import com.baeldung.inmemory.persistence.model.ManyTag; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ManyTagRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/dao/StudentRepository.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/dao/StudentRepository.java new file mode 100644 index 0000000000..8ac91fbf0c --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/dao/StudentRepository.java @@ -0,0 +1,24 @@ +package com.baeldung.inmemory.persistence.dao; + +import com.baeldung.inmemory.persistence.model.Student; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; + +public interface StudentRepository extends JpaRepository { + + @Query("SELECT s FROM Student s JOIN s.tags t WHERE t = LOWER(:tag)") + List retrieveByTag(@Param("tag") String tag); + + @Query("SELECT s FROM Student s JOIN s.tags t WHERE s.name = LOWER(:name) AND t = LOWER(:tag)") + List retrieveByNameFilterByTag(@Param("name") String name, @Param("tag") String tag); + + @Query("SELECT s FROM Student s JOIN s.skillTags t WHERE t.name = LOWER(:tagName) AND t.value > :tagValue") + List retrieveByNameFilterByMinimumSkillTag(@Param("tagName") String tagName, @Param("tagValue") int tagValue); + + @Query("SELECT s FROM Student s JOIN s.kvTags t WHERE t.key = LOWER(:key)") + List retrieveByKeyTag(@Param("key") String key); + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/KVTag.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/KVTag.java similarity index 91% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/KVTag.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/KVTag.java index 1522744116..1fc186f4ce 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/KVTag.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/KVTag.java @@ -1,4 +1,4 @@ -package org.baeldung.inmemory.persistence.model; +package com.baeldung.inmemory.persistence.model; import javax.persistence.Embeddable; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/LocationTag.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/LocationTag.java similarity index 92% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/LocationTag.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/LocationTag.java index 3acdbbe6fe..b12ad9fbd1 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/LocationTag.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/LocationTag.java @@ -1,4 +1,4 @@ -package org.baeldung.inmemory.persistence.model; +package com.baeldung.inmemory.persistence.model; import javax.persistence.Embeddable; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyStudent.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/ManyStudent.java similarity index 94% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyStudent.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/ManyStudent.java index 8343edc9cd..190740d582 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyStudent.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/ManyStudent.java @@ -1,4 +1,4 @@ -package org.baeldung.inmemory.persistence.model; +package com.baeldung.inmemory.persistence.model; import javax.persistence.*; import java.util.HashSet; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyTag.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/ManyTag.java similarity index 93% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyTag.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/ManyTag.java index e820506544..5af898f7df 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyTag.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/ManyTag.java @@ -1,4 +1,4 @@ -package org.baeldung.inmemory.persistence.model; +package com.baeldung.inmemory.persistence.model; import javax.persistence.*; import java.util.HashSet; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/SkillTag.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/SkillTag.java similarity index 90% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/SkillTag.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/SkillTag.java index 490ee0a18e..738b5d0b36 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/SkillTag.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/SkillTag.java @@ -1,4 +1,4 @@ -package org.baeldung.inmemory.persistence.model; +package com.baeldung.inmemory.persistence.model; import javax.persistence.Embeddable; diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/Student.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/Student.java new file mode 100644 index 0000000000..f0e824e165 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/inmemory/persistence/model/Student.java @@ -0,0 +1,74 @@ +package com.baeldung.inmemory.persistence.model; + +import java.util.ArrayList; +import java.util.List; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + private long id; + private String name; + + @ElementCollection + private List tags = new ArrayList<>(); + + @ElementCollection + private List skillTags = new ArrayList<>(); + + @ElementCollection + private List kvTags = new ArrayList<>(); + + public Student() { + } + + public Student(long id, String name) { + super(); + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags.addAll(tags); + } + + public List getSkillTags() { + return skillTags; + } + + public void setSkillTags(List skillTags) { + this.skillTags.addAll(skillTags); + } + + public List getKVTags() { + return this.kvTags; + } + + public void setKVTags(List kvTags) { + this.kvTags.addAll(kvTags); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/AbstractJpaDAO.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/AbstractJpaDAO.java similarity index 96% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/AbstractJpaDAO.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/AbstractJpaDAO.java index 13007d9fcc..b4827cc7e1 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/AbstractJpaDAO.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/AbstractJpaDAO.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.dao; +package com.baeldung.persistence.dao; import java.io.Serializable; import java.util.List; diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookRepository.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookRepository.java new file mode 100644 index 0000000000..48620f4ff1 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.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/com/baeldung/persistence/dao/BookRepositoryCustom.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookRepositoryCustom.java new file mode 100644 index 0000000000..1b46d0ecc3 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookRepositoryCustom.java @@ -0,0 +1,11 @@ +package com.baeldung.persistence.dao; + +import java.util.List; + +import com.baeldung.persistence.model.Book; + +public interface BookRepositoryCustom { + + List findBooksByAuthorNameAndTitle(String authorName, String title); + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryImpl.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookRepositoryImpl.java similarity index 93% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryImpl.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookRepositoryImpl.java index 6e9aa998d7..241a4c05aa 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryImpl.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookRepositoryImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.dao; +package com.baeldung.persistence.dao; import java.util.ArrayList; import java.util.List; @@ -10,7 +10,7 @@ import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import org.baeldung.persistence.model.Book; +import com.baeldung.persistence.model.Book; import org.springframework.stereotype.Repository; @Repository diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookService.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookService.java new file mode 100644 index 0000000000..f02f9daa11 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookService.java @@ -0,0 +1,25 @@ +package com.baeldung.persistence.dao; + +import static com.baeldung.persistence.dao.BookSpecifications.hasAuthor; +import static com.baeldung.persistence.dao.BookSpecifications.titleContains; +import static org.springframework.data.jpa.domain.Specifications.where; + +import java.util.List; + +import com.baeldung.persistence.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/dao/BookSpecifications.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookSpecifications.java similarity index 82% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookSpecifications.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookSpecifications.java index ed9540060d..16646a5b4b 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookSpecifications.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/BookSpecifications.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.dao; +package com.baeldung.persistence.dao; -import org.baeldung.persistence.model.Book; +import com.baeldung.persistence.model.Book; import org.springframework.data.jpa.domain.Specification; public class BookSpecifications { diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/FooDao.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/FooDao.java new file mode 100644 index 0000000000..a4ed7d97b4 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/FooDao.java @@ -0,0 +1,17 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.Foo; +import org.springframework.stereotype.Repository; + +@Repository +public class FooDao extends AbstractJpaDAO implements IFooDao { + + public FooDao() { + super(); + + setClazz(Foo.class); + } + + // API + +} diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/IFooDao.java new file mode 100644 index 0000000000..8a4877aa79 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/dao/IFooDao.java @@ -0,0 +1,21 @@ +package com.baeldung.persistence.dao; + +import java.util.List; + +import com.baeldung.persistence.model.Foo; + +public interface IFooDao { + + Foo findOne(long id); + + List findAll(); + + void create(Foo entity); + + Foo update(Foo entity); + + void delete(Foo entity); + + void deleteById(long entityId); + +} diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/model/Bar.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/model/Bar.java new file mode 100644 index 0000000000..5a88ecc6cf --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/model/Bar.java @@ -0,0 +1,102 @@ +package com.baeldung.persistence.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.OrderBy; + +@Entity +public class Bar implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false) + private String name; + + @OneToMany(mappedBy = "bar", fetch = FetchType.EAGER, cascade = CascadeType.ALL) + @OrderBy("name ASC") + List fooList; + + public Bar() { + super(); + } + + public Bar(final String name) { + super(); + + 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; + } + + public List getFooList() { + return fooList; + } + + public void setFooList(final List fooList) { + this.fooList = fooList; + } + + // + + @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(); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/model/Book.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/model/Book.java new file mode 100644 index 0000000000..507043dd56 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/model/Book.java @@ -0,0 +1,36 @@ +package com.baeldung.persistence.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/com/baeldung/persistence/model/Foo.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/model/Foo.java new file mode 100644 index 0000000000..7897bba4e4 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/model/Foo.java @@ -0,0 +1,92 @@ +package com.baeldung.persistence.model; + +import org.hibernate.annotations.CacheConcurrencyStrategy; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +@Cacheable +@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) +public class Foo implements Serializable { + + private static final long serialVersionUID = 1L; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "ID") + private Long id; + @Column(name = "NAME") + private String name; + + @ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar; + + 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/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/multiple/model/user/Possession.java similarity index 96% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/multiple/model/user/Possession.java index 7aff5f51d0..6ad6b8e603 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/com/baeldung/persistence/multiple/model/user/Possession.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.multiple.model.user; +package com.baeldung.persistence.multiple.model.user; import javax.persistence.*; diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/multiple/model/user/User.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/multiple/model/user/User.java new file mode 100644 index 0000000000..3ebb1e0156 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/multiple/model/user/User.java @@ -0,0 +1,74 @@ +package com.baeldung.persistence.multiple.model.user; + +import javax.persistence.*; +import java.util.List; + +@Entity +@Table(schema = "spring_jpa_user") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + + private String name; + + @Column(unique = true, nullable = false) + private String email; + + private int age; + + @OneToMany + List possessionList; + + public User() { + 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 String getEmail() { + return email; + } + + public void setEmail(final String email) { + this.email = email; + } + + 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/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/service/FooService.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/service/FooService.java new file mode 100644 index 0000000000..ace36dd03b --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/persistence/service/FooService.java @@ -0,0 +1,36 @@ +package com.baeldung.persistence.service; + +import java.util.List; + +import com.baeldung.persistence.dao.IFooDao; +import com.baeldung.persistence.model.Foo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class FooService { + + @Autowired + private IFooDao dao; + + public FooService() { + super(); + } + + // API + + public void create(final Foo entity) { + dao.create(entity); + } + + public Foo findOne(final long id) { + return dao.findOne(id); + } + + public List findAll() { + return dao.findAll(); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/sqlfiles/Country.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/sqlfiles/Country.java new file mode 100644 index 0000000000..f2be33adfd --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/sqlfiles/Country.java @@ -0,0 +1,36 @@ +package com.baeldung.sqlfiles; + +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/persistence-modules/spring-jpa/src/main/java/com/baeldung/web/MainController.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/web/MainController.java new file mode 100644 index 0000000000..c0d4743ae7 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/web/MainController.java @@ -0,0 +1,21 @@ +package com.baeldung.web; + +import com.baeldung.persistence.service.FooService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class MainController { + + @Autowired + private FooService fooService; + + @GetMapping("/") + public String main(Model model) { + model.addAttribute("foos", fooService.findAll()); + return "index"; + } + +} 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 deleted file mode 100644 index 309a4f43e1..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/Person.java +++ /dev/null @@ -1,54 +0,0 @@ -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 deleted file mode 100644 index 58558860ff..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/PersonRepository.java +++ /dev/null @@ -1,32 +0,0 @@ -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/WebInitializer.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java deleted file mode 100644 index cf6e69eb39..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung.config; - -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; - -public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { - @Override - protected Class[] getRootConfigClasses() { - return new Class[] { PersistenceJPAConfig.class }; - } - - @Override - protected Class[] getServletConfigClasses() { - return new Class[] { SpringWebConfig.class }; - } - - @Override - protected String[] getServletMappings() { - return new String[] { "/" }; - } -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabase.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabase.java deleted file mode 100644 index 619b8707d8..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabase.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.baeldung.dsrouting; - -public enum ClientDatabase { - - CLIENT_A, CLIENT_B - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyStudentRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyStudentRepository.java deleted file mode 100644 index a03b2950a0..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyStudentRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.inmemory.persistence.dao; - -import org.baeldung.inmemory.persistence.model.ManyStudent; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; - -public interface ManyStudentRepository extends JpaRepository { - List findByManyTags_Name(String name); -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyTagRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyTagRepository.java deleted file mode 100644 index b7d991de32..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyTagRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.baeldung.inmemory.persistence.dao; - -import org.baeldung.inmemory.persistence.model.ManyTag; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface ManyTagRepository extends JpaRepository { -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java deleted file mode 100644 index ffe1a68558..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.inmemory.persistence.dao; - -import org.baeldung.inmemory.persistence.model.Student; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import java.util.List; - -public interface StudentRepository extends JpaRepository { - - @Query("SELECT s FROM Student s JOIN s.tags t WHERE t = LOWER(:tag)") - List retrieveByTag(@Param("tag") String tag); - - @Query("SELECT s FROM Student s JOIN s.tags t WHERE s.name = LOWER(:name) AND t = LOWER(:tag)") - List retrieveByNameFilterByTag(@Param("name") String name, @Param("tag") String tag); - - @Query("SELECT s FROM Student s JOIN s.skillTags t WHERE t.name = LOWER(:tagName) AND t.value > :tagValue") - List retrieveByNameFilterByMinimumSkillTag(@Param("tagName") String tagName, @Param("tagValue") int tagValue); - - @Query("SELECT s FROM Student s JOIN s.kvTags t WHERE t.key = LOWER(:key)") - List retrieveByKeyTag(@Param("key") String key); - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java deleted file mode 100644 index 07aa3ef9ef..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.baeldung.inmemory.persistence.model; - -import java.util.ArrayList; -import java.util.List; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.Id; - -@Entity -public class Student { - - @Id - private long id; - private String name; - - @ElementCollection - private List tags = new ArrayList<>(); - - @ElementCollection - private List skillTags = new ArrayList<>(); - - @ElementCollection - private List kvTags = new ArrayList<>(); - - public Student() { - } - - public Student(long id, String name) { - super(); - this.id = id; - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags.addAll(tags); - } - - public List getSkillTags() { - return skillTags; - } - - public void setSkillTags(List skillTags) { - this.skillTags.addAll(skillTags); - } - - public List getKVTags() { - return this.kvTags; - } - - public void setKVTags(List kvTags) { - this.kvTags.addAll(kvTags); - } - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepository.java deleted file mode 100644 index 114cf48c7c..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.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/dao/BookRepositoryCustom.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryCustom.java deleted file mode 100644 index b939907572..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryCustom.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.baeldung.persistence.dao; - -import java.util.List; - -import org.baeldung.persistence.model.Book; - -public interface BookRepositoryCustom { - - List findBooksByAuthorNameAndTitle(String authorName, String title); - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookService.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookService.java deleted file mode 100644 index 88b769e9bf..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookService.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung.persistence.dao; - -import static org.baeldung.persistence.dao.BookSpecifications.hasAuthor; -import static org.baeldung.persistence.dao.BookSpecifications.titleContains; -import static org.springframework.data.jpa.domain.Specifications.where; - -import java.util.List; - -import org.baeldung.persistence.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/dao/FooDao.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/FooDao.java deleted file mode 100644 index 77978c5cf2..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/FooDao.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.Foo; -import org.springframework.stereotype.Repository; - -@Repository -public class FooDao extends AbstractJpaDAO implements IFooDao { - - public FooDao() { - super(); - - setClazz(Foo.class); - } - - // API - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/IFooDao.java deleted file mode 100644 index f5799522e2..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/IFooDao.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.persistence.dao; - -import java.util.List; - -import org.baeldung.persistence.model.Foo; - -public interface IFooDao { - - Foo findOne(long id); - - List findAll(); - - void create(Foo entity); - - Foo update(Foo entity); - - void delete(Foo entity); - - void deleteById(long entityId); - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Bar.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Bar.java deleted file mode 100644 index b602e57562..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Bar.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.baeldung.persistence.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; - -@Entity -public class Bar implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - @Column(nullable = false) - private String name; - - @OneToMany(mappedBy = "bar", fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @OrderBy("name ASC") - List fooList; - - public Bar() { - super(); - } - - public Bar(final String name) { - super(); - - 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; - } - - public List getFooList() { - return fooList; - } - - public void setFooList(final List fooList) { - this.fooList = fooList; - } - - // - - @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(); - } - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Book.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Book.java deleted file mode 100644 index 754bd179d1..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Book.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.persistence.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/model/Foo.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java deleted file mode 100644 index 5294860311..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.baeldung.persistence.model; - -import org.hibernate.annotations.CacheConcurrencyStrategy; - -import javax.persistence.*; -import java.io.Serializable; - -@Entity -@Cacheable -@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) -public class Foo implements Serializable { - - private static final long serialVersionUID = 1L; - - public Foo() { - super(); - } - - public Foo(final String name) { - super(); - - this.name = name; - } - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "ID") - private Long id; - @Column(name = "NAME") - private String name; - - @ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER) - @JoinColumn(name = "BAR_ID") - private Bar bar; - - 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/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 deleted file mode 100644 index 6fb9de4a47..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.baeldung.persistence.multiple.model.user; - -import javax.persistence.*; -import java.util.List; - -@Entity -@Table(schema = "spring_jpa_user") -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private int id; - - private String name; - - @Column(unique = true, nullable = false) - private String email; - - private int age; - - @OneToMany - List possessionList; - - public User() { - 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 String getEmail() { - return email; - } - - public void setEmail(final String email) { - this.email = email; - } - - 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/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/service/FooService.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/service/FooService.java deleted file mode 100644 index 6d1bb0adbe..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/service/FooService.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.persistence.service; - -import java.util.List; - -import org.baeldung.persistence.dao.IFooDao; -import org.baeldung.persistence.model.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class FooService { - - @Autowired - private IFooDao dao; - - public FooService() { - super(); - } - - // API - - public void create(final Foo entity) { - dao.create(entity); - } - - public Foo findOne(final long id) { - return dao.findOne(id); - } - - public List findAll() { - return dao.findAll(); - } - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java deleted file mode 100644 index 922f55cbf6..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.sqlfiles; - -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/persistence-modules/spring-jpa/src/main/java/org/baeldung/web/MainController.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/web/MainController.java deleted file mode 100644 index 6900482de8..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/web/MainController.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.web; - -import org.baeldung.persistence.service.FooService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; - -@Controller -public class MainController { - - @Autowired - private FooService fooService; - - @GetMapping("/") - public String main(Model model) { - model.addAttribute("foos", fooService.findAll()); - return "index"; - } - -} diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence.xml b/persistence-modules/spring-jpa/src/main/resources/persistence.xml index 6304fa0a65..57687c306d 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence.xml +++ b/persistence-modules/spring-jpa/src/main/resources/persistence.xml @@ -11,7 +11,7 @@ - + + + org.springframework + spring-orm + ${org.springframework.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + + + com.h2database + h2 + ${h2.version} + test + + + + + org.springframework + spring-test + ${org.springframework.version} + test + + + org.mockito + mockito-core + ${mockito.version} + test + + + + + + 5.2.4.RELEASE + + 1.4.200 + + 3.3.3 + + + \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java new file mode 100644 index 0000000000..bd6fe0fb15 --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java @@ -0,0 +1,42 @@ +package com.baeldung.jdbc; + +public class Employee { + private int id; + + private String firstName; + + private String lastName; + + + public Employee(int id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + +} diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java new file mode 100644 index 0000000000..2ea42381eb --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java @@ -0,0 +1,67 @@ +package com.baeldung.jdbc; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; +import org.springframework.jdbc.core.namedparam.SqlParameterSource; +import org.springframework.stereotype.Repository; + +@Repository +public class EmployeeDAO { + private JdbcTemplate jdbcTemplate; + private NamedParameterJdbcTemplate namedJdbcTemplate; + + public void setDataSource(DataSource dataSource) { + jdbcTemplate = new JdbcTemplate(dataSource); + namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); + } + + public int getCountOfEmployees() { + return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class); + } + + public List getEmployeesFromIdListNamed(List ids) { + SqlParameterSource parameters = new MapSqlParameterSource("ids", ids); + List employees = namedJdbcTemplate.query( + "SELECT * FROM EMPLOYEE WHERE id IN (:ids)", + parameters, + (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); + + return employees; + } + + public List getEmployeesFromIdList(List ids) { + String inSql = String.join(",", Collections.nCopies(ids.size(), "?")); + List employees = jdbcTemplate.query( + String.format("SELECT * FROM EMPLOYEE WHERE id IN (%s)", inSql), + ids.toArray(), + (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); + + return employees; + } + + public List getEmployeesFromLargeIdList(List ids) { + jdbcTemplate.execute("CREATE TEMPORARY TABLE IF NOT EXISTS employee_tmp (id INT NOT NULL)"); + + List employeeIds = new ArrayList<>(); + for (Integer id : ids) { + employeeIds.add(new Object[] { id }); + } + jdbcTemplate.batchUpdate("INSERT INTO employee_tmp VALUES(?)", employeeIds); + + List employees = jdbcTemplate.query( + "SELECT * FROM EMPLOYEE WHERE id IN (SELECT id FROM employee_tmp)", + (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); + + jdbcTemplate.update("DELETE FROM employee_tmp"); + + return employees; + } + +} diff --git a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql new file mode 100644 index 0000000000..be102431ca --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql @@ -0,0 +1,6 @@ +CREATE TABLE EMPLOYEE +( + ID int NOT NULL PRIMARY KEY, + FIRST_NAME varchar(255), + LAST_NAME varchar(255) +); \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql new file mode 100644 index 0000000000..5421c09849 --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql @@ -0,0 +1,4 @@ +INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling'); +INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth'); +INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds'); +INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie'); \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java b/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java new file mode 100644 index 0000000000..369725bafd --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java @@ -0,0 +1,107 @@ +package com.baeldung.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import javax.sql.DataSource; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) + +public class EmployeeDAOUnitTest { + @Mock + JdbcTemplate jdbcTemplate; + + DataSource dataSource; + + @Before + public void setup() { + dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) + .generateUniqueName(true) + .addScript("classpath:jdbc/schema.sql") + .addScript("classpath:jdbc/test-data.sql") + .build(); + + } + + @Test + public void whenMockJdbcTemplate_thenReturnCorrectEmployeeCount() { + EmployeeDAO employeeDAO = new EmployeeDAO(); + ReflectionTestUtils.setField(employeeDAO, "jdbcTemplate", jdbcTemplate); + Mockito.when(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class)) + .thenReturn(4); + + assertEquals(4, employeeDAO.getCountOfEmployees()); + + Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(Integer.class))) + .thenReturn(3); + + assertEquals(3, employeeDAO.getCountOfEmployees()); + } + + @Test + public void whenInjectInMemoryDataSource_thenReturnCorrectEmployeeCount() { + EmployeeDAO employeeDAO = new EmployeeDAO(); + employeeDAO.setDataSource(dataSource); + + assertEquals(4, employeeDAO.getCountOfEmployees()); + } + + @Test + public void givenSmallIdList_whenGetEmployeesFromIdList_thenReturnCorrectEmployees() { + List ids = new ArrayList<>(); + ids.add(1); + ids.add(3); + ids.add(4); + EmployeeDAO employeeDAO = new EmployeeDAO(); + employeeDAO.setDataSource(dataSource); + + List employees = employeeDAO.getEmployeesFromIdList(ids); + + assertEquals(3, employees.size()); + assertEquals(1, employees.get(0).getId()); + assertEquals(3, employees.get(1).getId()); + assertEquals(4, employees.get(2).getId()); + + employees = employeeDAO.getEmployeesFromIdListNamed(ids); + + assertEquals(3, employees.size()); + assertEquals(1, employees.get(0).getId()); + assertEquals(3, employees.get(1).getId()); + assertEquals(4, employees.get(2).getId()); + } + + @Test + public void givenLargeIdList_whenGetEmployeesFromIdList_thenReturnCorrectEmployees() { + List ids = new ArrayList<>(); + ids.add(1); + ids.add(3); + ids.add(4); + EmployeeDAO employeeDAO = new EmployeeDAO(); + employeeDAO.setDataSource(dataSource); + + List employees = employeeDAO.getEmployeesFromLargeIdList(ids); + + assertEquals(3, employees.size()); + assertEquals(1, employees.get(0).getId()); + assertEquals(3, employees.get(1).getId()); + assertEquals(4, employees.get(2).getId()); + + ids.clear(); + ids.add(2); + employees = employeeDAO.getEmployeesFromLargeIdList(ids); + assertEquals(1, employees.size()); + } +} diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index db0d0ce83c..d665433eef 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -6,7 +6,7 @@ ### Relevant Articles: - [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) - [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) -- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) +- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate) - [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) - [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index 3ecb9c3d7d..7318ec55bd 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ @@ -25,7 +24,11 @@ spring-context ${org.springframework.version} - + + org.springframework + spring-aspects + ${org.springframework.version} + org.hibernate @@ -106,13 +109,6 @@ - spring-persistence-simple - - - src/main/resources - true - - com.mysema.maven @@ -136,12 +132,13 @@ - 5.1.6.RELEASE + 5.2.6.RELEASE - 5.4.2.Final - 6.0.6 - 2.1.6.RELEASE + 5.4.13.Final + 8.0.19 + 1.4.200 + 2.2.7.RELEASE 9.0.0.M26 1.1 4.2.1 diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java index 569971e311..cdddbaa787 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java @@ -1,9 +1,7 @@ package com.baeldung.config; -import java.util.Properties; - -import javax.sql.DataSource; - +import com.baeldung.persistence.service.FooService; +import com.google.common.base.Preconditions; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -13,7 +11,6 @@ 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.hibernate5.HibernateTransactionManager; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.orm.jpa.JpaTransactionManager; @@ -23,16 +20,14 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import com.baeldung.hibernate.dao.FooDao; -import com.baeldung.jpa.dao.IFooDao; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.Properties; @Configuration @EnableTransactionManagement -@EnableJpaRepositories(basePackages = { "com.baeldung.hibernate.dao" }, transactionManagerRef = "jpaTransactionManager") @EnableJpaAuditing @PropertySource({ "classpath:persistence-mysql.properties" }) -@ComponentScan({ "com.baeldung.persistence", "com.baeldung.hibernate.dao" }) +@ComponentScan(basePackages = { "com.baeldung.persistence.dao", "com.baeldung.jpa.dao" }) public class PersistenceConfig { @Autowired @@ -46,7 +41,7 @@ public class PersistenceConfig { public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + sessionFactory.setPackagesToScan("com.baeldung.persistence.model"); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; @@ -56,7 +51,7 @@ public class PersistenceConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); emf.setDataSource(restDataSource()); - emf.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + emf.setPackagesToScan("com.baeldung.persistence.model"); final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); emf.setJpaVendorAdapter(vendorAdapter); @@ -96,18 +91,15 @@ public class PersistenceConfig { } @Bean - public IFooDao fooHibernateDao() { - return new FooDao(); + public FooService fooService() { + return new FooService(); } - private final Properties hibernateProperties() { + private 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")); diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java index e202e45b32..e8a2aefd6b 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java @@ -1,10 +1,6 @@ package com.baeldung.config; -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - +import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -12,21 +8,21 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.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.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.Properties; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "com.baeldung.persistence","com.baeldung.jpa.dao" }) -@EnableJpaRepositories(basePackages = "com.baeldung.jpa.dao") public class PersistenceJPAConfig { @Autowired @@ -39,12 +35,12 @@ public class PersistenceJPAConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + em.setPackagesToScan("com.baeldung.persistence.model"); - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); @@ -63,9 +59,9 @@ public class PersistenceJPAConfig { } @Bean - public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + public PlatformTransactionManager transactionManager() { final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(emf); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java index 4fbc8464bb..a6542c5cb1 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java @@ -1,16 +1,15 @@ package com.baeldung.jpa.dao; -import java.io.Serializable; -import java.util.List; - import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; +import java.io.Serializable; +import java.util.List; public abstract class AbstractJpaDAO { private Class clazz; - @PersistenceContext + @PersistenceContext(unitName = "entityManagerFactory") private EntityManager entityManager; public final void setClazz(final Class clazzToSet) { diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java index 66b540a692..604923d615 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java @@ -1,9 +1,6 @@ package com.baeldung.spring.data.persistence.config; -import java.util.Properties; - -import javax.sql.DataSource; - +import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -19,14 +16,15 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.Properties; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) @ComponentScan({ "com.baeldung.spring.data.persistence" }) -// @ImportResource("classpath*:springDataPersistenceConfig.xml") -@EnableJpaRepositories(basePackages = { "com.baeldung.spring.data.persistence.dao", "com.baeldung.spring.data.persistence.jpaquery" }) +//@ImportResource("classpath*:*springDataJpaRepositoriesConfig.xml") +@EnableJpaRepositories("com.baeldung.spring.data.persistence.repository") public class PersistenceConfig { @Autowired @@ -40,10 +38,9 @@ public class PersistenceConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.spring.data.persistence.model" }); + em.setPackagesToScan("com.baeldung.spring.data.persistence.model"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - // vendorAdapter.set em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); @@ -78,7 +75,7 @@ public class PersistenceConfig { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; } diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/IFooDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/IFooDao.java deleted file mode 100644 index d2b746dc8b..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/IFooDao.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.spring.data.persistence.dao; - -import com.baeldung.spring.data.persistence.model.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/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepository.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepository.java deleted file mode 100644 index f22970c401..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepository.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.baeldung.spring.data.persistence.jpaquery; - -import java.time.LocalDate; -import java.util.Collection; -import java.util.List; -import java.util.stream.Stream; - -import com.baeldung.spring.data.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; - -public interface UserRepository extends JpaRepository, UserRepositoryCustom { - - Stream findAllByName(String name); - - @Query("SELECT u FROM User u WHERE u.status = 1") - Collection findAllActiveUsers(); - - @Query("select u from User u where u.email like '%@gmail.com'") - List findUsersWithGmailAddress(); - - @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", 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); - - @Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true) - @Modifying - void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active); - - @Modifying - @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNativePostgres(Integer status, String name); - - @Query(value = "SELECT u FROM User u WHERE u.name IN :names") - List findUserByNameList(@Param("names") Collection names); - - void deleteAllByCreationDateAfter(LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("update User u set u.active = false where u.lastLoginDate < :date") - void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("delete User u where u.active = false") - int deleteDeactivatedUsers(); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true) - void addDeletedColumn(); -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java index 09f1092644..1475eccbf0 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java @@ -1,7 +1,6 @@ package com.baeldung.spring.data.persistence.model; import javax.persistence.*; - import java.time.LocalDate; import java.util.List; import java.util.Objects; @@ -13,14 +12,22 @@ public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; + private String name; + private LocalDate creationDate; + private LocalDate lastLoginDate; + private boolean active; + private int age; + @Column(unique = true, nullable = false) private String email; + private Integer status; + @OneToMany List possessionList; @@ -28,7 +35,7 @@ public class User { super(); } - public User(String name, LocalDate creationDate,String email, Integer status) { + public User(String name, LocalDate creationDate, String email, Integer status) { this.name = name; this.creationDate = creationDate; this.email = email; @@ -75,7 +82,7 @@ public class User { public void setAge(final int age) { this.age = age; } - + public LocalDate getCreationDate() { return creationDate; } @@ -94,18 +101,18 @@ public class User { builder.append("User [name=").append(name).append(", id=").append(id).append("]"); return builder.toString(); } - + @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id == user.id && - age == user.age && - Objects.equals(name, user.name) && - Objects.equals(creationDate, user.creationDate) && - Objects.equals(email, user.email) && - Objects.equals(status, user.status); + age == user.age && + Objects.equals(name, user.name) && + Objects.equals(creationDate, user.creationDate) && + Objects.equals(email, user.email) && + Objects.equals(status, user.status); } @Override diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java new file mode 100644 index 0000000000..0b750e37e1 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.data.persistence.repository; + +import com.baeldung.spring.data.persistence.model.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/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java new file mode 100644 index 0000000000..a8e3a536c3 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java @@ -0,0 +1,98 @@ +package com.baeldung.spring.data.persistence.repository; + +import com.baeldung.spring.data.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 java.time.LocalDate; +import java.util.Collection; +import java.util.List; +import java.util.stream.Stream; + +public interface UserRepository extends JpaRepository, UserRepositoryCustom { + + Stream findAllByName(String name); + + @Query("SELECT u FROM User u WHERE u.status = 1") + Collection findAllActiveUsers(); + + @Query("select u from User u where u.email like '%@gmail.com'") + List findUsersWithGmailAddress(); + + @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", 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); + + @Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true) + @Modifying + void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active); + + @Modifying + @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true) + int updateUserSetStatusForNameNativePostgres(Integer status, String name); + + @Query(value = "SELECT u FROM User u WHERE u.name IN :names") + List findUserByNameList(@Param("names") Collection names); + + void deleteAllByCreationDateAfter(LocalDate date); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query("update User u set u.active = false where u.lastLoginDate < :date") + void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query("delete User u where u.active = false") + int deleteDeactivatedUsers(); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true) + void addDeletedColumn(); +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustom.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java similarity index 85% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustom.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java index 8bfcb93158..77e661bbbe 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustom.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java @@ -1,14 +1,16 @@ -package com.baeldung.spring.data.persistence.jpaquery; +package com.baeldung.spring.data.persistence.repository; + +import com.baeldung.spring.data.persistence.model.User; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.function.Predicate; -import com.baeldung.spring.data.persistence.model.User; - public interface UserRepositoryCustom { + List findUserByEmails(Set emails); List findAllUsersByPredicates(Collection> predicates); + } diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustomImpl.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java similarity index 85% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustomImpl.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java index f264ca0b44..366b2c54d0 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustomImpl.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java @@ -1,5 +1,10 @@ -package com.baeldung.spring.data.persistence.jpaquery; +package com.baeldung.spring.data.persistence.repository; +import com.baeldung.spring.data.persistence.model.User; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.criteria.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -7,16 +12,6 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; - -import com.baeldung.spring.data.persistence.model.User; - public class UserRepositoryCustomImpl implements UserRepositoryCustom { @PersistenceContext diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java index cd566ba9f6..c1406b8602 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java @@ -2,7 +2,7 @@ package com.baeldung.spring.data.persistence.service.impl; import com.baeldung.spring.data.persistence.model.Foo; -import com.baeldung.spring.data.persistence.dao.IFooDao; +import com.baeldung.spring.data.persistence.repository.IFooDao; import com.baeldung.spring.data.persistence.service.IFooService; import com.baeldung.spring.data.persistence.service.common.AbstractService; import org.springframework.beans.factory.annotation.Autowired; diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml index bbb61cb3e0..55546a862a 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml +++ b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml @@ -21,7 +21,7 @@ - + diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql index c86d35cdae..ef4460e267 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql +++ b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql @@ -3,5 +3,5 @@ CREATE TABLE EMPLOYEE ID int NOT NULL PRIMARY KEY, FIRST_NAME varchar(255), LAST_NAME varchar(255), - ADDRESS varchar(255), + ADDRESS varchar(255) ); \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties index b3cfd31f46..9ba4f7602a 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties +++ b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties @@ -1,7 +1,7 @@ # jdbc.X jdbc.driverClassName=com.mysql.cj.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true -jdbc.eventGeneratedId=tutorialuser +jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true&serverTimezone=UTC +jdbc.user=tutorialuser jdbc.pass=tutorialmy5ql # hibernate.X diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml b/persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml new file mode 100644 index 0000000000..91778a17af --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/springDataPersistenceConfig.xml b/persistence-modules/spring-persistence-simple/src/main/resources/springDataPersistenceConfig.xml deleted file mode 100644 index 5ea2d9c05b..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/resources/springDataPersistenceConfig.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java index fde1857ca2..72031a2232 100644 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java @@ -14,6 +14,7 @@ import org.springframework.dao.annotation.PersistenceExceptionTranslationPostPro 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; @@ -91,12 +92,12 @@ public class PersistenceTransactionalTestConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryIntegrationTest.java deleted file mode 100644 index 3bffb51917..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.spring.data.persistence.jpaquery; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.time.LocalDate; - -import com.baeldung.spring.data.persistence.config.PersistenceConfig; -import com.baeldung.spring.data.persistence.model.User; -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; -import org.springframework.transaction.annotation.Transactional; - -/** - * Created by adam. - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -public class UserRepositoryIntegrationTest extends UserRepositoryCommon { - - @Test - @Transactional - public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java similarity index 97% rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java rename to persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java index 69ddbb9b9f..13b5b4357d 100644 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java @@ -1,25 +1,6 @@ -package com.baeldung.spring.data.persistence.jpaquery; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Stream; - -import javax.persistence.EntityManager; -import javax.persistence.Query; +package com.baeldung.spring.data.persistence.repository; import com.baeldung.spring.data.persistence.config.PersistenceConfig; -import com.baeldung.spring.data.persistence.jpaquery.UserRepository; import com.baeldung.spring.data.persistence.model.User; import org.junit.After; import org.junit.Test; @@ -36,6 +17,16 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.transaction.annotation.Transactional; +import javax.persistence.EntityManager; +import javax.persistence.Query; +import java.time.LocalDate; +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.*; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) @@ -283,7 +274,7 @@ public class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); assertThat(usersSortByName.get(0) .getName()).isEqualTo(USER_NAME_ADAM); @@ -295,7 +286,7 @@ public class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); @@ -459,6 +450,8 @@ public class UserRepositoryCommon { userRepository.save(usr01); userRepository.save(usr02); + System.out.println(TimeZone.getDefault()); + List users = userRepository.findUsersWithGmailAddress(); assertEquals(1, users.size()); assertEquals(usr02, users.get(0)); diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..c76e345fdd --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.spring.data.persistence.repository; + +import com.baeldung.spring.data.persistence.config.PersistenceConfig; +import com.baeldung.spring.data.persistence.model.User; +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; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext +public class UserRepositoryIntegrationTest extends UserRepositoryCommon { + + @Test + @Transactional + public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); + userRepository.flush(); + + int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } +} diff --git a/play-framework/async-http/.g8/form/app/controllers/$model__Camel$Controller.java b/play-framework/async-http/.g8/form/app/controllers/$model__Camel$Controller.java new file mode 100644 index 0000000000..1ac4fe547d --- /dev/null +++ b/play-framework/async-http/.g8/form/app/controllers/$model__Camel$Controller.java @@ -0,0 +1,43 @@ +package controllers; + +import play.data.Form; +import play.data.FormFactory; +import play.mvc.Controller; +import play.mvc.Result; + +import javax.inject.Inject; + +// Add the following to conf/routes +/* +GET /$model;format="camel"$ controllers.$model;format="Camel"$Controller.$model;format="camel"$Get +POST /$model;format="camel"$ controllers.$model;format="Camel"$Controller.$model;format="camel"$Post +*/ + +/** + * $model;format="Camel"$ form controller for Play Java + */ +public class $model;format="Camel"$Controller extends Controller { + + private final Form<$model;format="Camel"$Data> $model;format="camel"$Form; + + @Inject + public $model;format="Camel"$Controller(FormFactory formFactory) { + this.$model;format="camel"$Form = formFactory.form($model;format="Camel"$Data.class); + } + + public Result $model;format="camel"$Get() { + return ok(views.html.$model;format="camel"$.form.render($model;format="camel"$Form)); + } + + public Result $model;format="camel"$Post() { + Form<$model;format="Camel"$Data> boundForm = $model;format="camel"$Form.bindFromRequest(); + if (boundForm.hasErrors()) { + return badRequest(views.html.$model;format="camel"$.form.render(boundForm)); + } else { + $model;format="Camel"$Data $model;format="camel"$ = boundForm.get(); + flash("success", "$model;format="Camel"$ " + $model;format="camel"$); + return redirect(routes.$model;format="Camel"$Controller.$model;format="camel"$Get()); + } + } + +} diff --git a/play-framework/async-http/.g8/form/app/controllers/$model__Camel$Data.java b/play-framework/async-http/.g8/form/app/controllers/$model__Camel$Data.java new file mode 100644 index 0000000000..50dc06f478 --- /dev/null +++ b/play-framework/async-http/.g8/form/app/controllers/$model__Camel$Data.java @@ -0,0 +1,37 @@ +package controllers; + +import play.data.validation.Constraints; + +public class $model;format="Camel"$Data { + + @Constraints.Required + private String name; + + @Constraints.Required + private Integer age; + + public $model;format="Camel"$Data() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + @Override + public String toString() { + return String.format("$model;format="Camel"$Data(%s, %s)", name, age); + } + +} diff --git a/play-framework/async-http/.g8/form/app/views/$model__camel$/form.scala.html b/play-framework/async-http/.g8/form/app/views/$model__camel$/form.scala.html new file mode 100644 index 0000000000..7bf9fd5427 --- /dev/null +++ b/play-framework/async-http/.g8/form/app/views/$model__camel$/form.scala.html @@ -0,0 +1,12 @@ +@($model;format="camel"$Form: Form[$model;format="Camel"$Data]) + +

$model;format="camel"$ form

+ +@flash.getOrDefault("success", "") + +@helper.form(action = routes.$model;format="Camel"$Controller.$model;format="camel"$Post()) { + @helper.CSRF.formField + @helper.inputText($model;format="camel"$Form("name")) + @helper.inputText($model;format="camel"$Form("age")) + +} diff --git a/play-framework/async-http/.g8/form/default.properties b/play-framework/async-http/.g8/form/default.properties new file mode 100644 index 0000000000..32090f30cb --- /dev/null +++ b/play-framework/async-http/.g8/form/default.properties @@ -0,0 +1,2 @@ +description = Generates a Controller with form handling +model = user diff --git a/play-framework/async-http/.g8/form/generated-test/README.md b/play-framework/async-http/.g8/form/generated-test/README.md new file mode 100644 index 0000000000..db01c87f30 --- /dev/null +++ b/play-framework/async-http/.g8/form/generated-test/README.md @@ -0,0 +1 @@ +Temporary file until g8-scaffold will generate "test" directory diff --git a/play-framework/async-http/.g8/form/generated-test/controllers/$model__Camel$ControllerTest.java b/play-framework/async-http/.g8/form/generated-test/controllers/$model__Camel$ControllerTest.java new file mode 100644 index 0000000000..7cdb87068b --- /dev/null +++ b/play-framework/async-http/.g8/form/generated-test/controllers/$model__Camel$ControllerTest.java @@ -0,0 +1,50 @@ +package controllers; + +import org.junit.Test; +import play.Application; +import play.filters.csrf.*; +import play.inject.guice.GuiceApplicationBuilder; +import play.mvc.*; +import play.test.WithApplication; + +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; +import static play.mvc.Http.RequestBuilder; +import static play.mvc.Http.Status.OK; +import static play.test.Helpers.*; +import static play.api.test.CSRFTokenHelper.*; + +public class $model;format="Camel"$ControllerTest extends WithApplication { + + @Override + protected Application provideApplication() { + return new GuiceApplicationBuilder().build(); + } + + @Test + public void test$model;format="Camel"$Get() { + RequestBuilder request = new RequestBuilder() + .method(GET) + .uri("/$model;format="camel"$"); + + Result result = route(app, request); + assertEquals(OK, result.status()); + } + + @Test + public void test$model;format="Camel"$Post() { + HashMap formData = new HashMap<>(); + formData.put("name", "play"); + formData.put("age", "4"); + RequestBuilder request = addCSRFToken(new RequestBuilder() + .header(Http.HeaderNames.HOST, "localhost") + .method(POST) + .bodyForm(formData) + .uri("/$model;format="camel"$")); + + Result result = route(app, request); + assertEquals(SEE_OTHER, result.status()); + } + +} diff --git a/play-framework/async-http/.gitignore b/play-framework/async-http/.gitignore new file mode 100644 index 0000000000..eb372fc719 --- /dev/null +++ b/play-framework/async-http/.gitignore @@ -0,0 +1,8 @@ +logs +target +/.idea +/.idea_modules +/.classpath +/.project +/.settings +/RUNNING_PID diff --git a/play-framework/async-http/README.md b/play-framework/async-http/README.md new file mode 100644 index 0000000000..c42b86ad4e --- /dev/null +++ b/play-framework/async-http/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Asynchronous HTTP Programming with Play Framework](https://www.baeldung.com/java-play-asynchronous-http-programming) diff --git a/play-framework/async-http/app/controllers/HomeController.java b/play-framework/async-http/app/controllers/HomeController.java new file mode 100644 index 0000000000..5c791dcd22 --- /dev/null +++ b/play-framework/async-http/app/controllers/HomeController.java @@ -0,0 +1,38 @@ +package controllers; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import java.util.Collections; +import java.util.Map; +import play.mvc.Controller; +import play.mvc.Http; +import play.mvc.Result; + +/** + * This controller contains an action to handle HTTP requests to the application's home page. + */ +public class HomeController extends Controller { + + /** + * An action that renders an HTML page with a welcome message. The configuration in the + * routes file means that this method will be called when the application receives + * a + * GET request with a path of /. + */ + public Result index(Http.Request request) throws JsonProcessingException { + return ok(printStats(request)); + } + + private String printStats(Http.Request request) throws JsonProcessingException { + Map stringMap = request.body() + .asFormUrlEncoded(); + Map map = ImmutableMap.of( + "Result", "ok", + "GetParams", request.queryString(), + "PostParams", stringMap == null ? Collections.emptyMap() : stringMap, + "Headers", request.getHeaders().toMap() + ); + return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(map); + } +} diff --git a/play-framework/async-http/app/views/index.scala.html b/play-framework/async-http/app/views/index.scala.html new file mode 100644 index 0000000000..68d37fb1d4 --- /dev/null +++ b/play-framework/async-http/app/views/index.scala.html @@ -0,0 +1,5 @@ +@() + +@main("Welcome to Play") { +

Welcome to Play!

+} diff --git a/play-framework/async-http/app/views/main.scala.html b/play-framework/async-http/app/views/main.scala.html new file mode 100644 index 0000000000..c5f755f236 --- /dev/null +++ b/play-framework/async-http/app/views/main.scala.html @@ -0,0 +1,24 @@ +@* + * 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/play-framework/async-http/build.sbt b/play-framework/async-http/build.sbt new file mode 100644 index 0000000000..eea47ffe88 --- /dev/null +++ b/play-framework/async-http/build.sbt @@ -0,0 +1,12 @@ +name := """async""" +organization := "com.example" + +version := "1.0-SNAPSHOT" + +lazy val root = (project in file(".")).enablePlugins(PlayJava) + +scalaVersion := "2.13.1" + +// comment out the original line +libraryDependencies += guice +libraryDependencies += javaWs diff --git a/play-framework/async-http/conf/application.conf b/play-framework/async-http/conf/application.conf new file mode 100644 index 0000000000..492f37fed7 --- /dev/null +++ b/play-framework/async-http/conf/application.conf @@ -0,0 +1,11 @@ +# This is the main configuration file for the application. +# https://www.playframework.com/documentation/latest/ConfigFile +play.ws.followRedirects=false +play.ws.useragent=MyPlayApplication +play.ws.compressionEnabled=true +# time to wait for the connection to be established +play.ws.timeout.connection=30.seconds +# time to wait for data after the connection is open +play.ws.timeout.idle=30.seconds +# max time available to complete the request +play.ws.timeout.request=300.seconds diff --git a/play-framework/async-http/conf/logback.xml b/play-framework/async-http/conf/logback.xml new file mode 100644 index 0000000000..55441d39e2 --- /dev/null +++ b/play-framework/async-http/conf/logback.xml @@ -0,0 +1,36 @@ + + + + + + + ${application.home:-.}/logs/application.log + + %date [%level] from %logger in %thread - %message%n%xException + + + + + + %coloredLevel %logger{15} - %message%n%xException{10} + + + + + + + + + + + + + + + + + + + + + diff --git a/play-framework/async-http/conf/routes b/play-framework/async-http/conf/routes new file mode 100644 index 0000000000..4f5162a8e7 --- /dev/null +++ b/play-framework/async-http/conf/routes @@ -0,0 +1,10 @@ +# Routes +# This file defines all application routes (Higher priority routes first) +# ~~~~ + +# An example controller showing a sample home page +GET / controllers.HomeController.index(request: Request) +POST / controllers.HomeController.index(request: Request) + +# Map static resources from the /public folder to the /assets URL path +GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) diff --git a/play-framework/async-http/project/build.properties b/play-framework/async-http/project/build.properties new file mode 100644 index 0000000000..6adcdc753f --- /dev/null +++ b/play-framework/async-http/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.3.3 diff --git a/play-framework/async-http/project/plugins.sbt b/play-framework/async-http/project/plugins.sbt new file mode 100644 index 0000000000..1c8c62a0d5 --- /dev/null +++ b/play-framework/async-http/project/plugins.sbt @@ -0,0 +1,7 @@ +// The Play plugin +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.7.3") + +// Defines scaffolding (found under .g8 folder) +// http://www.foundweekends.org/giter8/scaffolding.html +// sbt "g8Scaffold form" +addSbtPlugin("org.foundweekends.giter8" % "sbt-giter8-scaffold" % "0.11.0") diff --git a/play-framework/async-http/public/images/favicon.png b/play-framework/async-http/public/images/favicon.png new file mode 100644 index 0000000000..c7d92d2ae4 Binary files /dev/null and b/play-framework/async-http/public/images/favicon.png differ diff --git a/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.css b/play-framework/async-http/public/javascripts/main.js similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.css rename to play-framework/async-http/public/javascripts/main.js diff --git a/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.css b/play-framework/async-http/public/stylesheets/main.css similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.css rename to play-framework/async-http/public/stylesheets/main.css diff --git a/play-framework/async-http/test/controllers/HomeControllerTest.java b/play-framework/async-http/test/controllers/HomeControllerTest.java new file mode 100644 index 0000000000..a232dbfde0 --- /dev/null +++ b/play-framework/async-http/test/controllers/HomeControllerTest.java @@ -0,0 +1,232 @@ +package controllers; + +import static java.time.temporal.ChronoUnit.SECONDS; +import static org.junit.Assert.assertEquals; +import static play.mvc.Http.Status.SERVICE_UNAVAILABLE; + +import akka.Done; +import akka.actor.ActorSystem; +import akka.stream.ActorMaterializer; +import akka.stream.javadsl.Sink; +import akka.util.ByteString; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.OptionalInt; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import play.Application; +import play.inject.guice.GuiceApplicationBuilder; +import play.libs.concurrent.Futures; +import play.libs.ws.WSClient; +import play.libs.ws.WSResponse; +import play.libs.ws.ahc.AhcCurlRequestLogger; +import play.mvc.Result; +import play.mvc.Results; +import play.test.WithServer; + +public class HomeControllerTest extends WithServer { + + private final Logger log = LoggerFactory.getLogger(HomeControllerTest.class); + private String url; + private int port; + + @Override + protected Application provideApplication() { + return new GuiceApplicationBuilder().build(); + } + + @Before + public void setup() { + OptionalInt optHttpsPort = testServer.getRunningHttpsPort(); + if (optHttpsPort.isPresent()) { + port = optHttpsPort.getAsInt(); + url = "https://localhost:" + port; + } else { + port = testServer.getRunningHttpPort() + .getAsInt(); + url = "http://localhost:" + port; + } + } + + @Test + public void givenASingleGetRequestWhenResponseThenBlockWithCompletableAndLog() + throws Exception { + WSClient ws = play.test.WSTestClient.newClient(port); + WSResponse wsResponse = ws.url(url) + .setRequestFilter(new AhcCurlRequestLogger()) + .addHeader("key", "value") + .addQueryParameter("num", "" + 1) + .get() + .toCompletableFuture() + .get(); + + log.debug("Thread#" + Thread.currentThread() + .getId() + " Request complete: Response code = " + + wsResponse.getStatus() + + " | Response: " + wsResponse.getBody() + " | Current Time:" + + System.currentTimeMillis()); + assert (HttpStatus.SC_OK == wsResponse.getStatus()); + } + + @Test + public void givenASingleGetRequestWhenResponseThenLog() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + WSClient ws = play.test.WSTestClient.newClient(port); + ws.url(url) + .setRequestFilter(new AhcCurlRequestLogger()) + .addHeader("key", "value") + .addQueryParameter("num", "" + 1) + .get() + .thenAccept(r -> { + log.debug("Thread#" + Thread.currentThread() + .getId() + " Request complete: Response code = " + + r.getStatus() + + " | Response: " + r.getBody() + " | Current Time:" + System.currentTimeMillis()); + latch.countDown(); + }); + + log.debug( + "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis()); + latch.await(5, TimeUnit.SECONDS ); + assertEquals(0, latch.getCount()); + log.debug("All requests have been completed. Exiting test."); + } + + @Test + public void givenASinglePostRequestWhenResponseThenLog() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + WSClient ws = play.test.WSTestClient.newClient(port); + ws.url(url) + .setContentType("application/x-www-form-urlencoded") + .post("key1=value1&key2=value2") + .thenAccept(r -> { + log.debug("Thread#" + Thread.currentThread() + .getId() + " Request complete: Response code = " + + r.getStatus() + + " | Response: " + r.getBody() + " | Current Time:" + System.currentTimeMillis()); + latch.countDown(); + }); + + log.debug( + "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis()); + latch.await(5, TimeUnit.SECONDS ); + assertEquals(0, latch.getCount()); + log.debug("All requests have been completed. Exiting test."); + } + + @Test + public void givenMultipleRequestsWhenResponseThenLog() throws Exception { + CountDownLatch latch = new CountDownLatch(100); + WSClient ws = play.test.WSTestClient.newClient(port); + IntStream.range(0, 100) + .parallel() + .forEach(num -> + ws.url(url) + .setRequestFilter(new AhcCurlRequestLogger()) + .addHeader("key", "value") + .addQueryParameter("num", "" + num) + .get() + .thenAccept(r -> { + log.debug( + "Thread#" + num + " Request complete: Response code = " + r.getStatus() + + " | Response: " + r.getBody() + " | Current Time:" + + System.currentTimeMillis()); + latch.countDown(); + }) + ); + + log.debug( + "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis()); + latch.await(5, TimeUnit.SECONDS ); + assertEquals(0, latch.getCount()); + log.debug("All requests have been completed. Exiting test."); + } + + @Test + public void givenLongResponseWhenTimeoutThenHandle() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + WSClient ws = play.test.WSTestClient.newClient(port); + Futures futures = app.injector() + .instanceOf(Futures.class); + CompletionStage f = futures.timeout( + ws.url(url) + .setRequestTimeout(Duration.of(1, SECONDS)) + .get() + .thenApply(result -> { + try { + Thread.sleep(2000L); + return Results.ok(); + } catch (InterruptedException e) { + return Results.status( + SERVICE_UNAVAILABLE); + } + }), 1L, TimeUnit.SECONDS + ); + CompletionStage res = f.handleAsync((result, e) -> { + if (e != null) { + log.error("Exception thrown", e); + latch.countDown(); + return e.getCause(); + } else { + return result; + } + }); + res.thenAccept(result -> assertEquals(TimeoutException.class, result)); + + log.debug( + "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis()); + latch.await(5, TimeUnit.SECONDS ); + assertEquals(0, latch.getCount()); + log.debug("All requests have been completed. Exiting test."); + } + + @Test + public void givenMultigigabyteResponseConsumeWithStreams() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + final ActorSystem system = ActorSystem.create(); + final ActorMaterializer materializer = ActorMaterializer.create(system); + final Path path = Files.createTempFile("tmp_", ".out"); + + WSClient ws = play.test.WSTestClient.newClient(port); + log.info("Starting test server on url: " + url); + ws.url(url) + .stream() + .thenAccept( + response -> { + try { + OutputStream outputStream = java.nio.file.Files.newOutputStream(path); + Sink> outputWriter = + Sink.foreach(bytes -> { + log.info("Reponse: " + bytes.utf8String()); + outputStream.write(bytes.toArray()); + }); + + response.getBodyAsSource() + .runWith(outputWriter, materializer); + + } catch (IOException e) { + log.error("An error happened while opening the output stream", e); + } + }) + .whenComplete((value, error) -> latch.countDown()); + + log.debug( + "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis()); + latch.await(5, TimeUnit.SECONDS ); + assertEquals(0, latch.getCount()); + log.debug("All requests have been completed. Exiting test."); + } +} diff --git a/play-framework/websockets/README.md b/play-framework/websockets/README.md new file mode 100644 index 0000000000..d056b8f059 --- /dev/null +++ b/play-framework/websockets/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [WebSockets with the Play Framework and Akka](https://www.baeldung.com/akka-play-websockets) diff --git a/podman/README.md b/podman/README.md new file mode 100644 index 0000000000..3102036f04 --- /dev/null +++ b/podman/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [An Introduction to Podman](https://www.baeldung.com/podman-intro) diff --git a/pom.xml b/pom.xml index cfb3fe1889..c6addfa6aa 100644 --- a/pom.xml +++ b/pom.xml @@ -59,20 +59,20 @@ org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} + hamcrest + ${hamcrest.version} test org.hamcrest hamcrest-all - ${org.hamcrest.version} + ${hamcrest-all.version} + test + + + net.bytebuddy + byte-buddy + ${byte-buddy.version} test @@ -332,19 +332,24 @@ parent-spring-5 parent-java parent-kotlin - + + akka-http akka-streams + algorithms-genetic algorithms-miscellaneous-1 algorithms-miscellaneous-2 algorithms-miscellaneous-3 algorithms-miscellaneous-4 algorithms-miscellaneous-5 - algorithms-sorting + algorithms-miscellaneous-6 algorithms-searching + algorithms-sorting + algorithms-sorting-2 animal-sniffer-mvn-plugin annotations antlr + apache-avro apache-bval apache-curator @@ -356,6 +361,7 @@ apache-opennlp apache-poi apache-pulsar + apache-rocketmq apache-shiro apache-solrj apache-spark @@ -364,108 +370,49 @@ apache-tika apache-velocity apache-zookeeper + asciidoctor asm + atomix + aws aws-lambda + aws-reactive + axon + azure bazel blade bootique - - cas + cdi checker-plugin - cloud-foundry-uaa/cf-uaa-oauth2-client - cloud-foundry-uaa/cf-uaa-oauth2-resource-server + + cloud-foundry-uaa code-generation + core-groovy core-groovy-2 core-groovy-collections - - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 - core-java-modules/core-java-annotations - core-java-modules/core-java-streams - core-java-modules/core-java-streams-2 - core-java-modules/core-java-streams-3 - - core-java-modules/core-java-function - core-java-modules/core-java-lang-math - - - core-java-modules/core-java-text - core-java-modules/core-java-lambdas - - - core-java-modules/core-java-arrays - core-java-modules/core-java-arrays-2 - core-java-modules/core-java-collections - core-java-modules/core-java-collections-2 - core-java-modules/core-java-collections-3 - core-java-modules/core-java-collections-list - core-java-modules/core-java-collections-list-2 - core-java-modules/core-java-collections-list-3 - core-java-modules/core-java-collections-array-list - core-java-modules/core-java-collections-set - core-java-modules/core-java-concurrency-basic - core-java-modules/core-java-concurrency-basic-2 - core-java-modules/core-java-concurrency-collections - core-java-modules/core-java-io - core-java-modules/core-java-io-2 - core-java-modules/core-java-io-apis - core-java-modules/core-java-io-conversions - core-java-modules/core-java-nio - core-java-modules/core-java-nio-2 - core-java-modules/core-java-security - core-java-modules/core-java-exceptions - core-java-modules/core-java-lang-syntax - core-java-modules/core-java-lang-syntax-2 - core-java-modules/core-java-lang - core-java-modules/core-java-lang-2 - core-java-modules/core-java-lang-oop - core-java-modules/core-java-lang-oop-2 - core-java-modules/core-java-lang-oop-3 - core-java-modules/core-java-lang-oop-4 + core-java-modules - core-java-modules/core-java-networking - core-java-modules/core-java-perf - core-java-modules/core-java-reflection - core-java-modules/core-java-sun - core-java-modules/core-java-string-conversions - core-java-modules/core-java-string-conversions-2 - core-java-modules/core-java-string-operations - core-java-modules/core-java-string-operations-2 - core-java-modules/core-java-string-algorithms - core-java-modules/core-java-string-algorithms-2 - core-java-modules/core-java-string-apis - core-java-modules/core-java-strings - core-java-modules/core-java - core-java-modules/core-java-jar - core-java-modules/core-java-jvm core-kotlin-modules - core-scala + couchbase custom-pmd dagger data-structures ddd + deeplearning4j disruptor dozer drools + dropwizard dubbo ethereum @@ -477,15 +424,16 @@ google-cloud google-web-toolkit + graphql/graphql-java grpc gson guava - guava-io guava-collections guava-collections-map guava-collections-set + guava-io guava-modules guice @@ -499,34 +447,29 @@ image-processing immutables - jackson + jackson-modules jackson-simple - jackson-annotations - jackson-exceptions - jackson-conversions - jackson-conversions-2 - jackson-custom-conversions + java-blockchain + java-collections-conversions java-collections-conversions-2 - java-collections-maps - java-collections-maps-2 - java-jdi + java-collections-maps-3 + + javafx + java-jdi java-lite - java-math - java-math-2 java-numbers java-numbers-2 + java-numbers-3 java-rmi java-spi java-vavr-stream java-websocket - javafx javax-servlets javaxval jaxb - + jee-7 jee-7-security jee-kotlin jersey @@ -541,6 +484,7 @@ jooby jsf json + json-2 json-path jsoup jta @@ -548,51 +492,54 @@ kotlin-libraries kotlin-libraries-2 + kotlin-quasar - libraries libraries-2 libraries-3 + libraries-apache-commons + libraries-apache-commons-collections + libraries-apache-commons-io libraries-data libraries-data-2 libraries-data-db libraries-data-io - libraries-apache-commons - libraries-apache-commons-collections - libraries-apache-commons-io + libraries-http + libraries-http-2 + libraries-io libraries-primitive - libraries-testing libraries-security libraries-server - libraries-http - libraries-io + libraries-testing linkrest logging-modules lombok + lombok-custom lucene + machine-learning mapstruct - - maven-all/maven - maven-all/maven-custom-plugin/counter-maven-plugin - maven-all/maven-war-plugin - maven-all/profiles - maven-all/versions-maven-plugin + + maven-all maven-archetype - - maven-polyglot/maven-polyglot-json-extension - + + maven-polyglot + mesos-marathon metrics - + micronaut microprofile msf4j - + mustache mybatis - netflix + netflix-modules + + ninja + open-liberty + oauth2-framework-impl optaplanner orika osgi @@ -600,11 +547,12 @@ patterns pdf performance-tests + persistence-modules protobuffer - persistence-modules quarkus + quarkus-extension rabbitmq @@ -612,32 +560,14 @@ reactor-core resteasy restx - - rule-engines rsocket + rule-engines rxjava-core + rxjava-libraries rxjava-observables rxjava-operators - rxjava-libraries - software-security/sql-injection-samples - tensorflow-java - spf4j - spring-boot-config-jpa-error - spring-boot-flowable - spring-boot-mvc-2 - spring-boot-performance - spring-boot-properties - - spring-security-modules/spring-security-kerberos - oauth2-framework-impl - - spring-boot-nashorn - java-blockchain - machine-learning - webrtc - wildfly - quarkus-extension + atomikos @@ -673,8 +603,6 @@ - netflix - parent-boot-1 parent-boot-2 parent-spring-4 @@ -683,12 +611,14 @@ parent-kotlin saas + software-security/sql-injection-samples + spark-java + spf4j spring-4 spring-5 - spring-5-webflux spring-5-data-reactive spring-5-mvc spring-5-reactive @@ -697,55 +627,22 @@ spring-5-reactive-oauth spring-5-reactive-security spring-5-security - spring-5-security-oauth spring-5-security-cognito + spring-5-security-oauth + spring-5-webflux spring-activiti spring-akka spring-amqp spring-aop spring-apache-camel + spring-batch spring-bom - - spring-boot - spring-boot-admin - spring-boot-angular - spring-boot-autoconfiguration - spring-boot-bootstrap - spring-boot-camel - - spring-boot-config-jpa-error - spring-boot-client - - spring-boot-crud - spring-boot-ctx-fluent - spring-boot-custom-starter - - spring-boot-jasypt - spring-boot-keycloak - spring-boot-kotlin - spring-boot-logging-log4j2 - spring-boot-mvc - spring-boot-mvc-birt - spring-boot-environment - spring-boot-deployment - spring-boot-runtime - spring-boot-runtime/disabling-console-jul - spring-boot-runtime/disabling-console-log4j2 - spring-boot-runtime/disabling-console-logback - spring-boot-artifacts + spring-boot-modules spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp - spring-boot-security - spring-boot-springdoc - spring-boot-testing - spring-boot-vue - spring-caching - spring-boot-libraries + spring-caching spring-cloud spring-cloud-bus @@ -755,13 +652,14 @@ spring-core spring-core-2 spring-core-3 + spring-core-4 spring-cucumber spring-data-rest spring-data-rest-querydsl + spring-di spring-dispatcher-servlet spring-drools - spring-di spring-ehcache spring-ejb @@ -786,59 +684,42 @@ spring-mobile spring-mockito + + spring-mvc-basics spring-mvc-basics-2 + spring-mvc-basics-3 + spring-mvc-basics-4 + spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java + spring-mvc-java-2 spring-mvc-kotlin - spring-mvc-simple - spring-mvc-simple-2 - spring-mvc-views + spring-mvc-velocity + spring-mvc-views spring-mvc-webflow spring-mvc-xml spring-protobuf - - spring-quartz spring-reactive-kotlin spring-reactor spring-remoting - spring-rest-http spring-rest-angular spring-rest-compress - spring-rest-testing spring-rest-hal-browser + spring-rest-http spring-rest-query-language spring-rest-shell spring-rest-simple spring-resttemplate + spring-rest-testing spring-roo + spring-scheduling - spring-security-modules/spring-security-acl - spring-security-modules/spring-security-angular/server - spring-security-modules/spring-security-cache-control - spring-security-modules/spring-security-core - spring-security-modules/spring-security-mvc - spring-security-modules/spring-security-mvc-boot - spring-security-modules/spring-security-mvc-custom - spring-security-modules/spring-security-mvc-digest-auth - spring-security-modules/spring-security-mvc-jsonview - spring-security-modules/spring-security-mvc-ldap - spring-security-modules/spring-security-mvc-login - spring-security-modules/spring-security-mvc-persisted-remember-me - spring-security-modules/spring-security-mvc-socket - spring-security-modules/spring-security-openid - - spring-security-modules/spring-security-rest - spring-security-modules/spring-security-rest-basic-auth - spring-security-modules/spring-security-rest-custom - spring-security-modules/spring-security-sso - spring-security-modules/spring-security-stormpath - spring-security-modules/spring-security-thymeleaf - spring-security-modules/spring-security-x509 + spring-security-modules spring-session spring-shell spring-sleuth @@ -849,18 +730,23 @@ spring-static-resources spring-swagger-codegen + spring-threads spring-thymeleaf + spring-thymeleaf-2 + spring-thymeleaf-3 spring-vault spring-vertx spring-webflux-amqp + spring-websockets static-analysis stripe structurizr struts-2 + tensorflow-java testing-modules twilio @@ -873,17 +759,11 @@ video-tutorials vraptor + webrtc wicket - + wildfly xml xstream - - tensorflow-java - spring-boot-flowable - spring-security-modules/spring-security-kerberos - - spring-boot-nashorn - java-blockchain @@ -926,26 +806,18 @@ parent-java parent-kotlin - core-java-modules/core-java-concurrency-advanced - core-java-modules/core-java-concurrency-advanced-2 - core-java-modules/core-java-concurrency-advanced-3 - core-kotlin - core-kotlin-2 - jenkins/plugins jhipster jws libraries - persistence-modules/hibernate5 - persistence-modules/hibernate-mapping - persistence-modules/java-jpa - persistence-modules/java-jpa-2 - persistence-modules/java-mongodb - persistence-modules/jnosql + libraries-4 + libraries-5 + libraries-6 vaadin vavr + vavr-2 @@ -978,20 +850,26 @@ parent-spring-5 parent-java parent-kotlin - + + akka-http akka-streams + algorithms-genetic algorithms-miscellaneous-1 algorithms-miscellaneous-2 algorithms-miscellaneous-3 algorithms-miscellaneous-4 algorithms-miscellaneous-5 - algorithms-sorting + algorithms-miscellaneous-6 algorithms-searching + algorithms-sorting + algorithms-sorting-2 animal-sniffer-mvn-plugin annotations antlr + apache-avro + apache-beam apache-bval apache-curator apache-cxf @@ -1002,6 +880,7 @@ apache-opennlp apache-poi apache-pulsar + apache-rocketmq apache-shiro apache-solrj apache-spark @@ -1010,100 +889,49 @@ apache-tika apache-velocity apache-zookeeper + asciidoctor asm + atomix + aws aws-lambda - axon - azure - bazel - bootique + aws-reactive - cas + axon + + azure + + bazel + blade + bootique + cdi checker-plugin - cloud-foundry-uaa/cf-uaa-oauth2-client - cloud-foundry-uaa/cf-uaa-oauth2-resource-server + + cloud-foundry-uaa code-generation + core-groovy core-groovy-2 core-groovy-collections - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 - core-java-modules/core-java-annotations - core-java-modules/core-java-streams - core-java-modules/core-java-streams-2 - core-java-modules/core-java-streams-3 - - core-java-modules/core-java-function - core-java-modules/core-java-lang-math - - - core-java-modules/core-java-text - - - core-java-modules/core-java-arrays - core-java-modules/core-java-arrays-2 - core-java-modules/core-java-collections - core-java-modules/core-java-collections-2 - core-java-modules/core-java-collections-3 - core-java-modules/core-java-collections-list - core-java-modules/core-java-collections-list-2 - core-java-modules/core-java-collections-list-3 - core-java-modules/core-java-collections-array-list - core-java-modules/core-java-collections-set - core-java-modules/core-java-concurrency-basic - core-java-modules/core-java-concurrency-basic-2 - core-java-modules/core-java-concurrency-collections - core-java-modules/core-java-io - core-java-modules/core-java-io-2 - core-java-modules/core-java-io-apis - core-java-modules/core-java-io-conversions - core-java-modules/core-java-nio - core-java-modules/core-java-nio-2 - core-java-modules/core-java-security - core-java-modules/core-java-exceptions - core-java-modules/core-java-lang-syntax - core-java-modules/core-java-lang-syntax-2 - core-java-modules/core-java-lang - core-java-modules/core-java-lang-2 - core-java-modules/core-java-lang-oop - core-java-modules/core-java-lang-oop-2 - core-java-modules/core-java-lang-oop-3 - core-java-modules/core-java-lang-oop-4 + core-java-modules - core-java-modules/core-java-networking - core-java-modules/core-java-perf - core-java-modules/core-java-sun - core-java-modules/core-java-string-conversions - core-java-modules/core-java-string-conversions-2 - core-java-modules/core-java-string-operations - core-java-modules/core-java-string-operations-2 - core-java-modules/core-java-string-algorithms - core-java-modules/core-java-string-algorithms-2 - core-java-modules/core-java-string-apis - core-java-modules/core-java-strings core-kotlin-modules - core-scala + couchbase custom-pmd dagger data-structures ddd + deeplearning4j disruptor dozer drools + dropwizard dubbo ethereum @@ -1115,15 +943,16 @@ google-cloud google-web-toolkit + graphql/graphql-java grpc gson guava - guava-io guava-collections guava-collections-map guava-collections-set + guava-io guava-modules guice @@ -1137,34 +966,29 @@ image-processing immutables - jackson + jackson-modules jackson-simple - jackson-annotations - jackson-exceptions - jackson-conversions - jackson-conversions-2 - jackson-custom-conversions + java-blockchain + java-collections-conversions java-collections-conversions-2 - java-collections-maps - java-collections-maps-2 + java-collections-maps-3 + + + javafx java-jdi - java-ee-8-security-api java-lite - java-math - java-math-2 java-numbers java-numbers-2 + java-numbers-3 java-rmi java-spi java-vavr-stream java-websocket - javafx javax-servlets javaxval jaxb - + jee-7 jee-7-security jee-kotlin jersey @@ -1185,49 +1009,56 @@ kotlin-libraries + kotlin-libraries-2 + kotlin-quasar - libraries + libraries-2 libraries-3 + + libraries-apache-commons + libraries-apache-commons-collections + libraries-apache-commons-io libraries-data libraries-data-2 libraries-data-db libraries-data-io - libraries-apache-commons - libraries-apache-commons-collections - libraries-apache-commons-io - libraries-testing + libraries-http + libraries-http-2 + libraries-io + libraries-primitive libraries-security libraries-server - libraries-http + libraries-testing linkrest logging-modules lombok + lombok-custom lucene + machine-learning mapstruct - - maven-all/maven - maven-all/maven-custom-plugin/counter-maven-plugin - maven-all/maven-war-plugin - maven-all/profiles - maven-all/versions-maven-plugin - + + maven-all maven-archetype - - maven-polyglot/maven-polyglot-json-extension - + + maven-polyglot + mesos-marathon metrics - + micronaut microprofile msf4j - + mustache mybatis - netflix + netflix-modules + + ninja + open-liberty + oauth2-framework-impl optaplanner orika osgi @@ -1235,10 +1066,12 @@ patterns pdf performance-tests + persistence-modules protobuffer - persistence-modules + quarkus + quarkus-extension rabbitmq @@ -1246,20 +1079,14 @@ reactor-core resteasy restx - - rule-engines rsocket + rule-engines rxjava-core + rxjava-libraries rxjava-observables rxjava-operators - rxjava-libraries - oauth2-framework-impl - spf4j - spring-boot-performance - spring-boot-properties - - + atomikos @@ -1295,7 +1122,10 @@ parent-kotlin saas + software-security/sql-injection-samples + spark-java + spf4j spring-4 @@ -1308,48 +1138,23 @@ spring-5-reactive-oauth spring-5-reactive-security spring-5-security - spring-5-security-oauth spring-5-security-cognito + spring-5-security-oauth + spring-5-webflux + spring-activiti spring-akka spring-amqp spring-aop spring-apache-camel + spring-batch spring-bom - - spring-boot - spring-boot-admin - spring-boot-angular - spring-boot-autoconfiguration - spring-boot-bootstrap - spring-boot-camel - - spring-boot-client - spring-boot-crud - spring-boot-ctx-fluent - spring-boot-custom-starter - - spring-boot-jasypt - spring-boot-keycloak - spring-boot-logging-log4j2 - spring-boot-mvc - spring-boot-mvc-birt - spring-boot-environment - spring-boot-deployment - spring-boot-runtime - spring-boot-runtime/disabling-console-jul - spring-boot-runtime/disabling-console-log4j2 - spring-boot-runtime/disabling-console-logback - spring-boot-artifacts + spring-boot-modules spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp - spring-boot-security - spring-boot-springdoc - spring-boot-vue + spring-caching + spring-cloud spring-cloud-bus @@ -1358,13 +1163,14 @@ spring-core spring-core-2 spring-core-3 + spring-core-4 spring-cucumber spring-data-rest spring-data-rest-querydsl + spring-di spring-dispatcher-servlet spring-drools - spring-di spring-ehcache spring-ejb @@ -1389,59 +1195,43 @@ spring-mobile spring-mockito + + spring-mvc-basics spring-mvc-basics-2 + spring-mvc-basics-3 + spring-mvc-basics-4 + spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java + spring-mvc-java-2 spring-mvc-kotlin - spring-mvc-simple - spring-mvc-simple-2 - spring-mvc-views + spring-mvc-velocity + spring-mvc-views spring-mvc-webflow spring-mvc-xml + spring-mvc-crash spring-protobuf - - spring-quartz spring-reactive-kotlin spring-reactor spring-remoting - spring-rest-http spring-rest-angular spring-rest-compress - spring-rest-testing spring-rest-hal-browser + spring-rest-http spring-rest-query-language spring-rest-shell spring-rest-simple spring-resttemplate + spring-rest-testing spring-roo spring-scheduling - spring-security-modules/spring-security-acl - spring-security-modules/spring-security-angular/server - spring-security-modules/spring-security-cache-control - spring-security-modules/spring-security-core - spring-security-modules/spring-security-mvc - spring-security-modules/spring-security-mvc-boot - spring-security-modules/spring-security-mvc-custom - spring-security-modules/spring-security-mvc-digest-auth - spring-security-modules/spring-security-mvc-ldap - spring-security-modules/spring-security-mvc-login - spring-security-modules/spring-security-mvc-persisted-remember-me - spring-security-modules/spring-security-mvc-socket - spring-security-modules/spring-security-openid - - spring-security-modules/spring-security-rest - spring-security-modules/spring-security-rest-basic-auth - spring-security-modules/spring-security-rest-custom - spring-security-modules/spring-security-sso - spring-security-modules/spring-security-stormpath - spring-security-modules/spring-security-thymeleaf - spring-security-modules/spring-security-x509 + spring-security-modules spring-session spring-shell spring-sleuth @@ -1453,17 +1243,21 @@ spring-swagger-codegen spring-thymeleaf + spring-thymeleaf-2 + spring-thymeleaf-3 spring-vault spring-vertx spring-webflux-amqp + spring-websockets static-analysis stripe structurizr struts-2 + tensorflow-java testing-modules twilio @@ -1476,10 +1270,12 @@ video-tutorials vraptor + webrtc wicket - + wildfly xml xstream + libraries-concurrency @@ -1514,33 +1310,52 @@ parent-java parent-kotlin - core-java-modules/core-java - core-java-modules/core-java-jar - core-java-modules/core-java-concurrency-advanced - core-java-modules/core-java-concurrency-advanced-2 - core-java-modules/core-java-concurrency-advanced-3 - core-kotlin - core-kotlin-2 - jenkins/plugins jhipster jws libraries - - persistence-modules/hibernate5 - persistence-modules/hibernate-mapping - persistence-modules/java-jpa - persistence-modules/java-jpa-2 - persistence-modules/java-mongodb - persistence-modules/jnosql + libraries-4 + libraries-5 + libraries-6 vaadin vavr + vavr-2 + + live-all + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/SpringContextTest.java + **/*UnitTest.java + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*JdbcTest.java + + + **/*LiveTest.java + + + + + + + + + + @@ -1564,17 +1379,19 @@ false 4.12 - 1.3 - 2.21.0 + 2.2 + 1.3 + 3.3.0 + 1.10.5 - 1.7.21 - 1.1.7 + 1.7.30 + 1.2.3 2.21.0 - 3.7.0 + 3.8.1 1.6.0 1.8 1.2.17 @@ -1582,7 +1399,6 @@ 2.1.0.1 1.19 1.19 - 1.3 1.6.0 2.21.0 2.5 @@ -1600,12 +1416,12 @@ 1.2.0 5.2.0 0.3.1 - 2.5.1 + 2.5.2 0.0.1 3.8 - 2.3 + 3.0.0 - 3.8 + 3.13.0 1.16.12 1.4.197 diff --git a/quarkus-extension/README.md b/quarkus-extension/README.md new file mode 100644 index 0000000000..782ec75957 --- /dev/null +++ b/quarkus-extension/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [How to Implement a Quarkus Extension](https://www.baeldung.com/quarkus-extension-java) diff --git a/quarkus-extension/pom.xml b/quarkus-extension/pom.xml index 38d7c3d548..394376e59e 100644 --- a/quarkus-extension/pom.xml +++ b/quarkus-extension/pom.xml @@ -9,6 +9,12 @@ quarkus-extension pom + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + quarkus-liquibase quarkus-app diff --git a/quarkus-extension/quarkus-app/pom.xml b/quarkus-extension/quarkus-app/pom.xml index 6e4cce3ae7..6d3f4c7c28 100644 --- a/quarkus-extension/quarkus-app/pom.xml +++ b/quarkus-extension/quarkus-app/pom.xml @@ -5,7 +5,12 @@ 4.0.0 com.baeldung.quarkus.app quarkus-app - 1.0-SNAPSHOT + + + com.baeldung.quarkus.extension + quarkus-extension + 1.0-SNAPSHOT + @@ -22,13 +27,12 @@ com.baeldung.quarkus.liquibase - quarkus-liquibase - 1.0-SNAPSHOT + quarkus-liquibase-runtime + ${project.version} io.quarkus quarkus-jdbc-h2 - ${quarkus.version} @@ -46,31 +50,11 @@ - - maven-compiler-plugin - ${compiler-plugin.version} - - - maven-surefire-plugin - ${surefire-plugin.version} - - - org.jboss.logmanager.LogManager - - - - UTF-8 - 2.22.0 - true 1.0.0.Final - 3.8.1 - 1.8 - UTF-8 - 1.8 diff --git a/quarkus-extension/quarkus-liquibase/deployment/pom.xml b/quarkus-extension/quarkus-liquibase/deployment/pom.xml index f005ac4e8c..5c6b56e152 100644 --- a/quarkus-extension/quarkus-liquibase/deployment/pom.xml +++ b/quarkus-extension/quarkus-liquibase/deployment/pom.xml @@ -3,8 +3,8 @@ 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 - quarkus-liquibase-deployment - quarkus-liquibase-deployment + deployment + deployment com.baeldung.quarkus.liquibase @@ -30,7 +30,7 @@ com.baeldung.quarkus.liquibase - quarkus-liquibase + quarkus-liquibase-runtime ${project.version} @@ -40,7 +40,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + ${compiler.plugin.version} @@ -54,4 +54,8 @@ - \ No newline at end of file + + 3.8.1 + + + diff --git a/quarkus-extension/quarkus-liquibase/pom.xml b/quarkus-extension/quarkus-liquibase/pom.xml index e1f3e243ab..8ed6555ed7 100644 --- a/quarkus-extension/quarkus-liquibase/pom.xml +++ b/quarkus-extension/quarkus-liquibase/pom.xml @@ -5,20 +5,22 @@ 4.0.0 com.baeldung.quarkus.liquibase quarkus-liquibase-parent - 1.0-SNAPSHOT - quarkus-liquibase-parent + quarkus-liquibase pom + + com.baeldung.quarkus.extension + quarkus-extension + 1.0-SNAPSHOT + + runtime deployment - 1.8 - 1.8 - UTF-8 1.0.0.Final - \ No newline at end of file + diff --git a/quarkus-extension/quarkus-liquibase/runtime/pom.xml b/quarkus-extension/quarkus-liquibase/runtime/pom.xml index a1d705c691..760e6ab719 100644 --- a/quarkus-extension/quarkus-liquibase/runtime/pom.xml +++ b/quarkus-extension/quarkus-liquibase/runtime/pom.xml @@ -1,10 +1,9 @@ - + 4.0.0 - quarkus-liquibase-runtime - quarkus-liquibase-runtime + runtime + runtime com.baeldung.quarkus.liquibase @@ -26,7 +25,7 @@ org.liquibase liquibase-core - 3.8.1 + ${liquibase-core.version} @@ -42,7 +41,7 @@ extension-descriptor - ${project.groupId}:${project.artifactId}-deployment:${project.version} + ${project.groupId}:quarkus-liquibase-deployment:${project.version} @@ -51,7 +50,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + ${compiler.plugin.version} @@ -65,4 +64,10 @@ - \ No newline at end of file + + 3.8.1 + 3.8.1 + 3.8.1 + + + diff --git a/quarkus/pom.xml b/quarkus/pom.xml index de4c2ca9a3..09eb90d110 100644 --- a/quarkus/pom.xml +++ b/quarkus/pom.xml @@ -118,9 +118,6 @@ 2.22.0 0.15.0 - 1.8 - UTF-8 - 1.8 diff --git a/rabbitmq/pom.xml b/rabbitmq/pom.xml index b544da4c44..33ccf5402f 100644 --- a/rabbitmq/pom.xml +++ b/rabbitmq/pom.xml @@ -5,7 +5,6 @@ rabbitmq 0.1-SNAPSHOT rabbitmq - http://maven.apache.org com.baeldung diff --git a/ratpack/pom.xml b/ratpack/pom.xml index a00be905ee..9ad654fa7d 100644 --- a/ratpack/pom.xml +++ b/ratpack/pom.xml @@ -6,7 +6,6 @@ 1.0-SNAPSHOT ratpack jar - http://maven.apache.org com.baeldung @@ -85,18 +84,7 @@ - - ${project.artifactId} - - - src/main/resources - - - - - 1.8 - 1.8 1.5.4 4.5.3 4.4.6 diff --git a/reactor-core/README.md b/reactor-core/README.md index e3cca35f86..0214aa26fd 100644 --- a/reactor-core/README.md +++ b/reactor-core/README.md @@ -7,3 +7,4 @@ This module contains articles about Reactor Core. - [Intro To Reactor Core](https://www.baeldung.com/reactor-core) - [Combining Publishers in Project Reactor](https://www.baeldung.com/reactor-combine-streams) - [Programmatically Creating Sequences with Project Reactor](https://www.baeldung.com/flux-sequences-reactor) +- [How to Extract a Mono’s Content in Java](https://www.baeldung.com/java-string-from-mono) diff --git a/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java new file mode 100644 index 0000000000..f9e67b0a2f --- /dev/null +++ b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.mono; + +import org.junit.Test; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; + +public class MonoUnitTest { + @Test + public void whenMonoProducesString_thenBlockAndConsume() { + + String result1 = blockingHelloWorld().block(); + assertEquals("Hello world!", result1); + + String result2 = blockingHelloWorld() + .block(Duration.of(1000, ChronoUnit.MILLIS)); + assertEquals("Hello world!", result2); + + Optional result3 = Mono.empty().blockOptional(); + assertEquals(Optional.empty(), result3); + } + + @Test + public void whenMonoProducesString_thenConsumeNonBlocking() { + + blockingHelloWorld() + .doOnNext(result -> assertEquals("Hello world!", result)) + .subscribe(); + + blockingHelloWorld() + .subscribe(result -> assertEquals("Hello world!", result)); + + } + + private Mono blockingHelloWorld() { + // blocking + return Mono.just("Hello world!"); + } +} diff --git a/restx/pom.xml b/restx/pom.xml index 17c25fcdc0..ee25c88047 100644 --- a/restx/pom.xml +++ b/restx/pom.xml @@ -148,8 +148,6 @@ - 1.8 - 1.8 0.35-rc4 1.2.3 diff --git a/rsocket/pom.xml b/rsocket/pom.xml index 70f21064b6..5b407c2bd0 100644 --- a/rsocket/pom.xml +++ b/rsocket/pom.xml @@ -24,43 +24,10 @@ rsocket-transport-netty ${rsocket.version} - - junit - junit - ${junit.version} - test - - - org.hamcrest - hamcrest-core - ${hamcrest.version} - test - - - ch.qos.logback - logback-classic - ${logback.version} - - - ch.qos.logback - logback-core - ${logback.version} - - - org.slf4j - slf4j-api - ${slf4j-api.version} - - 1.8 - 1.8 - 3.0.1 0.11.13 - 1.3 - 1.2.3 - 1.7.25 diff --git a/rule-engines/easy-rules/pom.xml b/rule-engines/easy-rules/pom.xml index c1ba829045..b9661cd1c3 100644 --- a/rule-engines/easy-rules/pom.xml +++ b/rule-engines/easy-rules/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-modules + rule-engines 1.0.0-SNAPSHOT - ../.. diff --git a/rule-engines/openl-tablets/pom.xml b/rule-engines/openl-tablets/pom.xml index d1c7baabcc..25c4b8365a 100644 --- a/rule-engines/openl-tablets/pom.xml +++ b/rule-engines/openl-tablets/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-modules + rule-engines 1.0.0-SNAPSHOT - ../.. diff --git a/rule-engines/pom.xml b/rule-engines/pom.xml index cc015c600b..d3d3127ce0 100644 --- a/rule-engines/pom.xml +++ b/rule-engines/pom.xml @@ -10,7 +10,6 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - .. diff --git a/rule-engines/rulebook/pom.xml b/rule-engines/rulebook/pom.xml index b021adea10..95ededa5f9 100644 --- a/rule-engines/rulebook/pom.xml +++ b/rule-engines/rulebook/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-modules + rule-engines 1.0.0-SNAPSHOT - ../.. diff --git a/slack/README.md b/slack/README.md new file mode 100644 index 0000000000..fb3eff6290 --- /dev/null +++ b/slack/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [How to Create a Slack Plugin in Java](https://www.baeldung.com/java-slack-plugin) diff --git a/slack/pom.xml b/slack/pom.xml new file mode 100644 index 0000000000..ebe5ce2f60 --- /dev/null +++ b/slack/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + com.baeldung.examples + slack + 1.0 + slack + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.hubspot.slack + slack-base + ${slack.version} + + + com.hubspot.slack + slack-java-client + ${slack.version} + + + + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven-jar-plugin.version} + + + + true + com.baeldung.examples.slack.MainClass + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.baeldung.examples.slack.MainClass + + + + + + + 1.4 + 2.4 + + + diff --git a/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java b/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java new file mode 100644 index 0000000000..7a3f5cd607 --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java @@ -0,0 +1,42 @@ +package com.baeldung.examples.slack; + +import java.io.IOException; +import java.nio.file.FileSystems; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DiskSpaceErrorChecker implements ErrorChecker { + private static final Logger LOG = LoggerFactory.getLogger(DiskSpaceErrorChecker.class); + + private final ErrorReporter errorReporter; + + private final double limit; + + public DiskSpaceErrorChecker(ErrorReporter errorReporter, double limit) { + this.errorReporter = errorReporter; + this.limit = limit; + } + + @Override + public void check() { + LOG.info("Checking disk space"); + FileSystems.getDefault().getFileStores().forEach(fileStore -> { + try { + long totalSpace = fileStore.getTotalSpace(); + long usableSpace = fileStore.getUsableSpace(); + double usablePercentage = ((double) usableSpace) / totalSpace; + LOG.debug("File store {} has {} of {} ({}) usable space", + fileStore, usableSpace, totalSpace, usablePercentage); + + if (totalSpace > 0 && usablePercentage < limit) { + String error = String.format("File store %s only has %d%% usable disk space", + fileStore.name(), (int)(usablePercentage * 100)); + errorReporter.reportProblem(error); + } + } catch (IOException e) { + LOG.error("Error getting disk space for file store {}", fileStore, e); + } + }); + } +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java b/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java new file mode 100644 index 0000000000..08db9a7817 --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.slack; + +public interface ErrorChecker { + void check(); +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java b/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java new file mode 100644 index 0000000000..ba6165af9b --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.slack; + +public interface ErrorReporter { + void reportProblem(String problem); +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/MainClass.java b/slack/src/main/java/com/baeldung/examples/slack/MainClass.java new file mode 100644 index 0000000000..ac25e97cf6 --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/MainClass.java @@ -0,0 +1,41 @@ +package com.baeldung.examples.slack; + +import java.io.IOException; +import java.util.Timer; +import java.util.TimerTask; + +import com.hubspot.slack.client.SlackClient; +import com.hubspot.slack.client.SlackClientFactory; +import com.hubspot.slack.client.SlackClientRuntimeConfig; + +public class MainClass { + public static final long MINUTES = 1000 * 60; + + public static void main(String[] args) throws IOException { + SlackClientRuntimeConfig runtimeConfig = SlackClientRuntimeConfig.builder() + .setTokenSupplier(() -> "") + .build(); + + SlackClient slackClient = SlackClientFactory.defaultFactory().build(runtimeConfig); + + ErrorReporter slackChannelErrorReporter = new SlackChannelErrorReporter(slackClient, "general"); + ErrorReporter slackUserErrorReporter = new SlackUserErrorReporter(slackClient, "testuser@baeldung.com"); + + ErrorChecker diskSpaceErrorChecker10pct = new DiskSpaceErrorChecker(slackChannelErrorReporter, 0.1); + ErrorChecker diskSpaceErrorChecker2pct = new DiskSpaceErrorChecker(slackUserErrorReporter, 0.02); + + Timer timer = new Timer(); + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + diskSpaceErrorChecker10pct.check(); + } + }, 0, 5 * MINUTES); + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + diskSpaceErrorChecker2pct.check(); + } + }, 0, 5 * MINUTES); + } +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java b/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java new file mode 100644 index 0000000000..f7abcecc2e --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java @@ -0,0 +1,30 @@ +package com.baeldung.examples.slack; + +import com.hubspot.slack.client.SlackClient; +import com.hubspot.slack.client.methods.params.chat.ChatPostMessageParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SlackChannelErrorReporter implements ErrorReporter { + private static final Logger LOG = LoggerFactory.getLogger(SlackChannelErrorReporter.class); + + private final SlackClient slackClient; + + private final String channel; + + public SlackChannelErrorReporter(SlackClient slackClient, String channel) { + this.slackClient = slackClient; + this.channel = channel; + } + + @Override + public void reportProblem(String problem) { + LOG.debug("Sending message to channel {}: {}", channel, problem); + slackClient.postMessage( + ChatPostMessageParams.builder() + .setText(problem) + .setChannelId(channel) + .build() + ).join().unwrapOrElseThrow(); + } +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java b/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java new file mode 100644 index 0000000000..8fa4f9016b --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java @@ -0,0 +1,52 @@ +package com.baeldung.examples.slack; + +import java.util.List; + +import com.hubspot.slack.client.SlackClient; +import com.hubspot.slack.client.methods.params.chat.ChatPostMessageParams; +import com.hubspot.slack.client.methods.params.conversations.ConversationCreateParams; +import com.hubspot.slack.client.methods.params.im.ImOpenParams; +import com.hubspot.slack.client.methods.params.users.UserEmailParams; +import com.hubspot.slack.client.methods.params.users.UsersInfoParams; +import com.hubspot.slack.client.models.response.im.ImOpenResponse; +import com.hubspot.slack.client.models.response.users.UsersInfoResponse; +import com.hubspot.slack.client.models.users.SlackUser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SlackUserErrorReporter implements ErrorReporter { + private static final Logger LOG = LoggerFactory.getLogger(SlackUserErrorReporter.class); + + private final SlackClient slackClient; + + private final String user; + + public SlackUserErrorReporter(SlackClient slackClient, String user) { + this.slackClient = slackClient; + this.user = user; + } + + @Override + public void reportProblem(String problem) { + LOG.debug("Sending message to user {}: {}", user, problem); + UsersInfoResponse usersInfoResponse = slackClient + .lookupUserByEmail(UserEmailParams.builder() + .setEmail(user) + .build() + ).join().unwrapOrElseThrow(); + + ImOpenResponse imOpenResponse = slackClient.openIm(ImOpenParams.builder() + .setUserId(usersInfoResponse.getUser().getId()) + .build() + ).join().unwrapOrElseThrow(); + + imOpenResponse.getChannel().ifPresent(channel -> { + slackClient.postMessage( + ChatPostMessageParams.builder() + .setText(problem) + .setChannelId(channel.getId()) + .build() + ).join().unwrapOrElseThrow(); + }); + } +} diff --git a/slack/src/main/resources/logback.xml b/slack/src/main/resources/logback.xml new file mode 100644 index 0000000000..c8c077ba1d --- /dev/null +++ b/slack/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spf4j/spf4j-aspects-app/pom.xml b/spf4j/spf4j-aspects-app/pom.xml index 2458e2d8ad..db6a18f26a 100644 --- a/spf4j/spf4j-aspects-app/pom.xml +++ b/spf4j/spf4j-aspects-app/pom.xml @@ -39,16 +39,16 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 1.8 - 1.8 + ${java.version} + ${java.version} org.apache.maven.plugins maven-dependency-plugin - 3.1.1 + ${dependency.plugin.version} copy-dependencies @@ -84,6 +84,8 @@ UTF-8 8.6.10 1.7.21 + 3.8.0 + 3.1.1 diff --git a/spf4j/spf4j-core-app/pom.xml b/spf4j/spf4j-core-app/pom.xml index 45300fd4a4..48cbf4a1c9 100644 --- a/spf4j/spf4j-core-app/pom.xml +++ b/spf4j/spf4j-core-app/pom.xml @@ -39,16 +39,16 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 1.8 - 1.8 + ${java.version} + ${java.version} org.apache.maven.plugins maven-dependency-plugin - 3.1.1 + ${dependency.plugin.version} copy-dependencies @@ -84,6 +84,8 @@ UTF-8 8.6.10 1.7.21 + 3.8.0 + 3.1.1 diff --git a/spring-4/src/main/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationsTestController.java b/spring-4/src/main/java/com/baeldung/spring43/attributeannotations/AttributeAnnotationsTestController.java similarity index 85% rename from spring-4/src/main/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationsTestController.java rename to spring-4/src/main/java/com/baeldung/spring43/attributeannotations/AttributeAnnotationsTestController.java index df1d173bd2..d11ca10873 100644 --- a/spring-4/src/main/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationsTestController.java +++ b/spring-4/src/main/java/com/baeldung/spring43/attributeannotations/AttributeAnnotationsTestController.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.attributeannotations; +package com.baeldung.spring43.attributeannotations; import org.springframework.web.bind.annotation.*; diff --git a/spring-4/src/main/java/org/baeldung/spring43/attributeannotations/ParamInterceptor.java b/spring-4/src/main/java/com/baeldung/spring43/attributeannotations/ParamInterceptor.java similarity index 91% rename from spring-4/src/main/java/org/baeldung/spring43/attributeannotations/ParamInterceptor.java rename to spring-4/src/main/java/com/baeldung/spring43/attributeannotations/ParamInterceptor.java index 9cf6020a93..3d6e0ad8b9 100644 --- a/spring-4/src/main/java/org/baeldung/spring43/attributeannotations/ParamInterceptor.java +++ b/spring-4/src/main/java/com/baeldung/spring43/attributeannotations/ParamInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.attributeannotations; +package com.baeldung.spring43.attributeannotations; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; diff --git a/spring-4/src/main/java/com/baeldung/spring43/cache/Foo.java b/spring-4/src/main/java/com/baeldung/spring43/cache/Foo.java new file mode 100644 index 0000000000..731ac68e70 --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/spring43/cache/Foo.java @@ -0,0 +1,28 @@ +package com.baeldung.spring43.cache; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Foo { + + private static final Logger log = LoggerFactory.getLogger(Foo.class); + + private static final AtomicInteger instanceCount = new AtomicInteger(0); + + private final int instanceNum; + + public Foo() { + instanceNum = instanceCount.incrementAndGet(); + } + + public static int getInstanceCount() { + return instanceCount.get(); + } + + public void printInstanceNumber() { + log.info("Foo instance number: {}", instanceNum); + } + +} diff --git a/spring-4/src/main/java/com/baeldung/spring43/cache/FooService.java b/spring-4/src/main/java/com/baeldung/spring43/cache/FooService.java new file mode 100644 index 0000000000..9c0aa583c5 --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/spring43/cache/FooService.java @@ -0,0 +1,14 @@ +package com.baeldung.spring43.cache; + +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; + +@Service +public class FooService { + + @Cacheable(cacheNames = "foos", sync = true) + public Foo getFoo(String id) { + return new Foo(); + } + +} diff --git a/spring-4/src/main/java/com/baeldung/spring43/composedmapping/Appointment.java b/spring-4/src/main/java/com/baeldung/spring43/composedmapping/Appointment.java new file mode 100644 index 0000000000..4d8ba86f4b --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/spring43/composedmapping/Appointment.java @@ -0,0 +1,5 @@ +package com.baeldung.spring43.composedmapping; + +public class Appointment { + +} diff --git a/spring-4/src/main/java/com/baeldung/spring43/composedmapping/AppointmentService.java b/spring-4/src/main/java/com/baeldung/spring43/composedmapping/AppointmentService.java new file mode 100644 index 0000000000..1ca389e16b --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/spring43/composedmapping/AppointmentService.java @@ -0,0 +1,9 @@ +package com.baeldung.spring43.composedmapping; + +import java.util.Map; + +public interface AppointmentService { + + Map getAppointmentsForToday(); + +} diff --git a/spring-4/src/main/java/org/baeldung/spring43/composedmapping/AppointmentsController.java b/spring-4/src/main/java/com/baeldung/spring43/composedmapping/AppointmentsController.java similarity index 94% rename from spring-4/src/main/java/org/baeldung/spring43/composedmapping/AppointmentsController.java rename to spring-4/src/main/java/com/baeldung/spring43/composedmapping/AppointmentsController.java index e83a33eb89..3ff3a237ac 100644 --- a/spring-4/src/main/java/org/baeldung/spring43/composedmapping/AppointmentsController.java +++ b/spring-4/src/main/java/com/baeldung/spring43/composedmapping/AppointmentsController.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.composedmapping; +package com.baeldung.spring43.composedmapping; import java.util.Map; diff --git a/spring-4/src/main/java/com/baeldung/spring43/ctor/FooRepository.java b/spring-4/src/main/java/com/baeldung/spring43/ctor/FooRepository.java new file mode 100644 index 0000000000..f1d8425682 --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/spring43/ctor/FooRepository.java @@ -0,0 +1,5 @@ +package com.baeldung.spring43.ctor; + +public class FooRepository { + +} diff --git a/spring-4/src/main/java/com/baeldung/spring43/ctor/FooService.java b/spring-4/src/main/java/com/baeldung/spring43/ctor/FooService.java new file mode 100644 index 0000000000..cb481f99b2 --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/spring43/ctor/FooService.java @@ -0,0 +1,15 @@ +package com.baeldung.spring43.ctor; + +public class FooService { + + private final FooRepository repository; + + public FooService(FooRepository repository) { + this.repository = repository; + } + + public FooRepository getRepository() { + return repository; + } + +} \ No newline at end of file diff --git a/spring-4/src/main/java/org/baeldung/spring43/defaultmethods/DateHolder.java b/spring-4/src/main/java/com/baeldung/spring43/defaultmethods/DateHolder.java similarity index 87% rename from spring-4/src/main/java/org/baeldung/spring43/defaultmethods/DateHolder.java rename to spring-4/src/main/java/com/baeldung/spring43/defaultmethods/DateHolder.java index 9ae62cf484..a5307ec37c 100644 --- a/spring-4/src/main/java/org/baeldung/spring43/defaultmethods/DateHolder.java +++ b/spring-4/src/main/java/com/baeldung/spring43/defaultmethods/DateHolder.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.defaultmethods; +package com.baeldung.spring43.defaultmethods; import java.time.LocalDate; diff --git a/spring-4/src/main/java/org/baeldung/spring43/defaultmethods/IDateHolder.java b/spring-4/src/main/java/com/baeldung/spring43/defaultmethods/IDateHolder.java similarity index 87% rename from spring-4/src/main/java/org/baeldung/spring43/defaultmethods/IDateHolder.java rename to spring-4/src/main/java/com/baeldung/spring43/defaultmethods/IDateHolder.java index e37d27f9fc..66eca031c0 100644 --- a/spring-4/src/main/java/org/baeldung/spring43/defaultmethods/IDateHolder.java +++ b/spring-4/src/main/java/com/baeldung/spring43/defaultmethods/IDateHolder.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.defaultmethods; +package com.baeldung.spring43.defaultmethods; import java.time.LocalDate; import java.time.format.DateTimeFormatter; diff --git a/spring-4/src/main/java/com/baeldung/spring43/depresolution/FooRepository.java b/spring-4/src/main/java/com/baeldung/spring43/depresolution/FooRepository.java new file mode 100644 index 0000000000..281a4f29fd --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/spring43/depresolution/FooRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.spring43.depresolution; + +import org.springframework.stereotype.Repository; + +@Repository +public class FooRepository { + +} diff --git a/spring-4/src/main/java/com/baeldung/spring43/depresolution/FooService.java b/spring-4/src/main/java/com/baeldung/spring43/depresolution/FooService.java new file mode 100644 index 0000000000..1a6b13dc23 --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/spring43/depresolution/FooService.java @@ -0,0 +1,18 @@ +package com.baeldung.spring43.depresolution; + +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.stereotype.Service; + +@Service +public class FooService { + + private final FooRepository repository; + + public FooService(ObjectProvider repositoryProvider) { + this.repository = repositoryProvider.getIfUnique(); + } + + public FooRepository getRepository() { + return repository; + } +} diff --git a/spring-4/src/main/java/org/baeldung/spring43/scopeannotations/AppPreferences.java b/spring-4/src/main/java/com/baeldung/spring43/scopeannotations/AppPreferences.java similarity index 81% rename from spring-4/src/main/java/org/baeldung/spring43/scopeannotations/AppPreferences.java rename to spring-4/src/main/java/com/baeldung/spring43/scopeannotations/AppPreferences.java index 45b90c4609..ede2849a51 100644 --- a/spring-4/src/main/java/org/baeldung/spring43/scopeannotations/AppPreferences.java +++ b/spring-4/src/main/java/com/baeldung/spring43/scopeannotations/AppPreferences.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.scopeannotations; +package com.baeldung.spring43.scopeannotations; import org.springframework.stereotype.Component; import org.springframework.web.context.annotation.ApplicationScope; diff --git a/spring-4/src/main/java/org/baeldung/spring43/scopeannotations/InstanceCountingService.java b/spring-4/src/main/java/com/baeldung/spring43/scopeannotations/InstanceCountingService.java similarity index 86% rename from spring-4/src/main/java/org/baeldung/spring43/scopeannotations/InstanceCountingService.java rename to spring-4/src/main/java/com/baeldung/spring43/scopeannotations/InstanceCountingService.java index 4fb90566d8..e6879e0544 100644 --- a/spring-4/src/main/java/org/baeldung/spring43/scopeannotations/InstanceCountingService.java +++ b/spring-4/src/main/java/com/baeldung/spring43/scopeannotations/InstanceCountingService.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.scopeannotations; +package com.baeldung.spring43.scopeannotations; import java.util.concurrent.atomic.AtomicInteger; diff --git a/spring-4/src/main/java/org/baeldung/spring43/scopeannotations/LoginAction.java b/spring-4/src/main/java/com/baeldung/spring43/scopeannotations/LoginAction.java similarity index 80% rename from spring-4/src/main/java/org/baeldung/spring43/scopeannotations/LoginAction.java rename to spring-4/src/main/java/com/baeldung/spring43/scopeannotations/LoginAction.java index 60017b4b94..132e701b5a 100644 --- a/spring-4/src/main/java/org/baeldung/spring43/scopeannotations/LoginAction.java +++ b/spring-4/src/main/java/com/baeldung/spring43/scopeannotations/LoginAction.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.scopeannotations; +package com.baeldung.spring43.scopeannotations; import org.springframework.stereotype.Component; import org.springframework.web.context.annotation.RequestScope; diff --git a/spring-4/src/main/java/org/baeldung/spring43/scopeannotations/ScopeTestController.java b/spring-4/src/main/java/com/baeldung/spring43/scopeannotations/ScopeTestController.java similarity index 95% rename from spring-4/src/main/java/org/baeldung/spring43/scopeannotations/ScopeTestController.java rename to spring-4/src/main/java/com/baeldung/spring43/scopeannotations/ScopeTestController.java index 8f4390dfc0..bd3e3e9b92 100644 --- a/spring-4/src/main/java/org/baeldung/spring43/scopeannotations/ScopeTestController.java +++ b/spring-4/src/main/java/com/baeldung/spring43/scopeannotations/ScopeTestController.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.scopeannotations; +package com.baeldung.spring43.scopeannotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-4/src/main/java/org/baeldung/spring43/scopeannotations/UserPreferences.java b/spring-4/src/main/java/com/baeldung/spring43/scopeannotations/UserPreferences.java similarity index 81% rename from spring-4/src/main/java/org/baeldung/spring43/scopeannotations/UserPreferences.java rename to spring-4/src/main/java/com/baeldung/spring43/scopeannotations/UserPreferences.java index ce49c4b1fe..27f313b2cb 100644 --- a/spring-4/src/main/java/org/baeldung/spring43/scopeannotations/UserPreferences.java +++ b/spring-4/src/main/java/com/baeldung/spring43/scopeannotations/UserPreferences.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.scopeannotations; +package com.baeldung.spring43.scopeannotations; import org.springframework.stereotype.Component; import org.springframework.web.context.annotation.SessionScope; diff --git a/spring-4/src/main/java/org/baeldung/spring43/cache/Foo.java b/spring-4/src/main/java/org/baeldung/spring43/cache/Foo.java deleted file mode 100644 index ce34adf6c1..0000000000 --- a/spring-4/src/main/java/org/baeldung/spring43/cache/Foo.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.baeldung.spring43.cache; - -import java.util.concurrent.atomic.AtomicInteger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Foo { - - private static final Logger log = LoggerFactory.getLogger(Foo.class); - - private static final AtomicInteger instanceCount = new AtomicInteger(0); - - private final int instanceNum; - - public Foo() { - instanceNum = instanceCount.incrementAndGet(); - } - - public static int getInstanceCount() { - return instanceCount.get(); - } - - public void printInstanceNumber() { - log.info("Foo instance number: {}", instanceNum); - } - -} diff --git a/spring-4/src/main/java/org/baeldung/spring43/cache/FooService.java b/spring-4/src/main/java/org/baeldung/spring43/cache/FooService.java deleted file mode 100644 index ad4c8b395f..0000000000 --- a/spring-4/src/main/java/org/baeldung/spring43/cache/FooService.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.spring43.cache; - -import org.springframework.cache.annotation.Cacheable; -import org.springframework.stereotype.Service; - -@Service -public class FooService { - - @Cacheable(cacheNames = "foos", sync = true) - public Foo getFoo(String id) { - return new Foo(); - } - -} diff --git a/spring-4/src/main/java/org/baeldung/spring43/composedmapping/Appointment.java b/spring-4/src/main/java/org/baeldung/spring43/composedmapping/Appointment.java deleted file mode 100644 index af06249768..0000000000 --- a/spring-4/src/main/java/org/baeldung/spring43/composedmapping/Appointment.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.spring43.composedmapping; - -public class Appointment { - -} diff --git a/spring-4/src/main/java/org/baeldung/spring43/composedmapping/AppointmentService.java b/spring-4/src/main/java/org/baeldung/spring43/composedmapping/AppointmentService.java deleted file mode 100644 index c4c5e82f65..0000000000 --- a/spring-4/src/main/java/org/baeldung/spring43/composedmapping/AppointmentService.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.spring43.composedmapping; - -import java.util.Map; - -public interface AppointmentService { - - Map getAppointmentsForToday(); - -} diff --git a/spring-4/src/main/java/org/baeldung/spring43/ctor/FooRepository.java b/spring-4/src/main/java/org/baeldung/spring43/ctor/FooRepository.java deleted file mode 100644 index 96dbeb8642..0000000000 --- a/spring-4/src/main/java/org/baeldung/spring43/ctor/FooRepository.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.spring43.ctor; - -public class FooRepository { - -} diff --git a/spring-4/src/main/java/org/baeldung/spring43/ctor/FooService.java b/spring-4/src/main/java/org/baeldung/spring43/ctor/FooService.java deleted file mode 100644 index bf92d1bd32..0000000000 --- a/spring-4/src/main/java/org/baeldung/spring43/ctor/FooService.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.spring43.ctor; - -public class FooService { - - private final FooRepository repository; - - public FooService(FooRepository repository) { - this.repository = repository; - } - - public FooRepository getRepository() { - return repository; - } - -} \ No newline at end of file diff --git a/spring-4/src/main/java/org/baeldung/spring43/depresolution/FooRepository.java b/spring-4/src/main/java/org/baeldung/spring43/depresolution/FooRepository.java deleted file mode 100644 index 313f6fc8c5..0000000000 --- a/spring-4/src/main/java/org/baeldung/spring43/depresolution/FooRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.spring43.depresolution; - -import org.springframework.stereotype.Repository; - -@Repository -public class FooRepository { - -} diff --git a/spring-4/src/main/java/org/baeldung/spring43/depresolution/FooService.java b/spring-4/src/main/java/org/baeldung/spring43/depresolution/FooService.java deleted file mode 100644 index b76fa84749..0000000000 --- a/spring-4/src/main/java/org/baeldung/spring43/depresolution/FooService.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.spring43.depresolution; - -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.stereotype.Service; - -@Service -public class FooService { - - private final FooRepository repository; - - public FooService(ObjectProvider repositoryProvider) { - this.repository = repositoryProvider.getIfUnique(); - } - - public FooRepository getRepository() { - return repository; - } -} diff --git a/spring-4/src/main/resources/defaultmethods-context.xml b/spring-4/src/main/resources/defaultmethods-context.xml index 2b55037405..5725d0cabf 100644 --- a/spring-4/src/main/resources/defaultmethods-context.xml +++ b/spring-4/src/main/resources/defaultmethods-context.xml @@ -3,7 +3,7 @@ xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - + diff --git a/spring-4/src/main/resources/implicit-ctor-context.xml b/spring-4/src/main/resources/implicit-ctor-context.xml index c978ca17bd..3dc0058f94 100644 --- a/spring-4/src/main/resources/implicit-ctor-context.xml +++ b/spring-4/src/main/resources/implicit-ctor-context.xml @@ -3,8 +3,8 @@ xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - + - + diff --git a/spring-4/src/test/java/com/baeldung/SpringContextTest.java b/spring-4/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..46308d41ea --- /dev/null +++ b/spring-4/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.flips.ApplicationConfig; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ApplicationConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-4/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java b/spring-4/src/test/java/com/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java similarity index 95% rename from spring-4/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java rename to spring-4/src/test/java/com/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java index 97ae651473..97b92a943c 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java +++ b/spring-4/src/test/java/com/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.attributeannotations; +package com.baeldung.spring43.attributeannotations; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; diff --git a/spring-4/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java b/spring-4/src/test/java/com/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java similarity index 96% rename from spring-4/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java index fff2716a64..f696a6f537 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java +++ b/spring-4/src/test/java/com/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.attributeannotations; +package com.baeldung.spring43.attributeannotations; import org.junit.Assert; import org.junit.Before; diff --git a/spring-4/src/test/java/org/baeldung/spring43/cache/CacheRefinementsConfiguration.java b/spring-4/src/test/java/com/baeldung/spring43/cache/CacheRefinementsConfiguration.java similarity index 95% rename from spring-4/src/test/java/org/baeldung/spring43/cache/CacheRefinementsConfiguration.java rename to spring-4/src/test/java/com/baeldung/spring43/cache/CacheRefinementsConfiguration.java index e4610e5a83..45acb11f72 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/cache/CacheRefinementsConfiguration.java +++ b/spring-4/src/test/java/com/baeldung/spring43/cache/CacheRefinementsConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.cache; +package com.baeldung.spring43.cache; import java.util.Collections; diff --git a/spring-4/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java b/spring-4/src/test/java/com/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java similarity index 96% rename from spring-4/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java index fa72ed6d43..3f56bb21ff 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java +++ b/spring-4/src/test/java/com/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.cache; +package com.baeldung.spring43.cache; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; diff --git a/spring-4/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingConfiguration.java b/spring-4/src/test/java/com/baeldung/spring43/composedmapping/ComposedMappingConfiguration.java similarity index 96% rename from spring-4/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingConfiguration.java rename to spring-4/src/test/java/com/baeldung/spring43/composedmapping/ComposedMappingConfiguration.java index f1028ebefb..c3a0ceba36 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingConfiguration.java +++ b/spring-4/src/test/java/com/baeldung/spring43/composedmapping/ComposedMappingConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.composedmapping; +package com.baeldung.spring43.composedmapping; import java.util.Collections; diff --git a/spring-4/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java b/spring-4/src/test/java/com/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java similarity index 96% rename from spring-4/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java index d0af48cd0e..d5c912b69b 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java +++ b/spring-4/src/test/java/com/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.composedmapping; +package com.baeldung.spring43.composedmapping; import org.junit.Before; import org.junit.Test; diff --git a/spring-4/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java b/spring-4/src/test/java/com/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java similarity index 94% rename from spring-4/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java index 871a985479..848fa44365 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java +++ b/spring-4/src/test/java/com/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.ctor; +package com.baeldung.spring43.ctor; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-4/src/test/java/org/baeldung/spring43/ctor/FooRepositoryConfiguration.java b/spring-4/src/test/java/com/baeldung/spring43/ctor/FooRepositoryConfiguration.java similarity index 88% rename from spring-4/src/test/java/org/baeldung/spring43/ctor/FooRepositoryConfiguration.java rename to spring-4/src/test/java/com/baeldung/spring43/ctor/FooRepositoryConfiguration.java index a05a36529f..fb33942844 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/ctor/FooRepositoryConfiguration.java +++ b/spring-4/src/test/java/com/baeldung/spring43/ctor/FooRepositoryConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.ctor; +package com.baeldung.spring43.ctor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-4/src/test/java/org/baeldung/spring43/ctor/FooServiceConfiguration.java b/spring-4/src/test/java/com/baeldung/spring43/ctor/FooServiceConfiguration.java similarity index 92% rename from spring-4/src/test/java/org/baeldung/spring43/ctor/FooServiceConfiguration.java rename to spring-4/src/test/java/com/baeldung/spring43/ctor/FooServiceConfiguration.java index 41f1719320..5ab09e37ec 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/ctor/FooServiceConfiguration.java +++ b/spring-4/src/test/java/com/baeldung/spring43/ctor/FooServiceConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.ctor; +package com.baeldung.spring43.ctor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-4/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java b/spring-4/src/test/java/com/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java similarity index 94% rename from spring-4/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java index 83fa11294e..5296927ef2 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java +++ b/spring-4/src/test/java/com/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.ctor; +package com.baeldung.spring43.ctor; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-4/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java b/spring-4/src/test/java/com/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java similarity index 93% rename from spring-4/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java index 956df44821..f617d48920 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java +++ b/spring-4/src/test/java/com/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.defaultmethods; +package com.baeldung.spring43.defaultmethods; import java.time.LocalDate; diff --git a/spring-4/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java b/spring-4/src/test/java/com/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java similarity index 92% rename from spring-4/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java rename to spring-4/src/test/java/com/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java index 3c180e91c8..a8f44d722d 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java +++ b/spring-4/src/test/java/com/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.defaultmethods; +package com.baeldung.spring43.defaultmethods; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-4/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java b/spring-4/src/test/java/com/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java similarity index 91% rename from spring-4/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java index dde153487d..7df6040456 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java +++ b/spring-4/src/test/java/com/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.defaultmethods; +package com.baeldung.spring43.defaultmethods; import org.junit.Test; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-4/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java b/spring-4/src/test/java/com/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java similarity index 95% rename from spring-4/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java rename to spring-4/src/test/java/com/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java index 8a8cec3f86..6323854099 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java +++ b/spring-4/src/test/java/com/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.defaultmethods; +package com.baeldung.spring43.defaultmethods; import javax.sql.DataSource; diff --git a/spring-4/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderConfiguration.java b/spring-4/src/test/java/com/baeldung/spring43/depresolution/ObjectProviderConfiguration.java similarity index 81% rename from spring-4/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderConfiguration.java rename to spring-4/src/test/java/com/baeldung/spring43/depresolution/ObjectProviderConfiguration.java index 530c4d9f4a..020b50ceb2 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderConfiguration.java +++ b/spring-4/src/test/java/com/baeldung/spring43/depresolution/ObjectProviderConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.depresolution; +package com.baeldung.spring43.depresolution; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; diff --git a/spring-4/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java b/spring-4/src/test/java/com/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java similarity index 93% rename from spring-4/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java index 6d06bfdc2a..29ce530a50 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java +++ b/spring-4/src/test/java/com/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.depresolution; +package com.baeldung.spring43.depresolution; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-4/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsConfiguration.java b/spring-4/src/test/java/com/baeldung/spring43/scopeannotations/ScopeAnnotationsConfiguration.java similarity index 93% rename from spring-4/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsConfiguration.java rename to spring-4/src/test/java/com/baeldung/spring43/scopeannotations/ScopeAnnotationsConfiguration.java index 24c1ec2f34..a7d9c16721 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsConfiguration.java +++ b/spring-4/src/test/java/com/baeldung/spring43/scopeannotations/ScopeAnnotationsConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.scopeannotations; +package com.baeldung.spring43.scopeannotations; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; diff --git a/spring-4/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java b/spring-4/src/test/java/com/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java similarity index 98% rename from spring-4/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java index 69cce15029..f2cea121cc 100644 --- a/spring-4/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java +++ b/spring-4/src/test/java/com/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring43.scopeannotations; +package com.baeldung.spring43.scopeannotations; import org.junit.Before; import org.junit.Test; diff --git a/spring-4/src/test/java/org/baeldung/SpringContextTest.java b/spring-4/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index cccdaff0cd..0000000000 --- a/spring-4/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -import com.baeldung.flips.ApplicationConfig; - - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = ApplicationConfig.class) -@WebAppConfiguration -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index 230f25768e..aeaf6daf1a 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -17,6 +17,7 @@ io.projectreactor reactor-core + ${reactor-core.version} org.springframework.boot @@ -213,31 +214,16 @@ - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - 1.2.40 1.2.40 - 5.2.0.M2 - 1.0.0.M2 - 0.8.0.M8 + 5.2.2.RELEASE + 1.0.0.RELEASE + 0.8.1.RELEASE 4.5.2 - 1.4.199 + 1.4.200 1.5.23 + 3.3.1.RELEASE diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java index 33b653140e..20f7642a7c 100644 --- a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java @@ -1,8 +1,10 @@ package com.baeldung.r2dbc.repository; -import com.baeldung.r2dbc.model.Player; -import org.springframework.data.r2dbc.repository.query.Query; +import org.springframework.data.r2dbc.repository.Query; import org.springframework.data.repository.reactive.ReactiveCrudRepository; + +import com.baeldung.r2dbc.model.Player; + import reactor.core.publisher.Flux; public interface PlayerRepository extends ReactiveCrudRepository { diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/SpringContextTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..bedb30fcaa --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.reactive.Spring5ReactiveApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java index ffd2e98f8e..1af570587e 100644 --- a/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java +++ b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java @@ -43,8 +43,7 @@ public class R2dbcApplicationIntegrationTest { "DROP TABLE IF EXISTS player;", "CREATE table player (id INT AUTO_INCREMENT NOT NULL, name VARCHAR2, age INT NOT NULL);"); - statements.forEach(it -> client.execute() // - .sql(it) // + statements.forEach(it -> client.execute(it) // .fetch() // .rowsUpdated() // .as(StepVerifier::create) // diff --git a/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index c3ea1d8435..0000000000 --- a/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.reactive.Spring5ReactiveApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Spring5ReactiveApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index e98012c047..aff8bb227c 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -6,3 +6,4 @@ This module contains articles about Spring 5 model-view-controller (MVC) pattern - [Spring Boot and Kotlin](https://www.baeldung.com/spring-boot-kotlin) - [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) - [Interface Driven Controllers in Spring](https://www.baeldung.com/spring-interface-driven-controllers) +- [Returning Plain HTML From a Spring MVC Controller](https://www.baeldung.com/spring-mvc-return-html) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 2f8ef05bff..4b42528d0f 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -42,6 +42,11 @@ org.slf4j jcl-over-slf4j + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + org.jetbrains.kotlin @@ -175,8 +180,8 @@ 2.9.0 2.9.9 1.2.71 - com.baeldung.Spring5Application 4.5.8 + com.baeldung.Spring5Application diff --git a/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java new file mode 100644 index 0000000000..ad660559c7 --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.html; + +import org.springframework.boot.*; +import org.springframework.boot.autoconfigure.*; + +@SpringBootApplication +public class HtmlApplication +{ + public static void main(String[] args) { + SpringApplication.run(HtmlApplication.class, args); + } +} diff --git a/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java new file mode 100644 index 0000000000..23674d165e --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java @@ -0,0 +1,17 @@ +package com.baeldung.html; + +import org.springframework.http.*; +import org.springframework.stereotype.*; +import org.springframework.web.bind.annotation.*; + +@Controller +public class HtmlController +{ + @GetMapping(value = "/welcome", produces = MediaType.TEXT_HTML_VALUE) + @ResponseBody + public String welcomeAsHTML() + { + return "\n" + "
Welcome
\n" + + "\n" + "Hello world\n" + "\n" + ""; + } +} diff --git a/spring-5-mvc/src/main/resources/application.properties b/spring-5-mvc/src/main/resources/application.properties index 886ea1978b..ccec014c2b 100644 --- a/spring-5-mvc/src/main/resources/application.properties +++ b/spring-5-mvc/src/main/resources/application.properties @@ -1,6 +1,3 @@ server.port=8081 -security.user.name=user -security.user.password=pass - logging.level.root=INFO \ No newline at end of file diff --git a/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java b/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java new file mode 100644 index 0000000000..8eba4e8cf9 --- /dev/null +++ b/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java @@ -0,0 +1,30 @@ +package com.baeldung.html; + +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.*; +import org.springframework.boot.test.autoconfigure.web.servlet.*; +import org.springframework.test.web.servlet.*; +import org.springframework.test.web.servlet.request.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@WebMvcTest(HtmlController.class) +class HtmlControllerUnitTest { + + @Autowired + private MockMvc mockMvc; + + private final String expectedHtmlResponse = + "\n" + "
Welcome
\n" + + "\n" + "Hello world\n" + "\n" + ""; + + @Test + void whenGETRequestToCorrectURL_thenReturnCorrectWelcomeMessage() throws Exception { + MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/welcome")) + .andExpect(status().isOk()) + .andReturn(); + + String resultDOW = result.getResponse().getContentAsString(); + assertEquals(expectedHtmlResponse, resultDOW); + } +} diff --git a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java index b7ed031ec7..9d04541f8d 100644 --- a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java +++ b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java @@ -52,14 +52,13 @@ public class ConsumerFooServiceIntegrationTest { .map(Arrays::stream) .orElse(Stream.empty()); }) - .map(IThrowableProxy::getMessage) + .map(IThrowableProxy::getClassName) .collect(Collectors.toList()); assertThat(allLoggedEntries).anyMatch(entry -> entry.contains("The following error happened on processFoo method!")) .anyMatch(entry -> entry.contains("| onSubscribe")) .anyMatch(entry -> entry.contains("| cancel()")); - assertThat(allSuppressedEntries).anyMatch(entry -> entry.contains("Assembly trace from producer")) - .anyMatch(entry -> entry.contains("Error has been observed by the following operator(s)")); + assertThat(allSuppressedEntries) + .anyMatch(entry -> entry.contains("reactor.core.publisher.FluxOnAssembly$OnAssemblyException")); } - } diff --git a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java index af9bdfbc9b..e61ea9e155 100644 --- a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java +++ b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java @@ -7,6 +7,11 @@ import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; import com.baeldung.debugging.consumer.service.FooService; +/** + * In order to run this live test, start the following classes: + * - com.baeldung.debugging.server.ServerDebuggingApplication + * - com.baeldung.debugging.consumer.ConsumerDebuggingApplication + */ public class ConsumerFooServiceLiveTest { FooService service = new FooService(); diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 2981fc4f77..cc728398f3 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 spring-5-reactive-client spring-5-reactive-client @@ -90,8 +92,8 @@
com.github.tomakehurst - wiremock - 2.24.1 + wiremock-standalone + 2.26.0 test diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/SpringContextTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c0ca9b7e64 --- /dev/null +++ b/spring-5-reactive-client/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.reactive.Spring5ReactiveTestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveTestApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/ReactiveIntegrationTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/ReactiveIntegrationTest.java index 394ff42e5f..1d2197a381 100644 --- a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/ReactiveIntegrationTest.java +++ b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/ReactiveIntegrationTest.java @@ -1,37 +1,67 @@ package com.baeldung.reactive; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; import com.baeldung.reactive.model.Foo; +import com.github.tomakehurst.wiremock.WireMockServer; import reactor.core.publisher.Mono; +@RunWith(SpringRunner.class) @SpringBootTest public class ReactiveIntegrationTest { private WebClient client; - - @BeforeEach - public void before() { - client = WebClient.create("http://localhost:8080"); + private int singleRequestTime = 1000; + private WireMockServer wireMockServer; + + @Before + public void setup() { + wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()); + wireMockServer.start(); + configureFor("localhost", wireMockServer.port()); + client = WebClient.create("http://localhost:" + wireMockServer.port()); } - // + @After + public void tearDown() { + wireMockServer.stop(); + } @Test public void whenMonoReactiveEndpointIsConsumed_thenCorrectOutput() { - final Mono fooMono = client.get().uri("/foos/123").exchange().log(); + stubFor(get(urlEqualTo("/foo/123")).willReturn(aResponse().withFixedDelay(singleRequestTime) + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{\"id\":123, \"name\":\"foo\"}"))); + + final Mono fooMono = client.get().uri("/foo/123").exchange().log(); System.out.println(fooMono.subscribe()); } @Test public void whenFluxReactiveEndpointIsConsumed_thenCorrectOutput() throws InterruptedException { - client.get().uri("/foos") + stubFor(get(urlEqualTo("/foo")).willReturn(aResponse().withFixedDelay(singleRequestTime) + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{\"id\":1, \"name\":\"foo\"}"))); + + client.get().uri("/foo") .retrieve() .bodyToFlux(Foo.class).log() .subscribe(System.out::println); diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/webclient/simultaneous/ClientIntegrationTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/webclient/simultaneous/ClientIntegrationTest.java index d74a64d9c9..43454daf17 100644 --- a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/webclient/simultaneous/ClientIntegrationTest.java +++ b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/webclient/simultaneous/ClientIntegrationTest.java @@ -5,6 +5,7 @@ import org.junit.Before; import org.junit.After; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import com.github.tomakehurst.wiremock.WireMockServer; @@ -19,15 +20,19 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest +@DirtiesContext public class ClientIntegrationTest { private WireMockServer wireMockServer; + private Client client; + @Before public void setup() { - wireMockServer = new WireMockServer(wireMockConfig().port(8089)); + wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()); wireMockServer.start(); configureFor("localhost", wireMockServer.port()); + client = new Client("http://localhost:" + wireMockServer.port()); } @After @@ -52,8 +57,6 @@ public class ClientIntegrationTest { .boxed() .collect(Collectors.toList()); - Client client = new Client("http://localhost:8089"); - // Act long start = System.currentTimeMillis(); List users = client.fetchUsers(userIds) diff --git a/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 678d04897b..0000000000 --- a/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.reactive.Spring5ReactiveTestApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Spring5ReactiveTestApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-5-reactive-security/README.md b/spring-5-reactive-security/README.md index 4ea6fb644f..a0f47a503d 100644 --- a/spring-5-reactive-security/README.md +++ b/spring-5-reactive-security/README.md @@ -11,3 +11,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Security 5 for Reactive Applications](https://www.baeldung.com/spring-security-5-reactive) - [Guide to Spring 5 WebFlux](https://www.baeldung.com/spring-webflux) - [Introduction to the Functional Web Framework in Spring 5](https://www.baeldung.com/spring-5-functional-web) +- [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml index 2f4a31241b..58c993bda5 100644 --- a/spring-5-reactive-security/pom.xml +++ b/spring-5-reactive-security/pom.xml @@ -128,7 +128,7 @@ 1.0 4.1 3.1.6.RELEASE - 2.2.1.RELEASE + 2.2.2.RELEASE diff --git a/spring-5-reactive-security/src/test/java/com/baeldung/SpringContextTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b4f4118527 --- /dev/null +++ b/spring-5-reactive-security/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.reactive.security.SpringSecurity5Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSecurity5Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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 index 6e73e8072c..d8e2f0b23b 100644 --- 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 @@ -1,11 +1,7 @@ package com.baeldung.reactive.functional; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; - -import java.util.ArrayList; -import java.util.List; - +import com.baeldung.webflux.Employee; +import com.baeldung.webflux.EmployeeRepository; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -15,13 +11,15 @@ 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.webflux.Employee; -import com.baeldung.webflux.EmployeeRepository; - import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import java.util.Arrays; +import java.util.List; + +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @@ -58,15 +56,11 @@ public class EmployeeSpringFunctionalIntegrationTest { .bindToRouterFunction(config.getAllEmployeesRoute()) .build(); - List employeeList = new ArrayList<>(); + List employees = Arrays.asList( + new Employee("1", "Employee 1"), + new Employee("2", "Employee 2")); - Employee employee1 = new Employee("1", "Employee 1"); - Employee employee2 = new Employee("2", "Employee 2"); - - employeeList.add(employee1); - employeeList.add(employee2); - - Flux employeeFlux = Flux.fromIterable(employeeList); + Flux employeeFlux = Flux.fromIterable(employees); given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); client.get() @@ -75,7 +69,7 @@ public class EmployeeSpringFunctionalIntegrationTest { .expectStatus() .isOk() .expectBodyList(Employee.class) - .isEqualTo(employeeList); + .isEqualTo(employees); } @Test diff --git a/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 479c35d986..0000000000 --- a/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.reactive.security.SpringSecurity5Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringSecurity5Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-5-reactive/src/test/java/com/baeldung/SpringContextTest.java b/spring-5-reactive/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..bedb30fcaa --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.reactive.Spring5ReactiveApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index c3ea1d8435..0000000000 --- a/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.reactive.Spring5ReactiveApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Spring5ReactiveApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-5-security/README.md b/spring-5-security/README.md index 4cace0db8d..07f2d48b7f 100644 --- a/spring-5-security/README.md +++ b/spring-5-security/README.md @@ -8,4 +8,4 @@ This module contains articles about Spring Security 5 - [A Custom Spring SecurityConfigurer](https://www.baeldung.com/spring-security-custom-configurer) - [New Password Storage In Spring Security 5](https://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) - +- [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) diff --git a/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java b/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java new file mode 100644 index 0000000000..50ea356f03 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.manuallogout; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ManualLogoutApplication { + public static void main(String[] args) { + SpringApplication.run(ManualLogoutApplication.class, args); + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java b/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java new file mode 100644 index 0000000000..08c2d83b99 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java @@ -0,0 +1,76 @@ +package com.baeldung.manuallogout; + +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; + +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.logout.HeaderWriterLogoutHandler; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; + +import javax.servlet.http.Cookie; + +import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.*; + +@Configuration +@EnableWebSecurity +public class SimpleSecurityConfiguration { + + @Order(3) + @Configuration + public static class DefaultLogoutConfiguration extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .antMatcher("/basic/**") + .authorizeRequests(authz -> authz.anyRequest().permitAll()) + .logout(logout -> logout + .logoutUrl("/basic/basiclogout") + ); + } + } + + @Order(2) + @Configuration + public static class AllCookieClearingLogoutConfiguration extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .antMatcher("/cookies/**") + .authorizeRequests(authz -> authz.anyRequest().permitAll()) + .logout(logout -> logout + .logoutUrl("/cookies/cookielogout") + .addLogoutHandler(new SecurityContextLogoutHandler()) + .addLogoutHandler((request, response, auth) -> { + for (Cookie cookie : request.getCookies()) { + String cookieName = cookie.getName(); + Cookie cookieToDelete = new Cookie(cookieName, null); + cookieToDelete.setMaxAge(0); + response.addCookie(cookieToDelete); + } + }) + ); + } + } + + @Order(1) + @Configuration + public static class ClearSiteDataHeaderLogoutConfiguration extends WebSecurityConfigurerAdapter { + + private static final ClearSiteDataHeaderWriter.Directive[] SOURCE = + {CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS}; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .antMatcher("/csd/**") + .authorizeRequests(authz -> authz.anyRequest().permitAll()) + .logout(logout -> logout + .logoutUrl("/csd/csdlogout") + .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE))) + ); + } + } +} diff --git a/spring-5-security/src/test/java/com/baeldung/SpringContextTest.java b/spring-5-security/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7812a5c063 --- /dev/null +++ b/spring-5-security/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.dsl.CustomConfigurerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CustomConfigurerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java b/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java new file mode 100644 index 0000000000..8909dc2620 --- /dev/null +++ b/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java @@ -0,0 +1,79 @@ +package com.baeldung.manuallogout; + +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.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpSession; + +import static org.junit.Assert.assertNull; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringRunner.class) +@WebMvcTest() +public class ManualLogoutIntegrationTest { + + private static final String CLEAR_SITE_DATA_HEADER = "Clear-Site-Data"; + public static final int EXPIRY = 60 * 10; + public static final String COOKIE_NAME = "customerName"; + public static final String COOKIE_VALUE = "myName"; + public static final String ATTRIBUTE_NAME = "att"; + public static final String ATTRIBUTE_VALUE = "attvalue"; + + @Autowired + private MockMvc mockMvc; + + @WithMockUser(value = "spring") + @Test + public void givenLoggedUserWhenUserLogoutThenSessionClearedAndNecessaryCookieCleared() throws Exception { + + this.mockMvc.perform(post("/basic/basiclogout").secure(true).with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(unauthenticated()) + .andReturn(); + } + + @WithMockUser(value = "spring") + @Test + public void givenLoggedUserWhenUserLogoutThenSessionClearedAndAllCookiesCleared() throws Exception { + + MockHttpSession session = new MockHttpSession(); + session.setAttribute(ATTRIBUTE_NAME, ATTRIBUTE_VALUE); + + Cookie randomCookie = new Cookie(COOKIE_NAME, COOKIE_VALUE); + randomCookie.setMaxAge(EXPIRY); // 10 minutes + + MockHttpServletRequest requestStateAfterLogout = this.mockMvc.perform(post("/cookies/cookielogout").secure(true).with(csrf()).session(session).cookie(randomCookie)) + .andExpect(status().is3xxRedirection()) + .andExpect(unauthenticated()) + .andExpect(cookie().maxAge(COOKIE_NAME, 0)) + .andReturn() + .getRequest(); + + HttpSession sessionStateAfterLogout = requestStateAfterLogout.getSession(); + assertNull(sessionStateAfterLogout.getAttribute(ATTRIBUTE_NAME)); + } + + @WithMockUser(value = "spring") + @Test + public void givenLoggedUserWhenUserLogoutThenClearDataSiteHeaderPresent() throws Exception { + + this.mockMvc.perform(post("/csd/csdlogout").secure(true).with(csrf())) + .andDo(print()) + .andExpect(status().is3xxRedirection()) + .andExpect(header().exists(CLEAR_SITE_DATA_HEADER)) + .andReturn(); + } +} \ No newline at end of file diff --git a/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 729790bd14..0000000000 --- a/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.dsl.CustomConfigurerApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = CustomConfigurerApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index 84ee3e332c..22f429da2a 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -64,38 +64,6 @@ - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - 2.2.0.RELEASE diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/TimeoutController.java b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/TimeoutController.java new file mode 100644 index 0000000000..a4cd6bd6ba --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/TimeoutController.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.serverconfig; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Mono; + +@RestController +@RequestMapping("/timeout") +public class TimeoutController { + + @GetMapping("/{timeout}") + private Mono timeout(@PathVariable int timeout) { + try { + Thread.sleep(timeout * 1000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return Mono.just("OK"); + } +} diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/TimeoutLiveTest.java b/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/TimeoutLiveTest.java new file mode 100644 index 0000000000..c53fd4fa80 --- /dev/null +++ b/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/TimeoutLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.spring.serverconfig; + +import java.util.concurrent.TimeUnit; + +import javax.net.ssl.SSLException; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +import io.netty.channel.ChannelOption; +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import io.netty.handler.timeout.ReadTimeoutException; +import io.netty.handler.timeout.ReadTimeoutHandler; +import io.netty.handler.timeout.WriteTimeoutHandler; +import reactor.netty.http.client.HttpClient; +import reactor.netty.tcp.TcpClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) +@DirtiesContext +public class TimeoutLiveTest { + + private static final String BASE_URL = "https://localhost:8443"; + private static final int TIMEOUT_MILLIS = 2000; + + private WebTestClient webTestClient; + + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Before + public void setup() throws SSLException { + webTestClient = WebTestClient.bindToServer(getConnector()) + .baseUrl(BASE_URL) + .build(); + } + + @Test + public void shouldTimeout() { + exception.expect(ReadTimeoutException.class); + webTestClient.get() + .uri("/timeout/{timeout}", 3) + .exchange(); + } + + @Test + public void shouldNotTimeout() { + WebTestClient.ResponseSpec response = webTestClient.get() + .uri("/timeout/{timeout}", 1) + .exchange(); + response.expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("OK"); + } + + private ReactorClientHttpConnector getConnector() throws SSLException { + SslContext sslContext = SslContextBuilder + .forClient() + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .build(); + + TcpClient tcpClient = TcpClient + .create() + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT_MILLIS) + .doOnConnected(connection -> { + connection.addHandlerLast(new ReadTimeoutHandler(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)); + connection.addHandlerLast(new WriteTimeoutHandler(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)); + }); + + HttpClient httpClient = HttpClient.from(tcpClient).secure(t -> t.sslContext(sslContext)); + return new ReactorClientHttpConnector(httpClient); + } +} diff --git a/spring-5/README.md b/spring-5/README.md index 857b199562..d50f9c7544 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -16,3 +16,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Assert Statements](https://www.baeldung.com/spring-assert) - [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) - [Difference between \ vs \](https://www.baeldung.com/spring-contextannotation-contextcomponentscan) +- [Finding the Spring Version](https://www.baeldung.com/spring-find-version) diff --git a/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java index 429d3f433a..b10cfd5f55 100644 --- a/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java @@ -1,6 +1,6 @@ package com.baeldung.restdocs; -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import java.util.ArrayList; import java.util.List; diff --git a/spring-5/src/main/java/com/baeldung/restdocs/IndexController.java b/spring-5/src/main/java/com/baeldung/restdocs/IndexController.java index 2c58d5fe6b..b1516f43c5 100644 --- a/spring-5/src/main/java/com/baeldung/restdocs/IndexController.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/IndexController.java @@ -1,21 +1,25 @@ package com.baeldung.restdocs; -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; - -import org.springframework.hateoas.ResourceSupport; +import org.springframework.hateoas.Link; +import org.springframework.hateoas.RepresentationModel; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; + @RestController @RequestMapping("/") public class IndexController { - @GetMapping - public ResourceSupport index() { - ResourceSupport index = new ResourceSupport(); - index.add(linkTo(CRUDController.class).withRel("crud")); - return index; + static class CustomRepresentationModel extends RepresentationModel { + public CustomRepresentationModel(Link initialLink) { + super(initialLink); + } } + @GetMapping + public CustomRepresentationModel index() { + return new CustomRepresentationModel(linkTo(CRUDController.class).withRel("crud")); + } } \ No newline at end of file diff --git a/spring-5/src/main/java/com/baeldung/version/VersionObtainer.java b/spring-5/src/main/java/com/baeldung/version/VersionObtainer.java new file mode 100644 index 0000000000..392cc44a72 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/version/VersionObtainer.java @@ -0,0 +1,20 @@ +package com.baeldung.version; + +import org.springframework.boot.system.JavaVersion; +import org.springframework.boot.system.SystemProperties; +import org.springframework.core.SpringVersion; + +public class VersionObtainer { + + public String getSpringVersion() { + return SpringVersion.getVersion(); + } + + public String getJavaVersion() { + return JavaVersion.getJavaVersion().toString(); + } + + public String getJdkVersion() { + return SystemProperties.get("java.version"); + } +} diff --git a/spring-5/src/test/java/com/baeldung/SpringContextTest.java b/spring-5/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e3f67def90 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.Spring5Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5/src/test/java/com/baeldung/version/VersionObtainerUnitTest.java b/spring-5/src/test/java/com/baeldung/version/VersionObtainerUnitTest.java new file mode 100644 index 0000000000..6d77cd1403 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/version/VersionObtainerUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.version; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest(classes = VersionObtainer.class) +public class VersionObtainerUnitTest { + + public VersionObtainer version = new VersionObtainer(); + + @Test + public void testGetSpringVersion() { + String res = version.getSpringVersion(); + assertThat(res).isNotEmpty(); + } + + @Test + public void testGetJdkVersion() { + String res = version.getJdkVersion(); + assertThat(res).isNotEmpty(); + } + + @Test + public void testGetJavaVersion() { + String res = version.getJavaVersion(); + assertThat(res).isNotEmpty(); + } +} diff --git a/spring-5/src/test/java/org/baeldung/SpringContextTest.java b/spring-5/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 56e8697f5c..0000000000 --- a/spring-5/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.Spring5Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Spring5Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-akka/src/main/java/org/baeldung/akka/AppConfiguration.java b/spring-akka/src/main/java/com/baeldung/akka/AppConfiguration.java similarity index 76% rename from spring-akka/src/main/java/org/baeldung/akka/AppConfiguration.java rename to spring-akka/src/main/java/com/baeldung/akka/AppConfiguration.java index 9211ae0fdb..3568026d6d 100644 --- a/spring-akka/src/main/java/org/baeldung/akka/AppConfiguration.java +++ b/spring-akka/src/main/java/com/baeldung/akka/AppConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.akka; +package com.baeldung.akka; import akka.actor.ActorSystem; import org.springframework.beans.factory.annotation.Autowired; @@ -7,8 +7,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import static org.baeldung.akka.SpringExtension.SPRING_EXTENSION_PROVIDER; - @Configuration @ComponentScan public class AppConfiguration { @@ -19,7 +17,7 @@ public class AppConfiguration { @Bean public ActorSystem actorSystem() { ActorSystem system = ActorSystem.create("akka-spring-demo"); - SPRING_EXTENSION_PROVIDER.get(system).initialize(applicationContext); + SpringExtension.SPRING_EXTENSION_PROVIDER.get(system).initialize(applicationContext); return system; } diff --git a/spring-akka/src/main/java/org/baeldung/akka/GreetingActor.java b/spring-akka/src/main/java/com/baeldung/akka/GreetingActor.java similarity index 97% rename from spring-akka/src/main/java/org/baeldung/akka/GreetingActor.java rename to spring-akka/src/main/java/com/baeldung/akka/GreetingActor.java index 6366c277a4..35dcd254d6 100644 --- a/spring-akka/src/main/java/org/baeldung/akka/GreetingActor.java +++ b/spring-akka/src/main/java/com/baeldung/akka/GreetingActor.java @@ -1,4 +1,4 @@ -package org.baeldung.akka; +package com.baeldung.akka; import akka.actor.UntypedActor; import org.springframework.beans.factory.config.ConfigurableBeanFactory; diff --git a/spring-akka/src/main/java/com/baeldung/akka/GreetingService.java b/spring-akka/src/main/java/com/baeldung/akka/GreetingService.java new file mode 100644 index 0000000000..aa6883648b --- /dev/null +++ b/spring-akka/src/main/java/com/baeldung/akka/GreetingService.java @@ -0,0 +1,12 @@ +package com.baeldung.akka; + +import org.springframework.stereotype.Component; + +@Component +public class GreetingService { + + public String greet(String name) { + return "Hello, " + name; + } + +} diff --git a/spring-akka/src/main/java/org/baeldung/akka/SpringActorProducer.java b/spring-akka/src/main/java/com/baeldung/akka/SpringActorProducer.java similarity index 96% rename from spring-akka/src/main/java/org/baeldung/akka/SpringActorProducer.java rename to spring-akka/src/main/java/com/baeldung/akka/SpringActorProducer.java index 20813ab60a..289acb4447 100644 --- a/spring-akka/src/main/java/org/baeldung/akka/SpringActorProducer.java +++ b/spring-akka/src/main/java/com/baeldung/akka/SpringActorProducer.java @@ -1,4 +1,4 @@ -package org.baeldung.akka; +package com.baeldung.akka; import akka.actor.Actor; import akka.actor.IndirectActorProducer; diff --git a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java b/spring-akka/src/main/java/com/baeldung/akka/SpringExtension.java similarity index 97% rename from spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java rename to spring-akka/src/main/java/com/baeldung/akka/SpringExtension.java index aa5941c763..96f62da179 100644 --- a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java +++ b/spring-akka/src/main/java/com/baeldung/akka/SpringExtension.java @@ -1,4 +1,4 @@ -package org.baeldung.akka; +package com.baeldung.akka; import akka.actor.AbstractExtensionId; import akka.actor.ExtendedActorSystem; diff --git a/spring-akka/src/main/java/org/baeldung/akka/GreetingService.java b/spring-akka/src/main/java/org/baeldung/akka/GreetingService.java deleted file mode 100644 index 801921887d..0000000000 --- a/spring-akka/src/main/java/org/baeldung/akka/GreetingService.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.akka; - -import org.springframework.stereotype.Component; - -@Component -public class GreetingService { - - public String greet(String name) { - return "Hello, " + name; - } - -} diff --git a/spring-akka/src/test/java/org/baeldung/akka/SpringAkkaIntegrationTest.java b/spring-akka/src/test/java/com/baeldung/akka/SpringAkkaIntegrationTest.java similarity index 90% rename from spring-akka/src/test/java/org/baeldung/akka/SpringAkkaIntegrationTest.java rename to spring-akka/src/test/java/com/baeldung/akka/SpringAkkaIntegrationTest.java index c5da0f747e..3915a46507 100644 --- a/spring-akka/src/test/java/org/baeldung/akka/SpringAkkaIntegrationTest.java +++ b/spring-akka/src/test/java/com/baeldung/akka/SpringAkkaIntegrationTest.java @@ -1,11 +1,11 @@ -package org.baeldung.akka; +package com.baeldung.akka; import java.util.concurrent.TimeUnit; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.util.Timeout; -import org.baeldung.akka.GreetingActor.Greet; +import com.baeldung.akka.GreetingActor.Greet; import org.junit.After; import org.junit.Assert; import org.junit.Test; @@ -17,7 +17,7 @@ import scala.concurrent.Future; import scala.concurrent.duration.FiniteDuration; import static akka.pattern.Patterns.ask; -import static org.baeldung.akka.SpringExtension.SPRING_EXTENSION_PROVIDER; +import static com.baeldung.akka.SpringExtension.SPRING_EXTENSION_PROVIDER; @ContextConfiguration(classes = AppConfiguration.class) public class SpringAkkaIntegrationTest extends AbstractJUnit4SpringContextTests { diff --git a/spring-all/README.md b/spring-all/README.md index d71b8569cf..9ad78aa1ee 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -1,7 +1,3 @@ ## Spring All This module contains articles about Spring - -### Relevant Articles: - -- [The @Scheduled Annotation in Spring](https://www.baeldung.com/spring-scheduled-tasks) diff --git a/spring-amqp/README.md b/spring-amqp/README.md index 0ae4eda12e..7d202f49f8 100644 --- a/spring-amqp/README.md +++ b/spring-amqp/README.md @@ -5,4 +5,6 @@ This module contains articles about Spring with the AMQP messaging system ## Relevant articles: - [Messaging With Spring AMQP](https://www.baeldung.com/spring-amqp) -- [RabbitMQ Message Dispatching with Spring AMQP](https://www.baeldung.com/rabbitmq-spring-amqp) \ No newline at end of file +- [RabbitMQ Message Dispatching with Spring AMQP](https://www.baeldung.com/rabbitmq-spring-amqp) +- [Error Handling with Spring AMQP](https://www.baeldung.com/spring-amqp-error-handling) +- [Exponential Backoff With Spring AMQP](https://www.baeldung.com/spring-amqp-exponential-backoff) diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/ExponentialBackoffApp.java b/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/ExponentialBackoffApp.java new file mode 100644 index 0000000000..182880cc7e --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/ExponentialBackoffApp.java @@ -0,0 +1,11 @@ +package com.baeldung.springamqp.exponentialbackoff; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ExponentialBackoffApp { + public static void main(String[] args) { + SpringApplication.run(ExponentialBackoffApp.class, args); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/ObservableRejectAndDontRequeueRecoverer.java b/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/ObservableRejectAndDontRequeueRecoverer.java new file mode 100644 index 0000000000..700f7ab725 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/ObservableRejectAndDontRequeueRecoverer.java @@ -0,0 +1,21 @@ +package com.baeldung.springamqp.exponentialbackoff; + +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.retry.RejectAndDontRequeueRecoverer; + +public class ObservableRejectAndDontRequeueRecoverer extends RejectAndDontRequeueRecoverer { + private Runnable observer; + + @Override + public void recover(Message message, Throwable cause) { + if(observer != null) { + observer.run(); + } + + super.recover(message, cause); + } + + void setObserver(Runnable observer){ + this.observer = observer; + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/RabbitConfiguration.java b/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/RabbitConfiguration.java new file mode 100644 index 0000000000..2335ecbf58 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/RabbitConfiguration.java @@ -0,0 +1,162 @@ +package com.baeldung.springamqp.exponentialbackoff; + +import org.aopalliance.aop.Advice; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.core.AmqpAdmin; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.core.MessageProperties; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.QueueBuilder; +import org.springframework.amqp.rabbit.annotation.EnableRabbit; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.amqp.rabbit.config.RetryInterceptorBuilder; +import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; +import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; +import org.springframework.amqp.rabbit.connection.ConnectionFactory; +import org.springframework.amqp.rabbit.core.RabbitAdmin; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.retry.interceptor.RetryOperationsInterceptor; + +import com.rabbitmq.client.Channel; + +@EnableRabbit +@Configuration +public class RabbitConfiguration { + + private static Logger logger = LoggerFactory.getLogger(RabbitConfiguration.class); + + @Bean + public ConnectionFactory connectionFactory() { + return new CachingConnectionFactory("localhost"); + } + + @Bean + public AmqpAdmin amqpAdmin() { + return new RabbitAdmin(connectionFactory()); + } + + @Bean + public RabbitTemplate rabbitTemplate() { + return new RabbitTemplate(connectionFactory()); + } + + @Bean + public Queue blockingQueue() { + return QueueBuilder.nonDurable("blocking-queue") + .build(); + } + + @Bean + public Queue nonBlockingQueue() { + return QueueBuilder.nonDurable("non-blocking-queue") + .build(); + } + + @Bean + public Queue retryWaitEndedQueue() { + return QueueBuilder.nonDurable("retry-wait-ended-queue") + .build(); + } + + @Bean + public Queue retryQueue1() { + return QueueBuilder.nonDurable("retry-queue-1") + .deadLetterExchange("") + .deadLetterRoutingKey("retry-wait-ended-queue") + .build(); + } + + @Bean + public Queue retryQueue2() { + return QueueBuilder.nonDurable("retry-queue-2") + .deadLetterExchange("") + .deadLetterRoutingKey("retry-wait-ended-queue") + .build(); + } + + @Bean + public Queue retryQueue3() { + return QueueBuilder.nonDurable("retry-queue-3") + .deadLetterExchange("") + .deadLetterRoutingKey("retry-wait-ended-queue") + .build(); + } + + @Bean + public RetryQueues retryQueues() { + return new RetryQueues(1000, 3.0, 10000, retryQueue1(), retryQueue2(), retryQueue3()); + } + + @Bean + public ObservableRejectAndDontRequeueRecoverer observableRecoverer() { + return new ObservableRejectAndDontRequeueRecoverer(); + } + + @Bean + public RetryOperationsInterceptor retryInterceptor() { + return RetryInterceptorBuilder.stateless() + .backOffOptions(1000, 3.0, 10000) + .maxAttempts(5) + .recoverer(observableRecoverer()) + .build(); + } + + @Bean + public RetryQueuesInterceptor retryQueuesInterceptor(RabbitTemplate rabbitTemplate, RetryQueues retryQueues) { + return new RetryQueuesInterceptor(rabbitTemplate, retryQueues); + } + + @Bean + public SimpleRabbitListenerContainerFactory defaultContainerFactory(ConnectionFactory connectionFactory) { + SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); + factory.setConnectionFactory(connectionFactory); + + return factory; + } + + @Bean + public SimpleRabbitListenerContainerFactory retryContainerFactory(ConnectionFactory connectionFactory, RetryOperationsInterceptor retryInterceptor) { + SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); + factory.setConnectionFactory(connectionFactory); + + Advice[] adviceChain = { retryInterceptor }; + factory.setAdviceChain(adviceChain); + + return factory; + } + + @Bean + public SimpleRabbitListenerContainerFactory retryQueuesContainerFactory(ConnectionFactory connectionFactory, RetryQueuesInterceptor retryInterceptor) { + SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); + factory.setConnectionFactory(connectionFactory); + + Advice[] adviceChain = { retryInterceptor }; + factory.setAdviceChain(adviceChain); + + return factory; + } + + @RabbitListener(queues = "blocking-queue", containerFactory = "retryContainerFactory") + public void consumeBlocking(String payload) throws Exception { + logger.info("Processing message from blocking-queue: {}", payload); + + throw new Exception("exception occured!"); + } + + @RabbitListener(queues = "non-blocking-queue", containerFactory = "retryQueuesContainerFactory", ackMode = "MANUAL") + public void consumeNonBlocking(String payload) throws Exception { + logger.info("Processing message from non-blocking-queue: {}", payload); + + throw new Exception("Error occured!"); + } + + @RabbitListener(queues = "retry-wait-ended-queue", containerFactory = "defaultContainerFactory") + public void consumeRetryWaitEndedMessage(String payload, Message message, Channel channel) throws Exception { + MessageProperties props = message.getMessageProperties(); + + rabbitTemplate().convertAndSend(props.getHeader("x-original-exchange"), props.getHeader("x-original-routing-key"), message); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/RetryQueues.java b/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/RetryQueues.java new file mode 100644 index 0000000000..f52415b3e6 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/RetryQueues.java @@ -0,0 +1,34 @@ +package com.baeldung.springamqp.exponentialbackoff; + +import org.springframework.amqp.core.Queue; + +public class RetryQueues { + private Queue[] queues; + private long initialInterval; + private double factor; + private long maxWait; + + public RetryQueues(long initialInterval, double factor, long maxWait, Queue... queues) { + this.queues = queues; + this.initialInterval = initialInterval; + this.factor = factor; + this.maxWait = maxWait; + } + + public boolean retriesExhausted(int retry) { + return retry >= queues.length; + } + + public String getQueueName(int retry) { + return queues[retry].getName(); + } + + public long getTimeToWait(int retry) { + double time = initialInterval * Math.pow(factor, (double) retry); + if (time > maxWait) { + return maxWait; + } + + return (long) time; + } +} \ No newline at end of file diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/RetryQueuesInterceptor.java b/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/RetryQueuesInterceptor.java new file mode 100644 index 0000000000..f09a71df7c --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/exponentialbackoff/RetryQueuesInterceptor.java @@ -0,0 +1,109 @@ +package com.baeldung.springamqp.exponentialbackoff; + +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +import com.rabbitmq.client.Channel; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.core.MessageProperties; +import org.springframework.amqp.rabbit.core.RabbitTemplate; + +public class RetryQueuesInterceptor implements MethodInterceptor { + + private RabbitTemplate rabbitTemplate; + + private RetryQueues retryQueues; + + private Runnable observer; + + public RetryQueuesInterceptor(RabbitTemplate rabbitTemplate, RetryQueues retryQueues) { + this.rabbitTemplate = rabbitTemplate; + this.retryQueues = retryQueues; + } + + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + return tryConsume(invocation, this::ack, (mac, e) -> { + try { + int retryCount = tryGetRetryCountOrFail(mac, e); + sendToNextRetryQueue(mac, retryCount); + } catch (Throwable t) { + if (observer != null) { + observer.run(); + } + + throw new RuntimeException(t); + } + }); + } + + void setObserver(Runnable observer) { + this.observer = observer; + } + + private Object tryConsume(MethodInvocation invocation, Consumer successHandler, BiConsumer errorHandler) throws Throwable { + MessageAndChannel mac = new MessageAndChannel((Message) invocation.getArguments()[1], (Channel) invocation.getArguments()[0]); + Object ret = null; + try { + ret = invocation.proceed(); + successHandler.accept(mac); + } catch (Throwable e) { + errorHandler.accept(mac, e); + } + return ret; + } + + private void ack(MessageAndChannel mac) { + try { + mac.channel.basicAck(mac.message.getMessageProperties() + .getDeliveryTag(), false); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private int tryGetRetryCountOrFail(MessageAndChannel mac, Throwable originalError) throws Throwable { + MessageProperties props = mac.message.getMessageProperties(); + + String xRetriedCountHeader = (String) props.getHeader("x-retried-count"); + final int xRetriedCount = xRetriedCountHeader == null ? 0 : Integer.valueOf(xRetriedCountHeader); + + if (retryQueues.retriesExhausted(xRetriedCount)) { + mac.channel.basicReject(props.getDeliveryTag(), false); + + throw originalError; + } + + return xRetriedCount; + } + + private void sendToNextRetryQueue(MessageAndChannel mac, int retryCount) throws Exception { + String retryQueueName = retryQueues.getQueueName(retryCount); + + rabbitTemplate.convertAndSend(retryQueueName, mac.message, m -> { + MessageProperties props = m.getMessageProperties(); + props.setExpiration(String.valueOf(retryQueues.getTimeToWait(retryCount))); + props.setHeader("x-retried-count", String.valueOf(retryCount + 1)); + props.setHeader("x-original-exchange", props.getReceivedExchange()); + props.setHeader("x-original-routing-key", props.getReceivedRoutingKey()); + + return m; + }); + + mac.channel.basicReject(mac.message.getMessageProperties() + .getDeliveryTag(), false); + } + + private class MessageAndChannel { + private Message message; + private Channel channel; + + private MessageAndChannel(Message message, Channel channel) { + this.message = message; + this.channel = channel; + } + } +} \ No newline at end of file diff --git a/spring-amqp/src/test/java/com/baeldung/springamqp/exponentialbackoff/ExponentialBackoffLiveTest.java b/spring-amqp/src/test/java/com/baeldung/springamqp/exponentialbackoff/ExponentialBackoffLiveTest.java new file mode 100644 index 0000000000..04bd463a72 --- /dev/null +++ b/spring-amqp/src/test/java/com/baeldung/springamqp/exponentialbackoff/ExponentialBackoffLiveTest.java @@ -0,0 +1,58 @@ +package com.baeldung.springamqp.exponentialbackoff; + +import java.util.concurrent.CountDownLatch; + +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.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * This live test requires: + * + * - A running RabbitMQ instance on localhost (e.g. docker run -p 5672:5672 -p 15672:15672 --name rabbit rabbitmq:3-management) + * + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { RabbitConfiguration.class }) +public class ExponentialBackoffLiveTest { + + @Autowired + private RabbitTemplate rabbitTemplate; + + @Autowired + private ObservableRejectAndDontRequeueRecoverer observableRecoverer; + + @Autowired + private RetryQueuesInterceptor retryQueues; + + @Test + public void whenSendToBlockingQueue_thenAllMessagesProcessed() throws Exception { + int nb = 2; + + CountDownLatch latch = new CountDownLatch(nb); + observableRecoverer.setObserver(() -> latch.countDown()); + + for (int i = 1; i <= nb; i++) { + rabbitTemplate.convertAndSend("blocking-queue", "blocking message " + i); + } + + latch.await(); + } + + @Test + public void whenSendToNonBlockingQueue_thenAllMessageProcessed() throws Exception { + int nb = 2; + + CountDownLatch latch = new CountDownLatch(nb); + retryQueues.setObserver(() -> latch.countDown()); + + for (int i = 1; i <= nb; i++) { + rabbitTemplate.convertAndSend("non-blocking-queue", "non-blocking message " + i); + } + + latch.await(); + } +} diff --git a/spring-amqp/src/test/resources/logback-test.xml b/spring-amqp/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..7eba9aea8b --- /dev/null +++ b/spring-amqp/src/test/resources/logback-test.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/spring-aop/README.md b/spring-aop/README.md index 061e736d31..4522cd63c1 100644 --- a/spring-aop/README.md +++ b/spring-aop/README.md @@ -3,8 +3,9 @@ This module contains articles about Spring aspect oriented programming (AOP) ### Relevant articles - - [Implementing a Custom Spring AOP Annotation](https://www.baeldung.com/spring-aop-annotation) - [Intro to AspectJ](https://www.baeldung.com/aspectj) - [Spring Performance Logging](https://www.baeldung.com/spring-performance-logging) - [Introduction to Spring AOP](https://www.baeldung.com/spring-aop) +- [Introduction to Pointcut Expressions in Spring](https://www.baeldung.com/spring-aop-pointcut-tutorial) +- [Introduction to Advice Types in Spring](https://www.baeldung.com/spring-aop-advice-tutorial) \ No newline at end of file diff --git a/spring-aop/src/main/java/com/baeldung/Application.java b/spring-aop/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..c0490d50c6 --- /dev/null +++ b/spring-aop/src/main/java/com/baeldung/Application.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-aop/src/main/java/org/baeldung/ExampleAspect.java b/spring-aop/src/main/java/com/baeldung/ExampleAspect.java similarity index 88% rename from spring-aop/src/main/java/org/baeldung/ExampleAspect.java rename to spring-aop/src/main/java/com/baeldung/ExampleAspect.java index 7c3b5fb599..482f4b8c08 100644 --- a/spring-aop/src/main/java/org/baeldung/ExampleAspect.java +++ b/spring-aop/src/main/java/com/baeldung/ExampleAspect.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; @@ -9,7 +9,7 @@ import org.springframework.stereotype.Component; @Component public class ExampleAspect { - @Around("@annotation(LogExecutionTime)") + @Around("@annotation(com.baeldung.LogExecutionTime)") public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { final long start = System.currentTimeMillis(); diff --git a/spring-aop/src/main/java/org/baeldung/LogExecutionTime.java b/spring-aop/src/main/java/com/baeldung/LogExecutionTime.java similarity index 92% rename from spring-aop/src/main/java/org/baeldung/LogExecutionTime.java rename to spring-aop/src/main/java/com/baeldung/LogExecutionTime.java index c10f97e78f..c58a3cb7ee 100644 --- a/spring-aop/src/main/java/org/baeldung/LogExecutionTime.java +++ b/spring-aop/src/main/java/com/baeldung/LogExecutionTime.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-aop/src/main/java/com/baeldung/Service.java b/spring-aop/src/main/java/com/baeldung/Service.java new file mode 100644 index 0000000000..01315c9723 --- /dev/null +++ b/spring-aop/src/main/java/com/baeldung/Service.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.stereotype.Component; + +@Component +public class Service { + + @LogExecutionTime + public void serve() throws InterruptedException { + Thread.sleep(2000); + } +} diff --git a/spring-aop/src/main/java/com/baeldung/aspectj/Account.java b/spring-aop/src/main/java/com/baeldung/aspectj/Account.java new file mode 100644 index 0000000000..bc9ca375aa --- /dev/null +++ b/spring-aop/src/main/java/com/baeldung/aspectj/Account.java @@ -0,0 +1,13 @@ +package com.baeldung.aspectj; + +public class Account { + int balance = 20; + + public boolean withdraw(int amount) { + if (balance < amount) { + return false; + } + balance = balance - amount; + return true; + } +} diff --git a/spring-aop/src/main/java/org/baeldung/aspectj/AccountAspect.aj b/spring-aop/src/main/java/com/baeldung/aspectj/AccountAspect.aj similarity index 86% rename from spring-aop/src/main/java/org/baeldung/aspectj/AccountAspect.aj rename to spring-aop/src/main/java/com/baeldung/aspectj/AccountAspect.aj index f08d7dc281..0c79e5546a 100644 --- a/spring-aop/src/main/java/org/baeldung/aspectj/AccountAspect.aj +++ b/spring-aop/src/main/java/com/baeldung/aspectj/AccountAspect.aj @@ -1,4 +1,4 @@ -package org.baeldung.aspectj; +package com.baeldung.aspectj; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -8,7 +8,7 @@ public aspect AccountAspect { final int MIN_BALANCE = 10; pointcut callWithDraw(int amount, Account account): - call(boolean Account.withdraw(int)) && args(amount) && target(account); + call(boolean com.baeldung.aspectj.Account.withdraw(int)) && args(amount) && target(account); before(int amount, Account account) : callWithDraw(amount, account) { logger.info(" Balance before withdrawal: {}", account.balance); diff --git a/spring-aop/src/main/java/org/baeldung/aspectj/Secured.java b/spring-aop/src/main/java/com/baeldung/aspectj/Secured.java similarity index 90% rename from spring-aop/src/main/java/org/baeldung/aspectj/Secured.java rename to spring-aop/src/main/java/com/baeldung/aspectj/Secured.java index 08711d5db1..923f208c2f 100644 --- a/spring-aop/src/main/java/org/baeldung/aspectj/Secured.java +++ b/spring-aop/src/main/java/com/baeldung/aspectj/Secured.java @@ -1,4 +1,4 @@ -package org.baeldung.aspectj; +package com.baeldung.aspectj; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-aop/src/main/java/org/baeldung/aspectj/SecuredMethod.java b/spring-aop/src/main/java/com/baeldung/aspectj/SecuredMethod.java similarity index 94% rename from spring-aop/src/main/java/org/baeldung/aspectj/SecuredMethod.java rename to spring-aop/src/main/java/com/baeldung/aspectj/SecuredMethod.java index d1f7d43738..aa4b733a00 100644 --- a/spring-aop/src/main/java/org/baeldung/aspectj/SecuredMethod.java +++ b/spring-aop/src/main/java/com/baeldung/aspectj/SecuredMethod.java @@ -1,4 +1,4 @@ -package org.baeldung.aspectj; +package com.baeldung.aspectj; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-aop/src/main/java/org/baeldung/aspectj/SecuredMethodAspect.java b/spring-aop/src/main/java/com/baeldung/aspectj/SecuredMethodAspect.java similarity index 96% rename from spring-aop/src/main/java/org/baeldung/aspectj/SecuredMethodAspect.java rename to spring-aop/src/main/java/com/baeldung/aspectj/SecuredMethodAspect.java index b474f266ab..9ea45ec43b 100644 --- a/spring-aop/src/main/java/org/baeldung/aspectj/SecuredMethodAspect.java +++ b/spring-aop/src/main/java/com/baeldung/aspectj/SecuredMethodAspect.java @@ -1,4 +1,4 @@ -package org.baeldung.aspectj; +package com.baeldung.aspectj; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; diff --git a/spring-aop/src/main/java/org/baeldung/logger/AdderAfterAspect.java b/spring-aop/src/main/java/com/baeldung/logger/AdderAfterAspect.java similarity index 86% rename from spring-aop/src/main/java/org/baeldung/logger/AdderAfterAspect.java rename to spring-aop/src/main/java/com/baeldung/logger/AdderAfterAspect.java index 59afa38f06..658eb8a726 100644 --- a/spring-aop/src/main/java/org/baeldung/logger/AdderAfterAspect.java +++ b/spring-aop/src/main/java/com/baeldung/logger/AdderAfterAspect.java @@ -1,13 +1,13 @@ -package org.baeldung.logger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AdderAfterAspect { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public void afterAdvice() throws Throwable { - logger.info("I'm done calling the method"); - } -} +package com.baeldung.logger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AdderAfterAspect { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public void afterAdvice() throws Throwable { + logger.info("I'm done calling the method"); + } +} diff --git a/spring-aop/src/main/java/org/baeldung/logger/AdderAfterReturnAspect.java b/spring-aop/src/main/java/com/baeldung/logger/AdderAfterReturnAspect.java similarity index 88% rename from spring-aop/src/main/java/org/baeldung/logger/AdderAfterReturnAspect.java rename to spring-aop/src/main/java/com/baeldung/logger/AdderAfterReturnAspect.java index a2b1959374..faec9547aa 100644 --- a/spring-aop/src/main/java/org/baeldung/logger/AdderAfterReturnAspect.java +++ b/spring-aop/src/main/java/com/baeldung/logger/AdderAfterReturnAspect.java @@ -1,13 +1,13 @@ -package org.baeldung.logger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AdderAfterReturnAspect { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public void afterReturn(final Object returnValue) throws Throwable { - logger.info("value return was {}", returnValue); - } -} +package com.baeldung.logger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AdderAfterReturnAspect { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public void afterReturn(final Object returnValue) throws Throwable { + logger.info("value return was {}", returnValue); + } +} diff --git a/spring-aop/src/main/java/org/baeldung/logger/AdderAfterThrowAspect.java b/spring-aop/src/main/java/com/baeldung/logger/AdderAfterThrowAspect.java similarity index 88% rename from spring-aop/src/main/java/org/baeldung/logger/AdderAfterThrowAspect.java rename to spring-aop/src/main/java/com/baeldung/logger/AdderAfterThrowAspect.java index 1f19af05e4..8637730b8a 100644 --- a/spring-aop/src/main/java/org/baeldung/logger/AdderAfterThrowAspect.java +++ b/spring-aop/src/main/java/com/baeldung/logger/AdderAfterThrowAspect.java @@ -1,13 +1,13 @@ -package org.baeldung.logger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AdderAfterThrowAspect { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public void afterThrow(final Exception exception) throws Throwable { - logger.info("Exception thrown was {}", exception.getMessage()); - } -} +package com.baeldung.logger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AdderAfterThrowAspect { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public void afterThrow(final Exception exception) throws Throwable { + logger.info("Exception thrown was {}", exception.getMessage()); + } +} diff --git a/spring-aop/src/main/java/org/baeldung/logger/AdderAroundAspect.java b/spring-aop/src/main/java/com/baeldung/logger/AdderAroundAspect.java similarity index 92% rename from spring-aop/src/main/java/org/baeldung/logger/AdderAroundAspect.java rename to spring-aop/src/main/java/com/baeldung/logger/AdderAroundAspect.java index fceba87d15..1524576085 100644 --- a/spring-aop/src/main/java/org/baeldung/logger/AdderAroundAspect.java +++ b/spring-aop/src/main/java/com/baeldung/logger/AdderAroundAspect.java @@ -1,18 +1,18 @@ -package org.baeldung.logger; - -import java.util.Arrays; -import org.aspectj.lang.ProceedingJoinPoint; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AdderAroundAspect { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public Object aroundAdvice(final ProceedingJoinPoint joinPoint) throws Throwable { - logger.info("Arguments passed to method are: " + Arrays.toString(joinPoint.getArgs())); - final Object result = joinPoint.proceed(); - logger.info("Result from method is: " + result); - return result; - } -} +package com.baeldung.logger; + +import java.util.Arrays; +import org.aspectj.lang.ProceedingJoinPoint; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AdderAroundAspect { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public Object aroundAdvice(final ProceedingJoinPoint joinPoint) throws Throwable { + logger.info("Arguments passed to method are: " + Arrays.toString(joinPoint.getArgs())); + final Object result = joinPoint.proceed(); + logger.info("Result from method is: " + result); + return result; + } +} diff --git a/spring-aop/src/main/java/org/baeldung/logger/AdderBeforeAspect.java b/spring-aop/src/main/java/com/baeldung/logger/AdderBeforeAspect.java similarity index 87% rename from spring-aop/src/main/java/org/baeldung/logger/AdderBeforeAspect.java rename to spring-aop/src/main/java/com/baeldung/logger/AdderBeforeAspect.java index 750e7ba122..0d30622088 100644 --- a/spring-aop/src/main/java/org/baeldung/logger/AdderBeforeAspect.java +++ b/spring-aop/src/main/java/com/baeldung/logger/AdderBeforeAspect.java @@ -1,13 +1,13 @@ -package org.baeldung.logger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AdderBeforeAspect { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public void beforeAdvice() throws Throwable { - logger.info("I would be executed just before method starts"); - } -} +package com.baeldung.logger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AdderBeforeAspect { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public void beforeAdvice() throws Throwable { + logger.info("I would be executed just before method starts"); + } +} diff --git a/spring-aop/src/main/java/org/baeldung/logger/SampleAdder.java b/spring-aop/src/main/java/com/baeldung/logger/SampleAdder.java similarity index 85% rename from spring-aop/src/main/java/org/baeldung/logger/SampleAdder.java rename to spring-aop/src/main/java/com/baeldung/logger/SampleAdder.java index 96fda1b0b9..0ef13ca7f0 100644 --- a/spring-aop/src/main/java/org/baeldung/logger/SampleAdder.java +++ b/spring-aop/src/main/java/com/baeldung/logger/SampleAdder.java @@ -1,12 +1,12 @@ -package org.baeldung.logger; - -public class SampleAdder { - - public int add(int a, int b) { - if (a < 0 || b < 0) { - throw new IllegalArgumentException("Make sure all the arguments are greater than zero."); - } - return a + b; - } - -} +package com.baeldung.logger; + +public class SampleAdder { + + public int add(int a, int b) { + if (a < 0 || b < 0) { + throw new IllegalArgumentException("Make sure all the arguments are greater than zero."); + } + return a + b; + } + +} diff --git a/spring-aop/src/main/java/org/baeldung/performancemonitor/AopConfiguration.java b/spring-aop/src/main/java/com/baeldung/performancemonitor/AopConfiguration.java similarity index 85% rename from spring-aop/src/main/java/org/baeldung/performancemonitor/AopConfiguration.java rename to spring-aop/src/main/java/com/baeldung/performancemonitor/AopConfiguration.java index 00026baf07..3df14e2f45 100644 --- a/spring-aop/src/main/java/org/baeldung/performancemonitor/AopConfiguration.java +++ b/spring-aop/src/main/java/com/baeldung/performancemonitor/AopConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.performancemonitor; +package com.baeldung.performancemonitor; import org.aspectj.lang.annotation.Pointcut; import org.springframework.aop.Advisor; @@ -16,10 +16,10 @@ import java.time.Month; @EnableAspectJAutoProxy public class AopConfiguration { - @Pointcut("execution(public String org.baeldung.performancemonitor.PersonService.getFullName(..))") + @Pointcut("execution(public String com.baeldung.performancemonitor.PersonService.getFullName(..))") public void monitor() { } - @Pointcut("execution(public int org.baeldung.performancemonitor.PersonService.getAge(..))") + @Pointcut("execution(public int com.baeldung.performancemonitor.PersonService.getAge(..))") public void myMonitor() { } @Bean @@ -30,7 +30,7 @@ public class AopConfiguration { @Bean public Advisor performanceMonitorAdvisor() { AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); - pointcut.setExpression("org.baeldung.performancemonitor.AopConfiguration.monitor()"); + pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.monitor()"); return new DefaultPointcutAdvisor(pointcut, performanceMonitorInterceptor()); } @@ -52,7 +52,7 @@ public class AopConfiguration { @Bean public Advisor myPerformanceMonitorAdvisor() { AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); - pointcut.setExpression("org.baeldung.performancemonitor.AopConfiguration.myMonitor()"); + pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.myMonitor()"); return new DefaultPointcutAdvisor(pointcut, myPerformanceMonitorInterceptor()); } diff --git a/spring-aop/src/main/java/org/baeldung/performancemonitor/MyPerformanceMonitorInterceptor.java b/spring-aop/src/main/java/com/baeldung/performancemonitor/MyPerformanceMonitorInterceptor.java similarity index 96% rename from spring-aop/src/main/java/org/baeldung/performancemonitor/MyPerformanceMonitorInterceptor.java rename to spring-aop/src/main/java/com/baeldung/performancemonitor/MyPerformanceMonitorInterceptor.java index d098d9466c..dfc6606c6a 100644 --- a/spring-aop/src/main/java/org/baeldung/performancemonitor/MyPerformanceMonitorInterceptor.java +++ b/spring-aop/src/main/java/com/baeldung/performancemonitor/MyPerformanceMonitorInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.performancemonitor; +package com.baeldung.performancemonitor; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; diff --git a/spring-aop/src/main/java/org/baeldung/performancemonitor/PerfomanceApp.java b/spring-aop/src/main/java/com/baeldung/performancemonitor/PerfomanceApp.java similarity index 93% rename from spring-aop/src/main/java/org/baeldung/performancemonitor/PerfomanceApp.java rename to spring-aop/src/main/java/com/baeldung/performancemonitor/PerfomanceApp.java index d0fb3a5393..00268c978e 100644 --- a/spring-aop/src/main/java/org/baeldung/performancemonitor/PerfomanceApp.java +++ b/spring-aop/src/main/java/com/baeldung/performancemonitor/PerfomanceApp.java @@ -1,4 +1,4 @@ -package org.baeldung.performancemonitor; +package com.baeldung.performancemonitor; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; diff --git a/spring-aop/src/main/java/com/baeldung/performancemonitor/Person.java b/spring-aop/src/main/java/com/baeldung/performancemonitor/Person.java new file mode 100644 index 0000000000..f16f28fdef --- /dev/null +++ b/spring-aop/src/main/java/com/baeldung/performancemonitor/Person.java @@ -0,0 +1,42 @@ +package com.baeldung.performancemonitor; + +import java.time.LocalDate; + +public class Person { + private String lastName; + private String firstName; + private LocalDate dateOfBirth; + + public Person() { + } + + public Person(String firstName, String lastName, LocalDate dateOfBirth) { + this.firstName = firstName; + this.lastName = lastName; + this.dateOfBirth = dateOfBirth; + } + + public LocalDate getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(LocalDate dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } +} diff --git a/spring-aop/src/main/java/com/baeldung/performancemonitor/PersonService.java b/spring-aop/src/main/java/com/baeldung/performancemonitor/PersonService.java new file mode 100644 index 0000000000..f5bfdddc12 --- /dev/null +++ b/spring-aop/src/main/java/com/baeldung/performancemonitor/PersonService.java @@ -0,0 +1,17 @@ +package com.baeldung.performancemonitor; + +import java.time.LocalDate; +import java.time.Period; + +public class PersonService { + + public String getFullName(Person person){ + return person.getLastName()+" "+person.getFirstName(); + } + + public int getAge(Person person){ + Period p = Period.between(person.getDateOfBirth(), LocalDate.now()); + return p.getYears(); + } + +} diff --git a/spring-aop/src/main/java/com/baeldung/pointcutadvice/Foo.java b/spring-aop/src/main/java/com/baeldung/pointcutadvice/Foo.java new file mode 100644 index 0000000000..b20c9a3ccf --- /dev/null +++ b/spring-aop/src/main/java/com/baeldung/pointcutadvice/Foo.java @@ -0,0 +1,19 @@ +package com.baeldung.pointcutadvice; + +import com.baeldung.pointcutadvice.annotations.Entity; + +@Entity +public class Foo { + private Long id; + private String name; + + public Foo(Long id, String name) { + this.id = id; + this.name = name; + } + + @Override + public String toString() { + return "Foo{" + "id=" + id + ", name='" + name + '\'' + '}'; + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java b/spring-aop/src/main/java/com/baeldung/pointcutadvice/LoggingAspect.java similarity index 87% rename from spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java rename to spring-aop/src/main/java/com/baeldung/pointcutadvice/LoggingAspect.java index 169d664471..481e1d323a 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java +++ b/spring-aop/src/main/java/com/baeldung/pointcutadvice/LoggingAspect.java @@ -1,4 +1,4 @@ -package com.baeldung.aop; +package com.baeldung.pointcutadvice; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; @@ -23,15 +23,15 @@ public class LoggingAspect { } }; - @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.*(..))") + @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.pointcutadvice.dao.FooDao.*(..))") public void repositoryMethods() { } - @Pointcut("within(com.baeldung..*) && @annotation(com.baeldung.aop.annotations.Loggable)") + @Pointcut("within(com.baeldung..*) && @annotation(com.baeldung.pointcutadvice.annotations.Loggable)") public void loggableMethods() { } - @Pointcut("within(com.baeldung..*) && @args(com.baeldung.aop.annotations.Entity)") + @Pointcut("within(com.baeldung..*) && @args(com.baeldung.pointcutadvice.annotations.Entity)") public void methodsAcceptingEntities() { } diff --git a/spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java b/spring-aop/src/main/java/com/baeldung/pointcutadvice/PerformanceAspect.java similarity index 93% rename from spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java rename to spring-aop/src/main/java/com/baeldung/pointcutadvice/PerformanceAspect.java index 8f374cc1e5..4f445e301e 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java +++ b/spring-aop/src/main/java/com/baeldung/pointcutadvice/PerformanceAspect.java @@ -1,4 +1,4 @@ -package com.baeldung.aop; +package com.baeldung.pointcutadvice; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; @@ -15,7 +15,7 @@ public class PerformanceAspect { private static Logger logger = Logger.getLogger(PerformanceAspect.class.getName()); - @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.*(..))") + @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.pointcutadvice.dao.FooDao.*(..))") public void repositoryClassMethods() { } diff --git a/spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java b/spring-aop/src/main/java/com/baeldung/pointcutadvice/PublishingAspect.java similarity index 86% rename from spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java rename to spring-aop/src/main/java/com/baeldung/pointcutadvice/PublishingAspect.java index a45402dc18..bb96e08772 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java +++ b/spring-aop/src/main/java/com/baeldung/pointcutadvice/PublishingAspect.java @@ -1,6 +1,6 @@ -package com.baeldung.aop; +package com.baeldung.pointcutadvice; -import com.baeldung.events.FooCreationEvent; +import com.baeldung.pointcutadvice.events.FooCreationEvent; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; @@ -20,11 +20,11 @@ public class PublishingAspect { this.eventPublisher = eventPublisher; } - @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.*(..))") + @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.pointcutadvice.dao.FooDao.*(..))") public void repositoryMethods() { } - @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.create*(Long,..))") + @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.pointcutadvice.dao.FooDao.create*(Long,..))") public void firstLongParamMethods() { } diff --git a/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Entity.java b/spring-aop/src/main/java/com/baeldung/pointcutadvice/annotations/Entity.java similarity index 83% rename from spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Entity.java rename to spring-aop/src/main/java/com/baeldung/pointcutadvice/annotations/Entity.java index 61d91b0777..e6753cdd61 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Entity.java +++ b/spring-aop/src/main/java/com/baeldung/pointcutadvice/annotations/Entity.java @@ -1,4 +1,4 @@ -package com.baeldung.aop.annotations; +package com.baeldung.pointcutadvice.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Loggable.java b/spring-aop/src/main/java/com/baeldung/pointcutadvice/annotations/Loggable.java similarity index 84% rename from spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Loggable.java rename to spring-aop/src/main/java/com/baeldung/pointcutadvice/annotations/Loggable.java index 92aa950e58..921003be63 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Loggable.java +++ b/spring-aop/src/main/java/com/baeldung/pointcutadvice/annotations/Loggable.java @@ -1,4 +1,4 @@ -package com.baeldung.aop.annotations; +package com.baeldung.pointcutadvice.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-aop/src/main/java/com/baeldung/pointcutadvice/dao/FooDao.java b/spring-aop/src/main/java/com/baeldung/pointcutadvice/dao/FooDao.java new file mode 100644 index 0000000000..72a9762991 --- /dev/null +++ b/spring-aop/src/main/java/com/baeldung/pointcutadvice/dao/FooDao.java @@ -0,0 +1,22 @@ +package com.baeldung.pointcutadvice.dao; + +import com.baeldung.pointcutadvice.Foo; +import com.baeldung.pointcutadvice.annotations.Loggable; +import org.springframework.stereotype.Repository; + +@Repository +public class FooDao { + + public String findById(Long id) { + return "Bazz"; + } + + @Loggable + public Foo create(Long id, String name) { + return new Foo(id, name); + } + + public Foo merge(Foo foo) { + return foo; + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEvent.java b/spring-aop/src/main/java/com/baeldung/pointcutadvice/events/FooCreationEvent.java similarity index 81% rename from spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEvent.java rename to spring-aop/src/main/java/com/baeldung/pointcutadvice/events/FooCreationEvent.java index 5ea4b46c04..8cee80fa0c 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEvent.java +++ b/spring-aop/src/main/java/com/baeldung/pointcutadvice/events/FooCreationEvent.java @@ -1,4 +1,4 @@ -package com.baeldung.events; +package com.baeldung.pointcutadvice.events; import org.springframework.context.ApplicationEvent; diff --git a/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEventListener.java b/spring-aop/src/main/java/com/baeldung/pointcutadvice/events/FooCreationEventListener.java similarity index 91% rename from spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEventListener.java rename to spring-aop/src/main/java/com/baeldung/pointcutadvice/events/FooCreationEventListener.java index c0aa744bc1..4a55b2138d 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEventListener.java +++ b/spring-aop/src/main/java/com/baeldung/pointcutadvice/events/FooCreationEventListener.java @@ -1,4 +1,4 @@ -package com.baeldung.events; +package com.baeldung.pointcutadvice.events; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; diff --git a/spring-aop/src/main/java/org/baeldung/Application.java b/spring-aop/src/main/java/org/baeldung/Application.java deleted file mode 100644 index e5c764ef7e..0000000000 --- a/spring-aop/src/main/java/org/baeldung/Application.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Application { - - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/spring-aop/src/main/java/org/baeldung/Service.java b/spring-aop/src/main/java/org/baeldung/Service.java deleted file mode 100644 index e4bee38438..0000000000 --- a/spring-aop/src/main/java/org/baeldung/Service.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung; - -import org.springframework.stereotype.Component; - -@Component -public class Service { - - @LogExecutionTime - public void serve() throws InterruptedException { - Thread.sleep(2000); - } -} diff --git a/spring-aop/src/main/java/org/baeldung/aspectj/Account.java b/spring-aop/src/main/java/org/baeldung/aspectj/Account.java deleted file mode 100644 index 2c551116f4..0000000000 --- a/spring-aop/src/main/java/org/baeldung/aspectj/Account.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.aspectj; - -public class Account { - int balance = 20; - - public boolean withdraw(int amount) { - if (balance < amount) { - return false; - } - balance = balance - amount; - return true; - } -} diff --git a/spring-aop/src/main/java/org/baeldung/performancemonitor/Person.java b/spring-aop/src/main/java/org/baeldung/performancemonitor/Person.java deleted file mode 100644 index abd2465764..0000000000 --- a/spring-aop/src/main/java/org/baeldung/performancemonitor/Person.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.performancemonitor; - -import java.time.LocalDate; - -public class Person { - private String lastName; - private String firstName; - private LocalDate dateOfBirth; - - public Person() { - } - - public Person(String firstName, String lastName, LocalDate dateOfBirth) { - this.firstName = firstName; - this.lastName = lastName; - this.dateOfBirth = dateOfBirth; - } - - public LocalDate getDateOfBirth() { - return dateOfBirth; - } - - public void setDateOfBirth(LocalDate dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } -} diff --git a/spring-aop/src/main/java/org/baeldung/performancemonitor/PersonService.java b/spring-aop/src/main/java/org/baeldung/performancemonitor/PersonService.java deleted file mode 100644 index 5b98aaf436..0000000000 --- a/spring-aop/src/main/java/org/baeldung/performancemonitor/PersonService.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.performancemonitor; - -import java.time.LocalDate; -import java.time.Period; - -public class PersonService { - - public String getFullName(Person person){ - return person.getLastName()+" "+person.getFirstName(); - } - - public int getAge(Person person){ - Period p = Period.between(person.getDateOfBirth(), LocalDate.now()); - return p.getYears(); - } - -} diff --git a/spring-aop/src/main/resources/META-INF/aop.xml b/spring-aop/src/main/resources/META-INF/aop.xml index e5bddcc30c..f930cde942 100644 --- a/spring-aop/src/main/resources/META-INF/aop.xml +++ b/spring-aop/src/main/resources/META-INF/aop.xml @@ -1,6 +1,6 @@ - + diff --git a/spring-aop/src/main/resources/org.baeldung.logger/springAop-applicationContext.xml b/spring-aop/src/main/resources/com.baeldung.logger/springAop-applicationContext.xml similarity index 75% rename from spring-aop/src/main/resources/org.baeldung.logger/springAop-applicationContext.xml rename to spring-aop/src/main/resources/com.baeldung.logger/springAop-applicationContext.xml index 058beaa7a1..595e7e46e6 100644 --- a/spring-aop/src/main/resources/org.baeldung.logger/springAop-applicationContext.xml +++ b/spring-aop/src/main/resources/com.baeldung.logger/springAop-applicationContext.xml @@ -1,54 +1,54 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-aop/src/main/resources/logback.xml b/spring-aop/src/main/resources/logback.xml index 7c15f603a0..4eaa556705 100644 --- a/spring-aop/src/main/resources/logback.xml +++ b/spring-aop/src/main/resources/logback.xml @@ -13,7 +13,7 @@ - + diff --git a/spring-mvc-java/src/main/resources/com/baeldung/aop/beans.xml b/spring-aop/src/main/resources/pointcutadvice/beans.xml similarity index 82% rename from spring-mvc-java/src/main/resources/com/baeldung/aop/beans.xml rename to spring-aop/src/main/resources/pointcutadvice/beans.xml index e6aa9d77c4..ad96827a13 100644 --- a/spring-mvc-java/src/main/resources/com/baeldung/aop/beans.xml +++ b/spring-aop/src/main/resources/pointcutadvice/beans.xml @@ -7,8 +7,8 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"> - - + + diff --git a/spring-aop/src/test/java/org/baeldung/CustomAnnotationIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/CustomAnnotationIntegrationTest.java similarity index 95% rename from spring-aop/src/test/java/org/baeldung/CustomAnnotationIntegrationTest.java rename to spring-aop/src/test/java/com/baeldung/CustomAnnotationIntegrationTest.java index b109e3a39e..155f8e1c96 100644 --- a/spring-aop/src/test/java/org/baeldung/CustomAnnotationIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/CustomAnnotationIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-aop/src/test/java/com/baeldung/SpringContextTest.java b/spring-aop/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..13c1c162f1 --- /dev/null +++ b/spring-aop/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +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(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-aop/src/test/java/org/baeldung/aspectj/AccountUnitTest.java b/spring-aop/src/test/java/com/baeldung/aspectj/AccountUnitTest.java similarity index 94% rename from spring-aop/src/test/java/org/baeldung/aspectj/AccountUnitTest.java rename to spring-aop/src/test/java/com/baeldung/aspectj/AccountUnitTest.java index 3d5384a7f7..3af1f963da 100644 --- a/spring-aop/src/test/java/org/baeldung/aspectj/AccountUnitTest.java +++ b/spring-aop/src/test/java/com/baeldung/aspectj/AccountUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.aspectj; +package com.baeldung.aspectj; import org.junit.Before; import org.junit.Test; diff --git a/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java b/spring-aop/src/test/java/com/baeldung/aspectj/SecuredMethodUnitTest.java similarity index 88% rename from spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java rename to spring-aop/src/test/java/com/baeldung/aspectj/SecuredMethodUnitTest.java index cbdb2db057..e1a2553610 100644 --- a/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java +++ b/spring-aop/src/test/java/com/baeldung/aspectj/SecuredMethodUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.aspectj; +package com.baeldung.aspectj; import org.junit.Test; diff --git a/spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/logger/CalculatorIntegrationTest.java similarity index 93% rename from spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java rename to spring-aop/src/test/java/com/baeldung/logger/CalculatorIntegrationTest.java index 8c31b7f892..66e06f7928 100644 --- a/spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/logger/CalculatorIntegrationTest.java @@ -1,29 +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); - } - -} +package com.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-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopLoggingIntegrationTest.java similarity index 91% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java rename to spring-aop/src/test/java/com/baeldung/pointcutadvice/AopLoggingIntegrationTest.java index 698bae4c0f..a687eec388 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopLoggingIntegrationTest.java @@ -1,8 +1,7 @@ -package com.baeldung.aop; +package com.baeldung.pointcutadvice; -import com.baeldung.config.TestConfig; -import com.baeldung.dao.FooDao; -import com.baeldung.model.Foo; +import com.baeldung.Application; +import com.baeldung.pointcutadvice.dao.FooDao; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -24,7 +23,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class) public class AopLoggingIntegrationTest { @Before diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPerformanceIntegrationTest.java similarity index 89% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java rename to spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPerformanceIntegrationTest.java index c9ab2fb4bb..5a7797e5cd 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPerformanceIntegrationTest.java @@ -1,7 +1,7 @@ -package com.baeldung.aop; +package com.baeldung.pointcutadvice; -import com.baeldung.config.TestConfig; -import com.baeldung.dao.FooDao; +import com.baeldung.Application; +import com.baeldung.pointcutadvice.dao.FooDao; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -23,7 +23,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class) public class AopPerformanceIntegrationTest { @Before diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPublishingIntegrationTest.java similarity index 85% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java rename to spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPublishingIntegrationTest.java index 2503900e69..996b56d61e 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPublishingIntegrationTest.java @@ -1,9 +1,8 @@ -package com.baeldung.aop; +package com.baeldung.pointcutadvice; -import com.baeldung.config.TestConfig; -import com.baeldung.dao.FooDao; -import com.baeldung.events.FooCreationEventListener; -import com.baeldung.model.Foo; +import com.baeldung.Application; +import com.baeldung.pointcutadvice.dao.FooDao; +import com.baeldung.pointcutadvice.events.FooCreationEventListener; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -22,7 +21,7 @@ import java.util.regex.Pattern; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class) public class AopPublishingIntegrationTest { @Before diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopXmlConfigPerformanceIntegrationTest.java similarity index 93% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java rename to spring-aop/src/test/java/com/baeldung/pointcutadvice/AopXmlConfigPerformanceIntegrationTest.java index 3b380315e8..5727cfd7bc 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopXmlConfigPerformanceIntegrationTest.java @@ -1,6 +1,6 @@ -package com.baeldung.aop; +package com.baeldung.pointcutadvice; -import com.baeldung.dao.FooDao; +import com.baeldung.pointcutadvice.dao.FooDao; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,7 +21,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("/com/baeldung/aop/beans.xml") +@ContextConfiguration("/pointcutadvice/beans.xml") public class AopXmlConfigPerformanceIntegrationTest { @Before diff --git a/spring-aop/src/test/java/org/baeldung/SpringContextTest.java b/spring-aop/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 4d3ed953c4..0000000000 --- a/spring-aop/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.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(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-aop/src/test/resources/springAop-applicationContext.xml b/spring-aop/src/test/resources/springAop-applicationContext.xml index 4d88bd3711..fb71052567 100644 --- a/spring-aop/src/test/resources/springAop-applicationContext.xml +++ b/spring-aop/src/test/resources/springAop-applicationContext.xml @@ -6,45 +6,45 @@ xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"> + class="com.baeldung.logger.SampleAdder" /> - - - - - + + + + + + expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" /> + expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" /> + expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" /> + expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" /> + expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" /> diff --git a/spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java b/spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..14e7de2095 --- /dev/null +++ b/spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.junit.Test; + +import com.baeldung.camel.main.App; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 1c098a56ab..0000000000 --- a/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung; - -import org.junit.Test; - -import com.baeldung.camel.main.App; - -public class SpringContextTest { - - @Test - public final void testMain() throws Exception { - App.main(null); - } -} diff --git a/spring-batch/README.md b/spring-batch/README.md index 99ac9826bc..3a89459629 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -3,9 +3,12 @@ This module contains articles about Spring Batch ### Relevant Articles: + - [Introduction to Spring Batch](https://www.baeldung.com/introduction-to-spring-batch) - [Spring Batch using Partitioner](https://www.baeldung.com/spring-batch-partitioner) - [Spring Batch – Tasklets vs Chunks](https://www.baeldung.com/spring-batch-tasklet-chunk) - [How to Trigger and Stop a Scheduled Spring Batch Job](https://www.baeldung.com/spring-batch-start-stop-job) - [Configuring Skip Logic in Spring Batch](https://www.baeldung.com/spring-batch-skip-logic) - [Testing a Spring Batch Job](https://www.baeldung.com/spring-batch-testing-job) +- [Configuring Retry Logic in Spring Batch](https://www.baeldung.com/spring-batch-retry-logic) +- [Conditional Flow in Spring Batch](https://www.baeldung.com/spring-batch-conditional-flow) diff --git a/spring-batch/repository.sqlite b/spring-batch/repository.sqlite index 4456ef63cc..2b549352ec 100644 Binary files a/spring-batch/repository.sqlite and b/spring-batch/repository.sqlite differ diff --git a/spring-batch/src/main/java/com/baeldung/batch/App.java b/spring-batch/src/main/java/com/baeldung/batch/App.java new file mode 100644 index 0000000000..0f888a77b3 --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/batch/App.java @@ -0,0 +1,51 @@ +package com.baeldung.batch; + +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.JobParameters; +import org.springframework.batch.core.JobParametersBuilder; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + public static void main(final String[] args) { + // Spring Java config + final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.register(SpringConfig.class); + context.register(SpringBatchConfig.class); + context.register(SpringBatchRetryConfig.class); + + context.refresh(); + + // Spring xml config + // ApplicationContext context = new ClassPathXmlApplicationContext("spring-batch.xml"); + + runJob(context, "firstBatchJob"); + runJob(context, "skippingBatchJob"); + runJob(context, "skipPolicyBatchJob"); + runJob(context, "retryBatchJob"); + + } + + private static void runJob(AnnotationConfigApplicationContext context, String batchJobName) { + final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); + final Job job = (Job) context.getBean(batchJobName); + + LOGGER.info("Starting the batch job: {}", batchJobName); + try { + // To enable multiple execution of a job with the same parameters + JobParameters jobParameters = new JobParametersBuilder().addString("jobID", String.valueOf(System.currentTimeMillis())) + .toJobParameters(); + final JobExecution execution = jobLauncher.run(job, jobParameters); + LOGGER.info("Job Status : {}", execution.getStatus()); + } catch (final Exception e) { + e.printStackTrace(); + LOGGER.error("Job failed {}", e.getMessage()); + } + } +} \ No newline at end of file diff --git a/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java b/spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java similarity index 92% rename from spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java rename to spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java index 07dd65bcfd..e1c52e1582 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java +++ b/spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java @@ -1,12 +1,12 @@ -package org.baeldung.batch; +package com.baeldung.batch; -import org.baeldung.batch.model.Transaction; -import org.baeldung.batch.service.CustomItemProcessor; -import org.baeldung.batch.service.CustomSkipPolicy; -import org.baeldung.batch.service.MissingUsernameException; -import org.baeldung.batch.service.NegativeAmountException; -import org.baeldung.batch.service.RecordFieldSetMapper; -import org.baeldung.batch.service.SkippingItemProcessor; +import com.baeldung.batch.model.Transaction; +import com.baeldung.batch.service.CustomItemProcessor; +import com.baeldung.batch.service.CustomSkipPolicy; +import com.baeldung.batch.service.MissingUsernameException; +import com.baeldung.batch.service.NegativeAmountException; +import com.baeldung.batch.service.RecordFieldSetMapper; +import com.baeldung.batch.service.SkippingItemProcessor; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; diff --git a/spring-batch/src/main/java/com/baeldung/batch/SpringBatchRetryConfig.java b/spring-batch/src/main/java/com/baeldung/batch/SpringBatchRetryConfig.java new file mode 100644 index 0000000000..a329df3016 --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/batch/SpringBatchRetryConfig.java @@ -0,0 +1,117 @@ +package com.baeldung.batch; + +import org.apache.http.client.config.RequestConfig; +import org.apache.http.conn.ConnectTimeoutException; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import com.baeldung.batch.model.Transaction; +import com.baeldung.batch.service.RecordFieldSetMapper; +import com.baeldung.batch.service.RetryItemProcessor; +import org.springframework.batch.core.Job; +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.item.ItemProcessor; +import org.springframework.batch.item.ItemReader; +import org.springframework.batch.item.ItemWriter; +import org.springframework.batch.item.file.FlatFileItemReader; +import org.springframework.batch.item.file.mapping.DefaultLineMapper; +import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; +import org.springframework.batch.item.xml.StaxEventItemWriter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.Resource; +import org.springframework.dao.DeadlockLoserDataAccessException; +import org.springframework.oxm.Marshaller; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; + +import java.text.ParseException; + +@Configuration +@EnableBatchProcessing +public class SpringBatchRetryConfig { + + private static final String[] tokens = { "username", "userid", "transactiondate", "amount" }; + private static final int TWO_SECONDS = 2000; + + @Autowired + private JobBuilderFactory jobBuilderFactory; + + @Autowired + private StepBuilderFactory stepBuilderFactory; + + @Value("input/recordRetry.csv") + private Resource inputCsv; + + @Value("file:xml/retryOutput.xml") + private Resource outputXml; + + public ItemReader itemReader(Resource inputData) throws ParseException { + DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); + tokenizer.setNames(tokens); + DefaultLineMapper lineMapper = new DefaultLineMapper<>(); + lineMapper.setLineTokenizer(tokenizer); + lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); + FlatFileItemReader reader = new FlatFileItemReader<>(); + reader.setResource(inputData); + reader.setLinesToSkip(1); + reader.setLineMapper(lineMapper); + return reader; + } + + @Bean + public CloseableHttpClient closeableHttpClient() { + final RequestConfig config = RequestConfig.custom() + .setConnectTimeout(TWO_SECONDS) + .build(); + return HttpClientBuilder.create().setDefaultRequestConfig(config).build(); + } + + @Bean + public ItemProcessor retryItemProcessor() { + return new RetryItemProcessor(); + } + + @Bean + public ItemWriter itemWriter(Marshaller marshaller) { + StaxEventItemWriter itemWriter = new StaxEventItemWriter<>(); + itemWriter.setMarshaller(marshaller); + itemWriter.setRootTagName("transactionRecord"); + itemWriter.setResource(outputXml); + return itemWriter; + } + + @Bean + public Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + marshaller.setClassesToBeBound(Transaction.class); + return marshaller; + } + + @Bean + public Step retryStep(@Qualifier("retryItemProcessor") ItemProcessor processor, + ItemWriter writer) throws ParseException { + return stepBuilderFactory.get("retryStep") + .chunk(10) + .reader(itemReader(inputCsv)) + .processor(processor) + .writer(writer) + .faultTolerant() + .retryLimit(3) + .retry(ConnectTimeoutException.class) + .retry(DeadlockLoserDataAccessException.class) + .build(); + } + + @Bean(name = "retryBatchJob") + public Job retryJob(@Qualifier("retryStep") Step retryStep) { + return jobBuilderFactory + .get("retryBatchJob") + .start(retryStep) + .build(); + } +} diff --git a/spring-batch/src/main/java/com/baeldung/batch/SpringConfig.java b/spring-batch/src/main/java/com/baeldung/batch/SpringConfig.java new file mode 100644 index 0000000000..73a07482ce --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/batch/SpringConfig.java @@ -0,0 +1,78 @@ +package com.baeldung.batch; + +import java.net.MalformedURLException; + +import javax.sql.DataSource; + +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +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.JobRepositoryFactoryBean; +import org.springframework.batch.support.transaction.ResourcelessTransactionManager; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.init.DataSourceInitializer; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.transaction.PlatformTransactionManager; + +@Configuration +@EnableBatchProcessing +public class SpringConfig { + + @Value("org/springframework/batch/core/schema-drop-sqlite.sql") + private Resource dropReopsitoryTables; + + @Value("org/springframework/batch/core/schema-sqlite.sql") + private Resource dataReopsitorySchema; + + @Bean + public DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.sqlite.JDBC"); + dataSource.setUrl("jdbc:sqlite:repository.sqlite"); + return dataSource; + } + + @Bean + public DataSourceInitializer dataSourceInitializer(DataSource dataSource) throws MalformedURLException { + ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); + + databasePopulator.addScript(dropReopsitoryTables); + databasePopulator.addScript(dataReopsitorySchema); + databasePopulator.setIgnoreFailedDrops(true); + + DataSourceInitializer initializer = new DataSourceInitializer(); + initializer.setDataSource(dataSource); + initializer.setDatabasePopulator(databasePopulator); + + return initializer; + } + + private JobRepository getJobRepository() throws Exception { + JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); + factory.setDataSource(dataSource()); + factory.setTransactionManager(getTransactionManager()); + // JobRepositoryFactoryBean's methods Throws Generic Exception, + // it would have been better to have a specific one + factory.afterPropertiesSet(); + return (JobRepository) factory.getObject(); + } + + private PlatformTransactionManager getTransactionManager() { + return new ResourcelessTransactionManager(); + } + + public JobLauncher getJobLauncher() throws Exception { + SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); + // SimpleJobLauncher's methods Throws Generic Exception, + // it would have been better to have a specific one + jobLauncher.setJobRepository(getJobRepository()); + jobLauncher.afterPropertiesSet(); + return jobLauncher; + } + +} \ No newline at end of file diff --git a/spring-batch/src/main/java/com/baeldung/batch/model/Transaction.java b/spring-batch/src/main/java/com/baeldung/batch/model/Transaction.java new file mode 100644 index 0000000000..ffb6d59a79 --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/batch/model/Transaction.java @@ -0,0 +1,75 @@ +package com.baeldung.batch.model; + +import com.baeldung.batch.service.adapter.LocalDateTimeAdapter; + +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import java.time.LocalDateTime; + +@SuppressWarnings("restriction") +@XmlRootElement(name = "transactionRecord") +public class Transaction { + private String username; + private int userId; + private int age; + private String postCode; + private LocalDateTime transactionDate; + private double amount; + + /* getters and setters for the attributes */ + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + @XmlJavaTypeAdapter(LocalDateTimeAdapter.class) + public LocalDateTime getTransactionDate() { + return transactionDate; + } + + public void setTransactionDate(LocalDateTime transactionDate) { + this.transactionDate = transactionDate; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getPostCode() { + return postCode; + } + + public void setPostCode(String postCode) { + this.postCode = postCode; + } + + @Override + public String toString() { + return "Transaction [username=" + username + ", userId=" + userId + ", age=" + age + ", postCode=" + postCode + ", transactionDate=" + transactionDate + ", amount=" + amount + "]"; + } + +} diff --git a/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java b/spring-batch/src/main/java/com/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java similarity index 98% rename from spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java rename to spring-batch/src/main/java/com/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java index 667e013c35..4fade76ffc 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java +++ b/spring-batch/src/main/java/com/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.baeldung.batch.partitioner; +package com.baeldung.batch.partitioner; import java.util.HashMap; import java.util.Map; diff --git a/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionConfig.java similarity index 98% rename from spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java rename to spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionConfig.java index ad3aee4a2e..b08c95af53 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java +++ b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionConfig.java @@ -1,7 +1,7 @@ -package org.baeldung.batch.partitioner; +package com.baeldung.batch.partitioner; -import org.baeldung.batch.model.Transaction; -import org.baeldung.batch.service.RecordFieldSetMapper; +import com.baeldung.batch.model.Transaction; +import com.baeldung.batch.service.RecordFieldSetMapper; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; diff --git a/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionerApp.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java rename to spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionerApp.java index f456135058..e755e21ca9 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java +++ b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionerApp.java @@ -1,4 +1,4 @@ -package org.baeldung.batch.partitioner; +package com.baeldung.batch.partitioner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batch/service/CustomItemProcessor.java similarity index 76% rename from spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java rename to spring-batch/src/main/java/com/baeldung/batch/service/CustomItemProcessor.java index 8ca7892fec..5c5f78f861 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/CustomItemProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.batch.service; +package com.baeldung.batch.service; -import org.baeldung.batch.model.Transaction; +import com.baeldung.batch.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class CustomItemProcessor implements ItemProcessor { diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/CustomSkipPolicy.java b/spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/batch/service/CustomSkipPolicy.java rename to spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java index a156a65b6e..25401de022 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/CustomSkipPolicy.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java @@ -1,4 +1,4 @@ -package org.baeldung.batch.service; +package com.baeldung.batch.service; import org.springframework.batch.core.step.skip.SkipLimitExceededException; import org.springframework.batch.core.step.skip.SkipPolicy; diff --git a/spring-batch/src/main/java/com/baeldung/batch/service/MissingUsernameException.java b/spring-batch/src/main/java/com/baeldung/batch/service/MissingUsernameException.java new file mode 100644 index 0000000000..b12daa17cc --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/batch/service/MissingUsernameException.java @@ -0,0 +1,4 @@ +package com.baeldung.batch.service; + +public class MissingUsernameException extends RuntimeException { +} diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/NegativeAmountException.java b/spring-batch/src/main/java/com/baeldung/batch/service/NegativeAmountException.java similarity index 87% rename from spring-batch/src/main/java/org/baeldung/batch/service/NegativeAmountException.java rename to spring-batch/src/main/java/com/baeldung/batch/service/NegativeAmountException.java index c9c05be671..ee46574f87 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/NegativeAmountException.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/NegativeAmountException.java @@ -1,4 +1,4 @@ -package org.baeldung.batch.service; +package com.baeldung.batch.service; public class NegativeAmountException extends RuntimeException { diff --git a/spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java b/spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java new file mode 100644 index 0000000000..09478e9a30 --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java @@ -0,0 +1,33 @@ +package com.baeldung.batch.service; + +import com.baeldung.batch.model.Transaction; +import org.springframework.batch.item.file.mapping.FieldSetMapper; +import org.springframework.batch.item.file.transform.FieldSet; +import org.springframework.validation.BindException; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +public class RecordFieldSetMapper implements FieldSetMapper { + + public Transaction mapFieldSet(FieldSet fieldSet) throws BindException { + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyy"); + + Transaction transaction = new Transaction(); + // you can either use the indices or custom names + // I personally prefer the custom names easy for debugging and + // validating the pipelines + transaction.setUsername(fieldSet.readString("username")); + transaction.setUserId(fieldSet.readInt("userid")); + transaction.setAmount(fieldSet.readDouble(3)); + + // Converting the date + String dateString = fieldSet.readString(2); + transaction.setTransactionDate(LocalDate.parse(dateString, formatter).atStartOfDay()); + + return transaction; + + } + +} diff --git a/spring-batch/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java new file mode 100644 index 0000000000..c380e2c0ab --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java @@ -0,0 +1,42 @@ +package com.baeldung.batch.service; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.util.EntityUtils; +import com.baeldung.batch.model.Transaction; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.batch.item.ItemProcessor; +import org.springframework.beans.factory.annotation.Autowired; + +import java.io.IOException; + +public class RetryItemProcessor implements ItemProcessor { + + private static final Logger LOGGER = LoggerFactory.getLogger(RetryItemProcessor.class); + + @Autowired + private CloseableHttpClient closeableHttpClient; + + @Override + public Transaction process(Transaction transaction) throws IOException, JSONException { + LOGGER.info("Attempting to process user with id={}", transaction.getUserId()); + HttpResponse response = fetchMoreUserDetails(transaction.getUserId()); + + //parse user's age and postCode from response and update transaction + String result = EntityUtils.toString(response.getEntity()); + JSONObject userObject = new JSONObject(result); + transaction.setAge(Integer.parseInt(userObject.getString("age"))); + transaction.setPostCode(userObject.getString("postCode")); + + return transaction; + } + + private HttpResponse fetchMoreUserDetails(int id) throws IOException { + final HttpGet request = new HttpGet("http://www.baeldung.com:81/user/" + id); + return closeableHttpClient.execute(request); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/SkippingItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batch/service/SkippingItemProcessor.java similarity index 88% rename from spring-batch/src/main/java/org/baeldung/batch/service/SkippingItemProcessor.java rename to spring-batch/src/main/java/com/baeldung/batch/service/SkippingItemProcessor.java index 307a8213e2..ee37eb6c1b 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/SkippingItemProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/SkippingItemProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.batch.service; +package com.baeldung.batch.service; -import org.baeldung.batch.model.Transaction; +import com.baeldung.batch.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class SkippingItemProcessor implements ItemProcessor { diff --git a/spring-batch/src/main/java/com/baeldung/batch/service/adapter/LocalDateTimeAdapter.java b/spring-batch/src/main/java/com/baeldung/batch/service/adapter/LocalDateTimeAdapter.java new file mode 100644 index 0000000000..561a7335b3 --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/batch/service/adapter/LocalDateTimeAdapter.java @@ -0,0 +1,19 @@ +package com.baeldung.batch.service.adapter; + +import javax.xml.bind.annotation.adapters.XmlAdapter; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +public class LocalDateTimeAdapter extends XmlAdapter { + + private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT); + + public LocalDateTime unmarshal(String v) throws Exception { + return LocalDateTime.parse(v, DATE_TIME_FORMATTER); + } + + public String marshal(LocalDateTime v) throws Exception { + return DATE_TIME_FORMATTER.format(v); + } +} \ No newline at end of file diff --git a/spring-batch/src/main/java/org/baeldung/batchscheduler/SpringBatchScheduler.java b/spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java similarity index 98% rename from spring-batch/src/main/java/org/baeldung/batchscheduler/SpringBatchScheduler.java rename to spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java index 1beeb6b2bf..4de3e0a4b6 100644 --- a/spring-batch/src/main/java/org/baeldung/batchscheduler/SpringBatchScheduler.java +++ b/spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java @@ -1,4 +1,4 @@ -package org.baeldung.batchscheduler; +package com.baeldung.batchscheduler; import java.util.Date; import java.util.IdentityHashMap; @@ -7,7 +7,7 @@ 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 com.baeldung.batchscheduler.model.Book; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Job; diff --git a/spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java b/spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java new file mode 100644 index 0000000000..8ee986c729 --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java @@ -0,0 +1,35 @@ +package com.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/java/org/baeldung/batchtesting/SpringBatchApplication.java b/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchApplication.java similarity index 97% rename from spring-batch/src/main/java/org/baeldung/batchtesting/SpringBatchApplication.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchApplication.java index 39bfdfbee7..04185fb1ca 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/SpringBatchApplication.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.batchtesting; +package com.baeldung.batchtesting; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParametersBuilder; diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/SpringBatchConfiguration.java b/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java similarity index 92% rename from spring-batch/src/main/java/org/baeldung/batchtesting/SpringBatchConfiguration.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java index 2d891ad7da..664db3fbba 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/SpringBatchConfiguration.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java @@ -1,13 +1,13 @@ -package org.baeldung.batchtesting; +package com.baeldung.batchtesting; import java.io.IOException; -import org.baeldung.batchtesting.model.Book; -import org.baeldung.batchtesting.model.BookDetails; -import org.baeldung.batchtesting.model.BookRecord; -import org.baeldung.batchtesting.service.BookDetailsItemProcessor; -import org.baeldung.batchtesting.service.BookItemProcessor; -import org.baeldung.batchtesting.service.BookRecordFieldSetMapper; +import com.baeldung.batchtesting.model.Book; +import com.baeldung.batchtesting.model.BookDetails; +import com.baeldung.batchtesting.model.BookRecord; +import com.baeldung.batchtesting.service.BookDetailsItemProcessor; +import com.baeldung.batchtesting.service.BookItemProcessor; +import com.baeldung.batchtesting.service.BookRecordFieldSetMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Job; diff --git a/spring-batch/src/main/java/com/baeldung/batchtesting/model/Book.java b/spring-batch/src/main/java/com/baeldung/batchtesting/model/Book.java new file mode 100644 index 0000000000..f34e6cb5f6 --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/model/Book.java @@ -0,0 +1,33 @@ +package com.baeldung.batchtesting.model; + +public class Book { + + private String author; + + private String name; + + public Book() { + } + + public String getAuthor() { + return author; + } + + public String getName() { + return name; + } + + public void setAuthor(String author) { + this.author = author; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Book [author=" + author + ", name=" + name + "]"; + } + +} diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/model/BookDetails.java b/spring-batch/src/main/java/com/baeldung/batchtesting/model/BookDetails.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/batchtesting/model/BookDetails.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/model/BookDetails.java index d9284fbc66..3e994d2c92 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/model/BookDetails.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/model/BookDetails.java @@ -1,4 +1,4 @@ -package org.baeldung.batchtesting.model; +package com.baeldung.batchtesting.model; public class BookDetails { diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/model/BookRecord.java b/spring-batch/src/main/java/com/baeldung/batchtesting/model/BookRecord.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/batchtesting/model/BookRecord.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/model/BookRecord.java index 35fb40e878..d6a1692577 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/model/BookRecord.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/model/BookRecord.java @@ -1,4 +1,4 @@ -package org.baeldung.batchtesting.model; +package com.baeldung.batchtesting.model; public class BookRecord { diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookDetailsItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java similarity index 83% rename from spring-batch/src/main/java/org/baeldung/batchtesting/service/BookDetailsItemProcessor.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java index f3800fee51..514a383108 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookDetailsItemProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java @@ -1,7 +1,7 @@ -package org.baeldung.batchtesting.service; +package com.baeldung.batchtesting.service; -import org.baeldung.batchtesting.model.BookDetails; -import org.baeldung.batchtesting.model.BookRecord; +import com.baeldung.batchtesting.model.BookDetails; +import com.baeldung.batchtesting.model.BookRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookItemProcessor.java similarity index 79% rename from spring-batch/src/main/java/org/baeldung/batchtesting/service/BookItemProcessor.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/service/BookItemProcessor.java index 69e72ba1d3..84e850fe71 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookItemProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookItemProcessor.java @@ -1,7 +1,7 @@ -package org.baeldung.batchtesting.service; +package com.baeldung.batchtesting.service; -import org.baeldung.batchtesting.model.Book; -import org.baeldung.batchtesting.model.BookRecord; +import com.baeldung.batchtesting.model.Book; +import com.baeldung.batchtesting.model.BookRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookRecordFieldSetMapper.java b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java similarity index 89% rename from spring-batch/src/main/java/org/baeldung/batchtesting/service/BookRecordFieldSetMapper.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java index cfc36fed7a..d9e8ee1158 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookRecordFieldSetMapper.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java @@ -1,6 +1,6 @@ -package org.baeldung.batchtesting.service; +package com.baeldung.batchtesting.service; -import org.baeldung.batchtesting.model.BookRecord; +import com.baeldung.batchtesting.model.BookRecord; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.validation.BindException; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineProcessor.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineProcessor.java similarity index 92% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineProcessor.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineProcessor.java index 5b6cd9add3..87d0bdc3fb 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.taskletsvschunks.chunks; +package com.baeldung.taskletsvschunks.chunks; -import org.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.model.Line; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineReader.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java similarity index 87% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineReader.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java index 5f6b6de218..6ffa730c19 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineReader.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java @@ -1,7 +1,7 @@ -package org.baeldung.taskletsvschunks.chunks; +package com.baeldung.taskletsvschunks.chunks; -import org.baeldung.taskletsvschunks.model.Line; -import org.baeldung.taskletsvschunks.utils.FileUtils; +import com.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.utils.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; diff --git a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java new file mode 100644 index 0000000000..9f292b24b9 --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java @@ -0,0 +1,39 @@ +package com.baeldung.taskletsvschunks.chunks; + +import com.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.utils.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.core.StepExecutionListener; +import org.springframework.batch.item.ItemWriter; + +import java.util.List; + +public class LinesWriter implements ItemWriter, StepExecutionListener { + + private final Logger logger = LoggerFactory.getLogger(LinesWriter.class); + private FileUtils fu; + + @Override + public void beforeStep(StepExecution stepExecution) { + fu = new FileUtils("output.csv"); + logger.debug("Line Writer initialized."); + } + + @Override + public ExitStatus afterStep(StepExecution stepExecution) { + fu.closeWriter(); + logger.debug("Line Writer ended."); + return ExitStatus.COMPLETED; + } + + @Override + public void write(List lines) throws Exception { + for (Line line : lines) { + fu.writeLine(line); + logger.debug("Wrote line " + line.toString()); + } + } +} diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/ChunksConfig.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java similarity index 91% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/ChunksConfig.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java index 601ffb7f27..57288fb312 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/ChunksConfig.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java @@ -1,9 +1,9 @@ -package org.baeldung.taskletsvschunks.config; +package com.baeldung.taskletsvschunks.config; -import org.baeldung.taskletsvschunks.chunks.LineProcessor; -import org.baeldung.taskletsvschunks.chunks.LineReader; -import org.baeldung.taskletsvschunks.chunks.LinesWriter; -import org.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.chunks.LineProcessor; +import com.baeldung.taskletsvschunks.chunks.LineReader; +import com.baeldung.taskletsvschunks.chunks.LinesWriter; +import com.baeldung.taskletsvschunks.model.Line; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/TaskletsConfig.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java similarity index 92% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/TaskletsConfig.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java index b9d06d2639..e7157ac520 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/TaskletsConfig.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java @@ -1,8 +1,8 @@ -package org.baeldung.taskletsvschunks.config; +package com.baeldung.taskletsvschunks.config; -import org.baeldung.taskletsvschunks.tasklets.LinesProcessor; -import org.baeldung.taskletsvschunks.tasklets.LinesReader; -import org.baeldung.taskletsvschunks.tasklets.LinesWriter; +import com.baeldung.taskletsvschunks.tasklets.LinesProcessor; +import com.baeldung.taskletsvschunks.tasklets.LinesReader; +import com.baeldung.taskletsvschunks.tasklets.LinesWriter; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/model/Line.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/model/Line.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/model/Line.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/model/Line.java index fee6fd31a6..2d7d3ff63f 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/model/Line.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/model/Line.java @@ -1,4 +1,4 @@ -package org.baeldung.taskletsvschunks.model; +package com.baeldung.taskletsvschunks.model; import java.io.Serializable; import java.time.LocalDate; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesProcessor.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesProcessor.java similarity index 94% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesProcessor.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesProcessor.java index ba7a3088d5..8b84c39174 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.taskletsvschunks.tasklets; +package com.baeldung.taskletsvschunks.tasklets; -import org.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.model.Line; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesReader.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java similarity index 91% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesReader.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java index 9905ee8f8a..b1f58be4a4 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesReader.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java @@ -1,7 +1,7 @@ -package org.baeldung.taskletsvschunks.tasklets; +package com.baeldung.taskletsvschunks.tasklets; -import org.baeldung.taskletsvschunks.model.Line; -import org.baeldung.taskletsvschunks.utils.FileUtils; +import com.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.utils.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; diff --git a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesWriter.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesWriter.java new file mode 100644 index 0000000000..76128b7841 --- /dev/null +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesWriter.java @@ -0,0 +1,50 @@ +package com.baeldung.taskletsvschunks.tasklets; + +import com.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.utils.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.core.StepExecutionListener; +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.item.ExecutionContext; +import org.springframework.batch.repeat.RepeatStatus; + +import java.util.List; + +public class LinesWriter implements Tasklet, StepExecutionListener { + + private final Logger logger = LoggerFactory.getLogger(LinesWriter.class); + + private List lines; + private FileUtils fu; + + @Override + public void beforeStep(StepExecution stepExecution) { + ExecutionContext executionContext = stepExecution + .getJobExecution() + .getExecutionContext(); + this.lines = (List) executionContext.get("lines"); + fu = new FileUtils("output.csv"); + logger.debug("Lines Writer initialized."); + } + + @Override + public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { + for (Line line : lines) { + fu.writeLine(line); + logger.debug("Wrote line " + line.toString()); + } + return RepeatStatus.FINISHED; + } + + @Override + public ExitStatus afterStep(StepExecution stepExecution) { + fu.closeWriter(); + logger.debug("Lines Writer ended."); + return ExitStatus.COMPLETED; + } +} diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/utils/FileUtils.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/utils/FileUtils.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/utils/FileUtils.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/utils/FileUtils.java index df36d5c756..fde3b1fa9d 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/utils/FileUtils.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/utils/FileUtils.java @@ -1,8 +1,8 @@ -package org.baeldung.taskletsvschunks.utils; +package com.baeldung.taskletsvschunks.utils; import com.opencsv.CSVReader; import com.opencsv.CSVWriter; -import org.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.model.Line; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-batch/src/main/java/org/baeldung/batch/App.java b/spring-batch/src/main/java/org/baeldung/batch/App.java deleted file mode 100644 index 91b99ba571..0000000000 --- a/spring-batch/src/main/java/org/baeldung/batch/App.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.baeldung.batch; - -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.JobParameters; -import org.springframework.batch.core.JobParametersBuilder; -import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -public class App { - - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - public static void main(final String[] args) { - // Spring Java config - final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.register(SpringConfig.class); - context.register(SpringBatchConfig.class); - context.refresh(); - - // Spring xml config - // ApplicationContext context = new ClassPathXmlApplicationContext("spring-batch.xml"); - - runJob(context, "firstBatchJob"); - runJob(context, "skippingBatchJob"); - runJob(context, "skipPolicyBatchJob"); - } - - private static void runJob(AnnotationConfigApplicationContext context, String batchJobName) { - final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); - final Job job = (Job) context.getBean(batchJobName); - - LOGGER.info("Starting the batch job: {}", batchJobName); - try { - // To enable multiple execution of a job with the same parameters - JobParameters jobParameters = new JobParametersBuilder().addString("jobID", String.valueOf(System.currentTimeMillis())) - .toJobParameters(); - final JobExecution execution = jobLauncher.run(job, jobParameters); - LOGGER.info("Job Status : {}", execution.getStatus()); - } catch (final Exception e) { - e.printStackTrace(); - LOGGER.error("Job failed {}", e.getMessage()); - } - } -} \ No newline at end of file diff --git a/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java b/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java deleted file mode 100644 index 35abcb2d16..0000000000 --- a/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.baeldung.batch; - -import java.net.MalformedURLException; - -import javax.sql.DataSource; - -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -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.JobRepositoryFactoryBean; -import org.springframework.batch.support.transaction.ResourcelessTransactionManager; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.Resource; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.jdbc.datasource.init.DataSourceInitializer; -import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.transaction.PlatformTransactionManager; - -@Configuration -@EnableBatchProcessing -public class SpringConfig { - - @Value("org/springframework/batch/core/schema-drop-sqlite.sql") - private Resource dropReopsitoryTables; - - @Value("org/springframework/batch/core/schema-sqlite.sql") - private Resource dataReopsitorySchema; - - @Bean - public DataSource dataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.sqlite.JDBC"); - dataSource.setUrl("jdbc:sqlite:repository.sqlite"); - return dataSource; - } - - @Bean - public DataSourceInitializer dataSourceInitializer(DataSource dataSource) throws MalformedURLException { - ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); - - databasePopulator.addScript(dropReopsitoryTables); - databasePopulator.addScript(dataReopsitorySchema); - databasePopulator.setIgnoreFailedDrops(true); - - DataSourceInitializer initializer = new DataSourceInitializer(); - initializer.setDataSource(dataSource); - initializer.setDatabasePopulator(databasePopulator); - - return initializer; - } - - private JobRepository getJobRepository() throws Exception { - JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); - factory.setDataSource(dataSource()); - factory.setTransactionManager(getTransactionManager()); - // JobRepositoryFactoryBean's methods Throws Generic Exception, - // it would have been better to have a specific one - factory.afterPropertiesSet(); - return (JobRepository) factory.getObject(); - } - - private PlatformTransactionManager getTransactionManager() { - return new ResourcelessTransactionManager(); - } - - public JobLauncher getJobLauncher() throws Exception { - SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); - // SimpleJobLauncher's methods Throws Generic Exception, - // it would have been better to have a specific one - jobLauncher.setJobRepository(getJobRepository()); - jobLauncher.afterPropertiesSet(); - return jobLauncher; - } - -} \ No newline at end of file diff --git a/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java b/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java deleted file mode 100644 index 0ce3a413ab..0000000000 --- a/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.baeldung.batch.model; - -import java.util.Date; - -import javax.xml.bind.annotation.XmlRootElement; - -@SuppressWarnings("restriction") -@XmlRootElement(name = "transactionRecord") -public class Transaction { - private String username; - private int userId; - private Date transactionDate; - private double amount; - - /* getters and setters for the attributes */ - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public int getUserId() { - return userId; - } - - public void setUserId(int userId) { - this.userId = userId; - } - - public Date getTransactionDate() { - return transactionDate; - } - - public void setTransactionDate(Date transactionDate) { - this.transactionDate = transactionDate; - } - - public double getAmount() { - return amount; - } - - public void setAmount(double amount) { - this.amount = amount; - } - - @Override - public String toString() { - return "Transaction [username=" + username + ", userId=" + userId + ", transactionDate=" + transactionDate + ", amount=" + amount + "]"; - } - -} diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/MissingUsernameException.java b/spring-batch/src/main/java/org/baeldung/batch/service/MissingUsernameException.java deleted file mode 100644 index 2cf8f4d334..0000000000 --- a/spring-batch/src/main/java/org/baeldung/batch/service/MissingUsernameException.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.baeldung.batch.service; - -public class MissingUsernameException extends RuntimeException { -} diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java b/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java deleted file mode 100644 index fa6f0870aa..0000000000 --- a/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.batch.service; - -import java.text.ParseException; -import java.text.SimpleDateFormat; - -import org.baeldung.batch.model.Transaction; -import org.springframework.batch.item.file.mapping.FieldSetMapper; -import org.springframework.batch.item.file.transform.FieldSet; -import org.springframework.validation.BindException; - -public class RecordFieldSetMapper implements FieldSetMapper { - - public Transaction mapFieldSet(FieldSet fieldSet) throws BindException { - - SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); - Transaction transaction = new Transaction(); - // you can either use the indices or custom names - // I personally prefer the custom names easy for debugging and - // validating the pipelines - transaction.setUsername(fieldSet.readString("username")); - transaction.setUserId(fieldSet.readInt("userid")); - transaction.setAmount(fieldSet.readDouble(3)); - // Converting the date - String dateString = fieldSet.readString(2); - try { - transaction.setTransactionDate(dateFormat.parse(dateString)); - } catch (ParseException e) { - e.printStackTrace(); - } - - return transaction; - - } - -} 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 deleted file mode 100644 index f992bde20e..0000000000 --- a/spring-batch/src/main/java/org/baeldung/batchscheduler/model/Book.java +++ /dev/null @@ -1,35 +0,0 @@ -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/java/org/baeldung/batchtesting/model/Book.java b/spring-batch/src/main/java/org/baeldung/batchtesting/model/Book.java deleted file mode 100644 index 3ea4a29e7f..0000000000 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/model/Book.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.baeldung.batchtesting.model; - -public class Book { - - private String author; - - private String name; - - public Book() { - } - - public String getAuthor() { - return author; - } - - public String getName() { - return name; - } - - public void setAuthor(String author) { - this.author = author; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return "Book [author=" + author + ", name=" + name + "]"; - } - -} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java new file mode 100644 index 0000000000..c977d6ecab --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java @@ -0,0 +1,21 @@ +package org.baeldung.conditionalflow; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ConditionalFlowApplication implements CommandLineRunner { + private static Logger logger = LoggerFactory.getLogger(ConditionalFlowApplication.class); + + public static void main(String[] args) { + SpringApplication.run(ConditionalFlowApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + logger.info("Running conditional flow application..."); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java new file mode 100644 index 0000000000..701011b4d3 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java @@ -0,0 +1,29 @@ +package org.baeldung.conditionalflow; + +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.core.job.flow.FlowExecutionStatus; +import org.springframework.batch.core.job.flow.JobExecutionDecider; + +public class NumberInfoDecider implements JobExecutionDecider { + + public static final String NOTIFY = "NOTIFY"; + public static final String QUIET = "QUIET"; + + /** + * Method that determines notification status of job + * @return true if notifications should be sent. + */ + private boolean shouldNotify() { + return true; + } + + @Override + public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { + if (shouldNotify()) { + return new FlowExecutionStatus(NOTIFY); + } else { + return new FlowExecutionStatus(QUIET); + } + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java new file mode 100644 index 0000000000..906a6e1d28 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java @@ -0,0 +1,91 @@ +package org.baeldung.conditionalflow.config; + +import org.baeldung.conditionalflow.NumberInfoDecider; +import org.baeldung.conditionalflow.model.NumberInfo; +import org.baeldung.conditionalflow.step.*; +import org.springframework.batch.core.Job; +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.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +import static org.baeldung.conditionalflow.NumberInfoDecider.NOTIFY; + +@Configuration +@EnableBatchProcessing +public class NumberInfoConfig { + + @Bean + @Qualifier("NotificationStep") + public Step notificationStep(StepBuilderFactory sbf) { + return sbf.get("Notify step") + .tasklet(new NotifierTasklet()) + .build(); + } + + public Step numberGeneratorStep(StepBuilderFactory sbf, int[] values, String prepend) { + return sbf.get("Number generator") + . chunk(1) + .reader(new NumberInfoGenerator(values)) + .processor(new NumberInfoClassifier()) + .writer(new PrependingStdoutWriter<>(prepend)) + .build(); + } + + public Step numberGeneratorStepDecider(StepBuilderFactory sbf, int[] values, String prepend) { + return sbf.get("Number generator decider") + . chunk(1) + .reader(new NumberInfoGenerator(values)) + .processor(new NumberInfoClassifierWithDecider()) + .writer(new PrependingStdoutWriter<>(prepend)) + .build(); + } + + @Bean + @Qualifier("first_job") + public Job numberGeneratorNonNotifierJob(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) { + int[] nonNotifierData = { -1, -2, -3 }; + Step step = numberGeneratorStep(stepBuilderFactory, nonNotifierData, "First Dataset Processor"); + return jobBuilderFactory.get("Number generator - first dataset") + .start(step) + .on(NOTIFY) + .to(notificationStep) + .from(step) + .on("*") + .stop() + .end() + .build(); + } + + @Bean + @Qualifier("second_job") + public Job numberGeneratorNotifierJob(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) { + int[] billableData = { 11, -2, -3 }; + Step dataProviderStep = numberGeneratorStep(stepBuilderFactory, billableData, "Second Dataset Processor"); + return jobBuilderFactory.get("Number generator - second dataset") + .start(dataProviderStep) + .on(NOTIFY) + .to(notificationStep) + .end() + .build(); + } + + @Bean + @Qualifier("third_job") + @Primary + public Job numberGeneratorNotifierJobWithDecider(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) { + int[] billableData = { 11, -2, -3 }; + Step dataProviderStep = numberGeneratorStepDecider(stepBuilderFactory, billableData, "Third Dataset Processor"); + return jobBuilderFactory.get("Number generator - third dataset") + .start(dataProviderStep) + .next(new NumberInfoDecider()) + .on(NOTIFY) + .to(notificationStep) + .end() + .build(); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java new file mode 100644 index 0000000000..4134974386 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java @@ -0,0 +1,47 @@ +package org.baeldung.conditionalflow.model; + +import java.util.Objects; + +public class NumberInfo { + private int number; + + public NumberInfo(int number) { + this.number = number; + } + + public static NumberInfo from(int number) { + return new NumberInfo(number); + } + + public boolean isPositive() { + return number > 0; + } + + public boolean isEven() { + return number % 2 == 0; + } + + public int getNumber() { + return number; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + NumberInfo that = (NumberInfo) o; + return number == that.number; + } + + @Override + public int hashCode() { + return Objects.hash(number); + } + + @Override + public String toString() { + return "NumberInfo{" + "number=" + number + '}'; + } +} \ No newline at end of file diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java new file mode 100644 index 0000000000..0d1db66fe9 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java @@ -0,0 +1,15 @@ +package org.baeldung.conditionalflow.step; + +import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.repeat.RepeatStatus; + +public class NotifierTasklet implements Tasklet { + @Override + public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { + System.err.println("[" + chunkContext.getStepContext() + .getJobName() + "] contains interesting data!!"); + return RepeatStatus.FINISHED; + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java new file mode 100644 index 0000000000..fdb28263e7 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java @@ -0,0 +1,35 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.core.annotation.BeforeStep; +import org.springframework.batch.core.listener.ItemListenerSupport; +import org.springframework.batch.item.ItemProcessor; + +import static org.baeldung.conditionalflow.NumberInfoDecider.NOTIFY; +import static org.baeldung.conditionalflow.NumberInfoDecider.QUIET; + +public class NumberInfoClassifier extends ItemListenerSupport + implements ItemProcessor { + private StepExecution stepExecution; + + @BeforeStep + public void beforeStep(StepExecution stepExecution) { + this.stepExecution = stepExecution; + this.stepExecution.setExitStatus(new ExitStatus(QUIET)); + } + + @Override + public void afterProcess(NumberInfo item, Integer result) { + super.afterProcess(item, result); + if (item.isPositive()) { + stepExecution.setExitStatus(new ExitStatus(NOTIFY)); + } + } + + @Override + public Integer process(NumberInfo numberInfo) throws Exception { + return Integer.valueOf(numberInfo.getNumber()); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java new file mode 100644 index 0000000000..4a8b7f1963 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java @@ -0,0 +1,13 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.springframework.batch.core.listener.ItemListenerSupport; +import org.springframework.batch.item.ItemProcessor; + +public class NumberInfoClassifierWithDecider extends ItemListenerSupport implements ItemProcessor { + + @Override + public Integer process(NumberInfo numberInfo) throws Exception { + return Integer.valueOf(numberInfo.getNumber()); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java new file mode 100644 index 0000000000..606ebf6204 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java @@ -0,0 +1,23 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.springframework.batch.item.ItemReader; + +public class NumberInfoGenerator implements ItemReader { + private int[] values; + private int counter; + + public NumberInfoGenerator(int[] values) { + this.values = values; + counter = 0; + } + + @Override + public NumberInfo read() { + if (counter == values.length) { + return null; + } else { + return new NumberInfo(values[counter++]); + } + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java new file mode 100644 index 0000000000..9ffea1e798 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java @@ -0,0 +1,20 @@ +package org.baeldung.conditionalflow.step; + +import java.util.List; + +import org.springframework.batch.item.ItemWriter; + +public class PrependingStdoutWriter implements ItemWriter { + private String prependText; + + public PrependingStdoutWriter(String prependText) { + this.prependText = prependText; + } + + @Override + public void write(List list) { + for (T listItem : list) { + System.out.println(prependText + " " + listItem.toString()); + } + } +} diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LinesWriter.java b/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LinesWriter.java deleted file mode 100644 index 66f9103a56..0000000000 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LinesWriter.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.taskletsvschunks.chunks; - -import org.baeldung.taskletsvschunks.model.Line; -import org.baeldung.taskletsvschunks.utils.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.StepExecutionListener; -import org.springframework.batch.item.ItemWriter; - -import java.util.List; - -public class LinesWriter implements ItemWriter, StepExecutionListener { - - private final Logger logger = LoggerFactory.getLogger(LinesWriter.class); - private FileUtils fu; - - @Override - public void beforeStep(StepExecution stepExecution) { - fu = new FileUtils("output.csv"); - logger.debug("Line Writer initialized."); - } - - @Override - public ExitStatus afterStep(StepExecution stepExecution) { - fu.closeWriter(); - logger.debug("Line Writer ended."); - return ExitStatus.COMPLETED; - } - - @Override - public void write(List lines) throws Exception { - for (Line line : lines) { - fu.writeLine(line); - logger.debug("Wrote line " + line.toString()); - } - } -} diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesWriter.java b/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesWriter.java deleted file mode 100644 index 937288a890..0000000000 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesWriter.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.baeldung.taskletsvschunks.tasklets; - -import org.baeldung.taskletsvschunks.model.Line; -import org.baeldung.taskletsvschunks.utils.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepContribution; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.StepExecutionListener; -import org.springframework.batch.core.scope.context.ChunkContext; -import org.springframework.batch.core.step.tasklet.Tasklet; -import org.springframework.batch.item.ExecutionContext; -import org.springframework.batch.repeat.RepeatStatus; - -import java.util.List; - -public class LinesWriter implements Tasklet, StepExecutionListener { - - private final Logger logger = LoggerFactory.getLogger(LinesWriter.class); - - private List lines; - private FileUtils fu; - - @Override - public void beforeStep(StepExecution stepExecution) { - ExecutionContext executionContext = stepExecution - .getJobExecution() - .getExecutionContext(); - this.lines = (List) executionContext.get("lines"); - fu = new FileUtils("output.csv"); - logger.debug("Lines Writer initialized."); - } - - @Override - public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { - for (Line line : lines) { - fu.writeLine(line); - logger.debug("Wrote line " + line.toString()); - } - return RepeatStatus.FINISHED; - } - - @Override - public ExitStatus afterStep(StepExecution stepExecution) { - fu.closeWriter(); - logger.debug("Lines Writer ended."); - return ExitStatus.COMPLETED; - } -} diff --git a/spring-batch/src/main/resources/input/recordRetry.csv b/spring-batch/src/main/resources/input/recordRetry.csv new file mode 100644 index 0000000000..1b1e3e1ac9 --- /dev/null +++ b/spring-batch/src/main/resources/input/recordRetry.csv @@ -0,0 +1,3 @@ +username, user_id, transaction_date, transaction_amount +sammy, 1234, 31/10/2015, 10000 +john, 9999, 3/12/2015, 12321 diff --git a/spring-batch/src/main/resources/logback.xml b/spring-batch/src/main/resources/logback.xml index 9a622ceb65..55bbeba870 100644 --- a/spring-batch/src/main/resources/logback.xml +++ b/spring-batch/src/main/resources/logback.xml @@ -8,15 +8,15 @@ - + - + - + diff --git a/spring-batch/src/main/resources/output/output1.xml b/spring-batch/src/main/resources/output/output1.xml index 194b860813..838d04882a 100644 --- a/spring-batch/src/main/resources/output/output1.xml +++ b/spring-batch/src/main/resources/output/output1.xml @@ -2,19 +2,19 @@ 10000.0 - 2015-10-31T00:00:00+05:30 + 2015-10-31 00:00:00 1234 devendra 12321.0 - 2015-12-03T00:00:00+05:30 + 2015-12-03 00:00:00 2134 john 23411.0 - 2015-02-02T00:00:00+05:30 + 2015-02-02 00:00:00 2134 robin diff --git a/spring-batch/src/main/resources/output/output2.xml b/spring-batch/src/main/resources/output/output2.xml index 194b860813..838d04882a 100644 --- a/spring-batch/src/main/resources/output/output2.xml +++ b/spring-batch/src/main/resources/output/output2.xml @@ -2,19 +2,19 @@ 10000.0 - 2015-10-31T00:00:00+05:30 + 2015-10-31 00:00:00 1234 devendra 12321.0 - 2015-12-03T00:00:00+05:30 + 2015-12-03 00:00:00 2134 john 23411.0 - 2015-02-02T00:00:00+05:30 + 2015-02-02 00:00:00 2134 robin diff --git a/spring-batch/src/main/resources/output/output3.xml b/spring-batch/src/main/resources/output/output3.xml index 194b860813..838d04882a 100644 --- a/spring-batch/src/main/resources/output/output3.xml +++ b/spring-batch/src/main/resources/output/output3.xml @@ -2,19 +2,19 @@ 10000.0 - 2015-10-31T00:00:00+05:30 + 2015-10-31 00:00:00 1234 devendra 12321.0 - 2015-12-03T00:00:00+05:30 + 2015-12-03 00:00:00 2134 john 23411.0 - 2015-02-02T00:00:00+05:30 + 2015-02-02 00:00:00 2134 robin diff --git a/spring-batch/src/main/resources/output/output4.xml b/spring-batch/src/main/resources/output/output4.xml index 194b860813..838d04882a 100644 --- a/spring-batch/src/main/resources/output/output4.xml +++ b/spring-batch/src/main/resources/output/output4.xml @@ -2,19 +2,19 @@ 10000.0 - 2015-10-31T00:00:00+05:30 + 2015-10-31 00:00:00 1234 devendra 12321.0 - 2015-12-03T00:00:00+05:30 + 2015-12-03 00:00:00 2134 john 23411.0 - 2015-02-02T00:00:00+05:30 + 2015-02-02 00:00:00 2134 robin diff --git a/spring-batch/src/main/resources/output/output5.xml b/spring-batch/src/main/resources/output/output5.xml index 194b860813..838d04882a 100644 --- a/spring-batch/src/main/resources/output/output5.xml +++ b/spring-batch/src/main/resources/output/output5.xml @@ -2,19 +2,19 @@ 10000.0 - 2015-10-31T00:00:00+05:30 + 2015-10-31 00:00:00 1234 devendra 12321.0 - 2015-12-03T00:00:00+05:30 + 2015-12-03 00:00:00 2134 john 23411.0 - 2015-02-02T00:00:00+05:30 + 2015-02-02 00:00:00 2134 robin diff --git a/spring-batch/src/main/resources/spring-batch-intro.xml b/spring-batch/src/main/resources/spring-batch-intro.xml index 0f76dd50ff..2a7c1e7c4a 100644 --- a/spring-batch/src/main/resources/spring-batch-intro.xml +++ b/spring-batch/src/main/resources/spring-batch-intro.xml @@ -22,14 +22,14 @@ + class="com.baeldung.batch.service.RecordFieldSetMapper" /> - + @@ -40,7 +40,7 @@ - org.baeldung.batch.model.Transaction + com.baeldung.batch.model.Transaction @@ -54,4 +54,19 @@ + + + + + + + + + + + + + diff --git a/spring-batch/src/test/java/com/baeldung/SpringContextTest.java b/spring-batch/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b82bb35daf --- /dev/null +++ b/spring-batch/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import com.baeldung.batch.App; +import org.junit.Test; + +public class SpringContextTest { + + @Test + public void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-batch/src/test/java/com/baeldung/batch/SpringBatchRetryIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/batch/SpringBatchRetryIntegrationTest.java new file mode 100644 index 0000000000..df9154a765 --- /dev/null +++ b/spring-batch/src/test/java/com/baeldung/batch/SpringBatchRetryIntegrationTest.java @@ -0,0 +1,91 @@ +package com.baeldung.batch; + +import com.baeldung.batch.SpringBatchRetryConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.conn.ConnectTimeoutException; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.JobInstance; +import org.springframework.batch.core.JobParameters; +import org.springframework.batch.core.JobParametersBuilder; +import org.springframework.batch.test.AssertFile; +import org.springframework.batch.test.JobLauncherTestUtils; +import org.springframework.batch.test.context.SpringBatchTest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.core.io.FileSystemResource; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@RunWith(SpringRunner.class) +@SpringBatchTest +@EnableAutoConfiguration +@ContextConfiguration(classes = { SpringBatchRetryConfig.class }) +public class SpringBatchRetryIntegrationTest { + + private static final String TEST_OUTPUT = "xml/retryOutput.xml"; + private static final String EXPECTED_OUTPUT = "src/test/resources/output/batchRetry/retryOutput.xml"; + + @Autowired + private JobLauncherTestUtils jobLauncherTestUtils; + + @MockBean + private CloseableHttpClient closeableHttpClient; + + @Mock + private CloseableHttpResponse httpResponse; + + @Test + public void whenEndpointAlwaysFail_thenJobFails() throws Exception { + when(closeableHttpClient.execute(any())) + .thenThrow(new ConnectTimeoutException("Endpoint is down")); + + JobExecution jobExecution = jobLauncherTestUtils.launchJob(defaultJobParameters()); + JobInstance actualJobInstance = jobExecution.getJobInstance(); + ExitStatus actualJobExitStatus = jobExecution.getExitStatus(); + + assertThat(actualJobInstance.getJobName(), is("retryBatchJob")); + assertThat(actualJobExitStatus.getExitCode(), is("FAILED")); + assertThat(actualJobExitStatus.getExitDescription(), containsString("org.apache.http.conn.ConnectTimeoutException")); + } + + @Test + public void whenEndpointFailsTwicePasses3rdTime_thenSuccess() throws Exception { + FileSystemResource expectedResult = new FileSystemResource(EXPECTED_OUTPUT); + FileSystemResource actualResult = new FileSystemResource(TEST_OUTPUT); + + //fails for first two calls and passes third time onwards + when(httpResponse.getEntity()) + .thenReturn(new StringEntity("{ \"age\":10, \"postCode\":\"430222\" }")); + when(closeableHttpClient.execute(any())) + .thenThrow(new ConnectTimeoutException("Timeout count 1")) + .thenThrow(new ConnectTimeoutException("Timeout count 2")) + .thenReturn(httpResponse); + + JobExecution jobExecution = jobLauncherTestUtils.launchJob(defaultJobParameters()); + JobInstance actualJobInstance = jobExecution.getJobInstance(); + ExitStatus actualJobExitStatus = jobExecution.getExitStatus(); + + assertThat(actualJobInstance.getJobName(), is("retryBatchJob")); + assertThat(actualJobExitStatus.getExitCode(), is("COMPLETED")); + AssertFile.assertFileEquals(expectedResult, actualResult); + } + + private JobParameters defaultJobParameters() { + JobParametersBuilder paramsBuilder = new JobParametersBuilder(); + paramsBuilder.addString("jobID", String.valueOf(System.currentTimeMillis())); + return paramsBuilder.toJobParameters(); + } +} diff --git a/spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java similarity index 96% rename from spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java rename to spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java index 8927421ac5..81877fbc39 100644 --- a/spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java @@ -1,5 +1,6 @@ -package org.baeldung.batchscheduler; +package com.baeldung.batchscheduler; +import com.baeldung.batchscheduler.SpringBatchScheduler; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchIntegrationTest.java similarity index 98% rename from spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchIntegrationTest.java rename to spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchIntegrationTest.java index d66da89ba4..333c69684e 100644 --- a/spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchIntegrationTest.java @@ -1,10 +1,11 @@ -package org.baeldung.batchtesting; +package com.baeldung.batchtesting; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.Collection; +import com.baeldung.batchtesting.SpringBatchConfiguration; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java similarity index 95% rename from spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java rename to spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java index f7b888f0f9..4655117b85 100644 --- a/spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java @@ -1,12 +1,13 @@ -package org.baeldung.batchtesting; +package com.baeldung.batchtesting; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.Arrays; -import org.baeldung.batchtesting.model.Book; -import org.baeldung.batchtesting.model.BookRecord; +import com.baeldung.batchtesting.SpringBatchConfiguration; +import com.baeldung.batchtesting.model.Book; +import com.baeldung.batchtesting.model.BookRecord; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java similarity index 89% rename from spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java rename to spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java index eaf73e4a4a..1132e4d5e2 100644 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.taskletsvschunks.chunks; +package com.baeldung.taskletsvschunks.chunks; -import org.baeldung.taskletsvschunks.config.ChunksConfig; +import com.baeldung.taskletsvschunks.config.ChunksConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java similarity index 89% rename from spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java rename to spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java index 322b17bd55..2e1ad031aa 100644 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.taskletsvschunks.tasklets; +package com.baeldung.taskletsvschunks.tasklets; -import org.baeldung.taskletsvschunks.config.TaskletsConfig; +import com.baeldung.taskletsvschunks.config.TaskletsConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-batch/src/test/java/org/baeldung/SpringContextTest.java b/spring-batch/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 1a4f923a1e..0000000000 --- a/spring-batch/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung; - -import org.baeldung.batch.App; -import org.junit.Test; - -public class SpringContextTest { - - @Test - public void testMain() throws Exception { - App.main(null); - } -} diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java new file mode 100644 index 0000000000..e73cb17494 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java @@ -0,0 +1,56 @@ +package org.baeldung.conditionalflow; + +import org.baeldung.conditionalflow.config.NumberInfoConfig; +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.core.StepExecution; +import org.springframework.batch.test.JobLauncherTestUtils; +import org.springframework.batch.test.context.SpringBatchTest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; + +import java.util.Collection; +import java.util.Iterator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@SpringBatchTest +@EnableAutoConfiguration +@ContextConfiguration(classes = { NumberInfoConfig.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +public class DeciderJobIntegrationTest { + @Autowired + private JobLauncherTestUtils jobLauncherTestUtils; + + @Test + public void givenNumberGeneratorDecider_whenDeciderRuns_thenStatusIsNotify() throws Exception { + JobExecution jobExecution = jobLauncherTestUtils.launchJob(); + Collection actualStepExecutions = jobExecution.getStepExecutions(); + ExitStatus actualJobExitStatus = jobExecution.getExitStatus(); + + assertEquals("COMPLETED", actualJobExitStatus.getExitCode() + .toString()); + assertEquals(2, actualStepExecutions.size()); + boolean notifyStepDidRun = false; + Iterator iterator = actualStepExecutions.iterator(); + while (iterator.hasNext() && !notifyStepDidRun) { + if (iterator.next() + .getStepName() + .equals("Notify step")) { + notifyStepDidRun = true; + } + } + assertTrue(notifyStepDidRun); + } +} diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java new file mode 100644 index 0000000000..dc396b38da --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java @@ -0,0 +1,71 @@ +package org.baeldung.conditionalflow.model; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +class NumberInfoUnitTest { + + @Test + void givenPositive_whenFrom_isPositive() { + assertTrue(NumberInfo.from(1) + .isPositive()); + assertTrue(NumberInfo.from(11) + .isPositive()); + assertFalse(NumberInfo.from(0) + .isPositive()); + } + + @Test + void givenNegative_whenFrom_isNegative() { + assertFalse(NumberInfo.from(-1) + .isPositive()); + assertFalse(NumberInfo.from(-10) + .isPositive()); + } + + @Test + void givenEven_whenFrom_isEven() { + assertTrue(NumberInfo.from(0) + .isEven()); + assertTrue(NumberInfo.from(-2) + .isEven()); + assertTrue(NumberInfo.from(2) + .isEven()); + assertTrue(NumberInfo.from(-22) + .isEven()); + assertTrue(NumberInfo.from(22) + .isEven()); + } + + @Test + void givenOdd_whenFrom_isOdd() { + + assertFalse(NumberInfo.from(1) + .isEven()); + assertFalse(NumberInfo.from(-1) + .isEven()); + + assertFalse(NumberInfo.from(13) + .isEven()); + assertFalse(NumberInfo.from(-13) + .isEven()); + assertFalse(NumberInfo.from(31) + .isEven()); + assertFalse(NumberInfo.from(-51) + .isEven()); + } + + @Test + void giveGeneratedInt_whenFrom_isNumberFromGenerator() { + for (int i = -100; i < 100; i++) { + assertEquals(i, NumberInfo.from(i) + .getNumber()); + } + } +} \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java new file mode 100644 index 0000000000..cea0626168 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java @@ -0,0 +1,16 @@ +package org.baeldung.conditionalflow.step; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.junit.jupiter.api.Test; + +class NumberInfoClassifierUnitTest { + + @Test + void givenNumberInfo_whenProcess_thenConvertsToInteger() throws Exception { + NumberInfoClassifier nic = new NumberInfoClassifier(); + assertEquals(Integer.valueOf(4), nic.process(NumberInfo.from(4))); + assertEquals(Integer.valueOf(-4), nic.process(NumberInfo.from(-4))); + } +} \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java new file mode 100644 index 0000000000..90fd884674 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java @@ -0,0 +1,21 @@ +package org.baeldung.conditionalflow.step; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.junit.jupiter.api.Test; + +public class NumberInfoGeneratorUnitTest { + + @Test + public void givenArray_whenGenerator_correctOrderAndValue() { + int[] numbers = new int[] { 1, -2, 4, -10 }; + NumberInfoGenerator numberGenerator = new NumberInfoGenerator(numbers); + assertEquals(new NumberInfo(numbers[0]), numberGenerator.read()); + assertEquals(new NumberInfo(numbers[1]), numberGenerator.read()); + assertEquals(new NumberInfo(numbers[2]), numberGenerator.read()); + assertEquals(new NumberInfo(numbers[3]), numberGenerator.read()); + assertNull(numberGenerator.read()); + } +} \ No newline at end of file diff --git a/spring-batch/src/test/resources/output/batchRetry/retryOutput.xml b/spring-batch/src/test/resources/output/batchRetry/retryOutput.xml new file mode 100644 index 0000000000..4cc8db7542 --- /dev/null +++ b/spring-batch/src/test/resources/output/batchRetry/retryOutput.xml @@ -0,0 +1 @@ +1010000.04302222015-10-31 00:00:001234sammy1012321.04302222015-12-03 00:00:009999john diff --git a/spring-batch/xml/output.xml b/spring-batch/xml/output.xml index acf4969341..d2bed5fcd3 100644 --- a/spring-batch/xml/output.xml +++ b/spring-batch/xml/output.xml @@ -1 +1 @@ -10000.02015-10-31T00:00:00+05:301234devendra12321.02015-12-03T00:00:00+05:302134john23411.02015-02-02T00:00:00+05:302134robin \ No newline at end of file +10000.02015-10-31 00:00:001234devendra12321.02015-12-03 00:00:002134john23411.02015-02-02 00:00:002134robin \ No newline at end of file diff --git a/spring-batch/xml/retryOutput.xml b/spring-batch/xml/retryOutput.xml new file mode 100644 index 0000000000..c5dec44f16 --- /dev/null +++ b/spring-batch/xml/retryOutput.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/spring-bom/src/test/java/com/baeldung/SpringContextTest.java b/spring-bom/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0c7da10dd6 --- /dev/null +++ b/spring-bom/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.junit.Test; + +import com.baeldung.spring.bom.HelloWorldApp; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + HelloWorldApp.main(null); + } +} diff --git a/spring-bom/src/test/java/org/baeldung/SpringContextTest.java b/spring-bom/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 783567cdfa..0000000000 --- a/spring-bom/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung; - -import org.junit.Test; - -import com.baeldung.spring.bom.HelloWorldApp; - -public class SpringContextTest { - - @Test - public final void testMain() throws Exception { - HelloWorldApp.main(null); - } -} diff --git a/spring-boot-admin/pom.xml b/spring-boot-admin/pom.xml deleted file mode 100644 index ab2b92102c..0000000000 --- a/spring-boot-admin/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - spring-boot-admin - 0.0.1-SNAPSHOT - spring-boot-admin - pom - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - - - - spring-boot-admin-server - spring-boot-admin-client - - - diff --git a/spring-boot-admin/spring-boot-admin-client/pom.xml b/spring-boot-admin/spring-boot-admin-client/pom.xml deleted file mode 100644 index 47abfdddc2..0000000000 --- a/spring-boot-admin/spring-boot-admin-client/pom.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - 4.0.0 - spring-boot-admin-client - 0.0.1-SNAPSHOT - spring-boot-admin-client - jar - Spring Boot Admin Client - - - com.baeldung - spring-boot-admin - 0.0.1-SNAPSHOT - ../../spring-boot-admin - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-security - - - de.codecentric - spring-boot-admin-starter-client - ${spring-boot-admin-starter-client.version} - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - build-info - - - - - - - - - 2.1.6 - 2.0.4.RELEASE - - - diff --git a/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 834f26dacf..0000000000 --- a/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.springbootadminclient.SpringBootAdminClientApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringBootAdminClientApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-admin/spring-boot-admin-server/pom.xml b/spring-boot-admin/spring-boot-admin-server/pom.xml deleted file mode 100644 index d0d2d7a1ef..0000000000 --- a/spring-boot-admin/spring-boot-admin-server/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - 4.0.0 - spring-boot-admin-server - 0.0.1-SNAPSHOT - spring-boot-admin-server - Spring Boot Admin Server - jar - - - com.baeldung - spring-boot-admin - 0.0.1-SNAPSHOT - ../../spring-boot-admin - - - - - org.springframework.boot - spring-boot-starter-web - - - - - - de.codecentric - spring-boot-admin-starter-server - ${spring-boot-admin-server.version} - - - - - de.codecentric - spring-boot-admin-server-ui-login - ${spring-boot-admin-server-ui-login.version} - - - org.springframework.boot - spring-boot-starter-security - - - com.hazelcast - hazelcast - - - - - de.codecentric - spring-boot-admin-starter-client - ${spring-boot-admin-starter-client.version} - - - - - org.springframework.boot - spring-boot-starter-mail - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - - - 2.1.6 - 2.1.6 - 1.5.7 - 2.0.4.RELEASE - - - diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index c185456019..0000000000 --- a/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.springbootadminserver.SpringBootAdminServerApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringBootAdminServerApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-angular/pom.xml b/spring-boot-angular/pom.xml deleted file mode 100644 index d78761e921..0000000000 --- a/spring-boot-angular/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - com.baeldung.springbootangular - spring-boot-angular - 1.0 - spring-boot-angular - jar - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-web - - - com.h2database - h2 - 1.4.197 - runtime - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/spring-boot-angular/src/main/java/com/baeldung/application/Application.java b/spring-boot-angular/src/main/java/com/baeldung/application/Application.java deleted file mode 100644 index f1155c3106..0000000000 --- a/spring-boot-angular/src/main/java/com/baeldung/application/Application.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.application; - -import com.baeldung.application.entities.User; -import com.baeldung.application.repositories.UserRepository; -import java.util.stream.Stream; -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 { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - - @Bean - CommandLineRunner init(UserRepository userRepository) { - return args -> { - Stream.of("John", "Julie", "Jennifer", "Helen", "Rachel").forEach(name -> { - User user = new User(name, name.toLowerCase() + "@domain.com"); - userRepository.save(user); - }); - userRepository.findAll().forEach(System.out::println); - }; - } -} diff --git a/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java b/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java deleted file mode 100644 index 14c90d5b10..0000000000 --- a/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.application.controllers; - -import com.baeldung.application.entities.User; -import com.baeldung.application.repositories.UserRepository; -import java.util.List; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@CrossOrigin(origins = "http://localhost:4200") -public class UserController { - - private final UserRepository userRepository; - - public UserController(UserRepository userRepository) { - this.userRepository = userRepository; - } - - @GetMapping("/users") - public List getUsers() { - return (List) userRepository.findAll(); - } - - @PostMapping("/users") - void addUser(@RequestBody User user) { - userRepository.save(user); - } -} diff --git a/spring-boot-angular/src/main/java/com/baeldung/application/entities/User.java b/spring-boot-angular/src/main/java/com/baeldung/application/entities/User.java deleted file mode 100644 index 4c346fa5b9..0000000000 --- a/spring-boot-angular/src/main/java/com/baeldung/application/entities/User.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.application.entities; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - private final String name; - private final String email; - - public User() { - this.name = ""; - this.email = ""; - } - - public User(String name, String email) { - this.name = name; - this.email = email; - } - - public long getId() { - return id; - } - - public String getName() { - return name; - } - - public String getEmail() { - return email; - } - - @Override - public String toString() { - return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; - } -} diff --git a/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java b/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java deleted file mode 100644 index 5a81cadcbe..0000000000 --- a/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.application.repositories; - -import com.baeldung.application.entities.User; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; -import org.springframework.web.bind.annotation.CrossOrigin; - -@Repository -public interface UserRepository extends CrudRepository{} diff --git a/spring-boot-angular/src/main/js/application/src/index.html b/spring-boot-angular/src/main/js/application/src/index.html deleted file mode 100644 index 1ce7ff1ca6..0000000000 --- a/spring-boot-angular/src/main/js/application/src/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - Spring Boot - Angular Application - - - - - - - - - - \ No newline at end of file diff --git a/spring-boot-angular/src/main/js/ecommerce/src/index.html b/spring-boot-angular/src/main/js/ecommerce/src/index.html deleted file mode 100644 index 3faefb6e8c..0000000000 --- a/spring-boot-angular/src/main/js/ecommerce/src/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - Frontend - - - - - - - - - diff --git a/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 961d756a68..0000000000 --- a/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.ecommerce.EcommerceApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = EcommerceApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-artifacts/README.md b/spring-boot-artifacts/README.md deleted file mode 100644 index 876954e858..0000000000 --- a/spring-boot-artifacts/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Spring Boot Artifacts - -This module contains articles about configuring the Spring Boot build process. - -### Relevant Articles: - - [Spring Boot Dependency Management with a Custom Parent](https://www.baeldung.com/spring-boot-dependency-management-custom-parent) - - [Create a Fat Jar App with Spring Boot](https://www.baeldung.com/deployable-fat-jar-spring-boot) - - [Intro to Spring Boot Starters](https://www.baeldung.com/spring-boot-starters) - - [Introduction to WebJars](https://www.baeldung.com/maven-webjars) - - [A Quick Guide to Maven Wrapper](https://www.baeldung.com/maven-wrapper) - - [Running a Spring Boot App with Maven vs an Executable War/Jar](https://www.baeldung.com/spring-boot-run-maven-vs-executable-jar) diff --git a/spring-boot-artifacts/pom.xml b/spring-boot-artifacts/pom.xml deleted file mode 100644 index 97d3c53b49..0000000000 --- a/spring-boot-artifacts/pom.xml +++ /dev/null @@ -1,194 +0,0 @@ - - - 4.0.0 - spring-boot-artifacts - spring-boot-artifacts - war - Demo project for Spring Boot - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-thymeleaf - provided - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - 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} - - - - org.springframework.cloud - spring-cloud-context - ${springcloud.version} - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - - - - ${project.artifactId} - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - com.baeldung.webjar.WebjarsdemoApplication - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.18 - - - - integration-tests - - integration-test - verify - - - - - **/ExternalPropertyFileLoaderIntegrationTest.java - - - - - - - - - - - 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 - 2.0.2.RELEASE - 4.5.8 - - - diff --git a/spring-boot-autoconfiguration/README.md b/spring-boot-autoconfiguration/README.md deleted file mode 100644 index b3a50ad7a5..0000000000 --- a/spring-boot-autoconfiguration/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Spring Boot Auto Configuration - -This module contains articles about Spring Boot Auto Configuration - -### The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles: - -- [Create a Custom Auto-Configuration with Spring Boot](https://www.baeldung.com/spring-boot-custom-auto-configuration) -- [Guide to ApplicationContextRunner in Spring Boot](https://www.baeldung.com/spring-boot-context-runner) -- [A Guide to Spring Boot Configuration Metadata](https://www.baeldung.com/spring-boot-configuration-metadata) diff --git a/spring-boot-autoconfiguration/pom.xml b/spring-boot-autoconfiguration/pom.xml deleted file mode 100644 index a39bf0f071..0000000000 --- a/spring-boot-autoconfiguration/pom.xml +++ /dev/null @@ -1,118 +0,0 @@ - - - 4.0.0 - spring-boot-autoconfiguration - 0.0.1-SNAPSHOT - spring-boot-autoconfiguration - war - This is simple boot application demonstrating a custom auto-configuration - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-test - test - - - - mysql - mysql-connector-java - - - - org.springframework.boot - spring-boot-configuration-processor - 2.1.6.RELEASE - true - - - - org.hsqldb - hsqldb - runtime - - - - - spring-boot - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-war-plugin - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - - - 3.1.1 - 3.3.7-1 - 3.1.7 - 8.5.11 - - - \ No newline at end of file diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md deleted file mode 100644 index 5fb8fd4a84..0000000000 --- a/spring-boot-bootstrap/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Spring Boot Bootstrap - -This module contains articles about bootstrapping Spring Boot applications. - -### Relevant Articles: -- [Spring Boot Tutorial – Bootstrap a Simple Application](https://www.baeldung.com/spring-boot-start) -- [Thin JARs with Spring Boot](https://www.baeldung.com/spring-boot-thin-jar) -- [Deploying a Spring Boot Application to Cloud Foundry](https://www.baeldung.com/spring-boot-app-deploy-to-cloud-foundry) -- [Deploy a Spring Boot Application to Google App Engine](https://www.baeldung.com/spring-boot-google-app-engine) -- [Deploy a Spring Boot Application to OpenShift](https://www.baeldung.com/spring-boot-deploy-openshift) -- [Deploy a Spring Boot Application to AWS Beanstalk](https://www.baeldung.com/spring-boot-deploy-aws-beanstalk) -- [Guide to @SpringBootConfiguration in Spring Boot](https://www.baeldung.com/springbootconfiguration-annotation) diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml deleted file mode 100644 index a81908d8b6..0000000000 --- a/spring-boot-bootstrap/pom.xml +++ /dev/null @@ -1,335 +0,0 @@ - - - 4.0.0 - spring-boot-bootstrap - spring-boot-bootstrap - jar - Demo project for Spring Boot - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - - - mysql - mysql-connector-java - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-test - test - - - io.rest-assured - rest-assured - ${rest-assured.version} - test - - - javax.servlet - javax.servlet-api - ${servlet.version} - - - - - - beanstalk - - ${project.name}-eb - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - - - **/cloud/config/*.java - - - - - - - - openshift - - 0.3.0.RELEASE - Greenwich.RELEASE - 3.5.37 - - - - - org.springframework.cloud - spring-cloud-kubernetes-dependencies - ${spring-cloud-k8s.version} - pom - import - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - org.springframework.cloud - spring-cloud-starter-kubernetes-config - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-actuator - - - - - - src/main/resources - - **/logback.xml - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - **/cloud/config/*.java - - - - - org.springframework.boot - spring-boot-maven-plugin - - - io.fabric8 - fabric8-maven-plugin - ${fabric8.maven.plugin.version} - - - fmp - - resource - build - - - - - - - - - cloud-gcp - - - - org.springframework.cloud - spring-cloud-dependencies - Greenwich.RELEASE - pom - import - - - - - - org.springframework.cloud - spring-cloud-gcp-starter - 1.0.0.RELEASE - - - org.springframework.cloud - spring-cloud-gcp-starter-sql-mysql - 1.0.0.RELEASE - - - - ${project.name}-gcp - - - src/main/resources - - **/logback.xml - - - - - - com.google.cloud.tools - appengine-maven-plugin - 1.3.2 - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - cloudfoundry - - - - org.springframework.cloud - spring-cloud-dependencies - Greenwich.RELEASE - pom - import - - - - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.boot - spring-boot-starter-cloud-connectors - - - - ${project.name}-cf - - - src/main/resources - - **/logback.xml - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - - - **/cloud/config/*.java - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - thin-jar - - - - org.springframework.boot.experimental - spring-boot-thin-maven-plugin - ${thin.version} - - - - resolve - - resolve - - false - - - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - **/cloud/config/*.java - - - - - - - - 4.0.0 - - - diff --git a/spring-boot-bootstrap/src/main/resources/application-mysql.properties b/spring-boot-bootstrap/src/main/resources/application-mysql.properties deleted file mode 100644 index a1823b5d7f..0000000000 --- a/spring-boot-bootstrap/src/main/resources/application-mysql.properties +++ /dev/null @@ -1 +0,0 @@ -spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect \ No newline at end of file diff --git a/spring-boot-camel/pom.xml b/spring-boot-camel/pom.xml deleted file mode 100644 index 8bab0ed5c8..0000000000 --- a/spring-boot-camel/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - 4.0.0 - com.example - spring-boot-camel - 0.0.1-SNAPSHOT - spring-boot-camel - - - 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} - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot-starter.version} - test - - - - - 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/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 8324fabfca..0000000000 --- a/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.camel.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-client/pom.xml b/spring-boot-client/pom.xml deleted file mode 100644 index 2cfd413e93..0000000000 --- a/spring-boot-client/pom.xml +++ /dev/null @@ -1,141 +0,0 @@ - - - 4.0.0 - spring-boot-client - 0.0.1-SNAPSHOT - spring-boot-client - war - This is simple boot client application for Spring boot actuator test - - - com.baeldung - parent-boot-2 - 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 deleted file mode 100644 index c1b6558b26..0000000000 --- a/spring-boot-client/src/main/java/org/baeldung/boot/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -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-client/src/main/java/org/baeldung/websocket/client/Message.java b/spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java deleted file mode 100644 index 2744c49f62..0000000000 --- a/spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.websocket.client; - -public class Message { - - private String from; - private String text; - - public String getText() { - return text; - } - - public String getFrom() { - return from; - } - - public void setFrom(String from) { - this.from = from; - } - - public void setText(String text) { - this.text = text; - } - -} diff --git a/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 9c3b83ea79..0000000000 --- a/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.boot.Application; -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(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-config-jpa-error/data-jpa-application/README.md b/spring-boot-config-jpa-error/data-jpa-application/README.md deleted file mode 100644 index 443ec07183..0000000000 --- a/spring-boot-config-jpa-error/data-jpa-application/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles - -- [Unable to Find @SpringBootConfiguration with @DataJpaTest](https://www.baeldung.com/spring-boot-unable-to-find-springbootconfiguration-with-datajpatest) diff --git a/spring-boot-config-jpa-error/data-jpa-library/README.md b/spring-boot-config-jpa-error/data-jpa-library/README.md deleted file mode 100644 index 4e852f8a90..0000000000 --- a/spring-boot-config-jpa-error/data-jpa-library/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Unable to Find @SpringBootConfiguration with @DataJpaTest](https://www.baeldung.com/spring-boot-unable-to-find-springbootconfiguration-with-datajpatest) diff --git a/spring-boot-config-jpa-error/pom.xml b/spring-boot-config-jpa-error/pom.xml deleted file mode 100644 index 4b99f9be93..0000000000 --- a/spring-boot-config-jpa-error/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - 4.0.0 - com.baeldung.spring-boot-config-jpa-error - spring-boot-config-jpa-error - 0.0.1-SNAPSHOT - pom - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2/pom.xml - - - - data-jpa-library - data-jpa-application - - - - - - 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-test - ${spring-boot.version} - test - - - - com.h2database - h2 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - \ No newline at end of file diff --git a/spring-boot-crud/pom.xml b/spring-boot-crud/pom.xml deleted file mode 100644 index e78e939f0c..0000000000 --- a/spring-boot-crud/pom.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - 4.0.0 - spring-boot-crud - spring-boot-crud - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-test - - - org.mockito - mockito-core - test - - - com.h2database - h2 - runtime - - - - - spring-boot-crud - - - src/main/resources - true - - - - - org.springframework.boot - spring-boot-maven-plugin - - exec - - - - org.apache.maven.plugins - maven-assembly-plugin - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - - - - UTF-8 - - - diff --git a/spring-boot-crud/src/main/java/com/baeldung/crud/Application.java b/spring-boot-crud/src/main/java/com/baeldung/crud/Application.java deleted file mode 100644 index 0b686e90e9..0000000000 --- a/spring-boot-crud/src/main/java/com/baeldung/crud/Application.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.crud; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -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.crud"}) -@EnableJpaRepositories(basePackages="com.baeldung.crud.repositories") -@EnableTransactionManagement -@EntityScan(basePackages="com.baeldung.crud.entities") -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-boot-crud/src/main/java/com/baeldung/crud/controllers/UserController.java b/spring-boot-crud/src/main/java/com/baeldung/crud/controllers/UserController.java deleted file mode 100644 index 9a6cb477aa..0000000000 --- a/spring-boot-crud/src/main/java/com/baeldung/crud/controllers/UserController.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.crud.controllers; - -import javax.validation.Valid; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; - -import com.baeldung.crud.entities.User; -import com.baeldung.crud.repositories.UserRepository; - -@Controller -public class UserController { - - private final UserRepository userRepository; - - @Autowired - public UserController(UserRepository userRepository) { - this.userRepository = userRepository; - } - - @GetMapping("/signup") - public String showSignUpForm(User user) { - return "add-user"; - } - - @PostMapping("/adduser") - public String addUser(@Valid User user, BindingResult result, Model model) { - if (result.hasErrors()) { - return "add-user"; - } - - userRepository.save(user); - model.addAttribute("users", userRepository.findAll()); - return "index"; - } - - @GetMapping("/edit/{id}") - public String showUpdateForm(@PathVariable("id") long id, Model model) { - User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); - model.addAttribute("user", user); - return "update-user"; - } - - @PostMapping("/update/{id}") - public String updateUser(@PathVariable("id") long id, @Valid User user, BindingResult result, Model model) { - if (result.hasErrors()) { - user.setId(id); - return "update-user"; - } - - userRepository.save(user); - model.addAttribute("users", userRepository.findAll()); - return "index"; - } - - @GetMapping("/delete/{id}") - public String deleteUser(@PathVariable("id") long id, Model model) { - User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); - userRepository.delete(user); - model.addAttribute("users", userRepository.findAll()); - return "index"; - } -} diff --git a/spring-boot-crud/src/main/java/com/baeldung/crud/entities/User.java b/spring-boot-crud/src/main/java/com/baeldung/crud/entities/User.java deleted file mode 100644 index 2074268179..0000000000 --- a/spring-boot-crud/src/main/java/com/baeldung/crud/entities/User.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.crud.entities; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.validation.constraints.NotBlank; - -@Entity -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - @NotBlank(message = "Name is mandatory") - private String name; - - @NotBlank(message = "Email is mandatory") - private String email; - - public User() {} - - public User(String name, String email) { - this.name = name; - this.email = email; - } - - public void setId(long id) { - this.id = id; - } - - public long getId() { - return id; - } - - public void setName(String name) { - this.name = name; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getName() { - return name; - } - - public String getEmail() { - return email; - } - - @Override - public String toString() { - return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; - } -} diff --git a/spring-boot-crud/src/main/java/com/baeldung/crud/repositories/UserRepository.java b/spring-boot-crud/src/main/java/com/baeldung/crud/repositories/UserRepository.java deleted file mode 100644 index 72348463f2..0000000000 --- a/spring-boot-crud/src/main/java/com/baeldung/crud/repositories/UserRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.crud.repositories; - -import com.baeldung.crud.entities.User; -import java.util.List; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface UserRepository extends CrudRepository { - - List findByName(String name); - -} diff --git a/spring-boot-crud/src/test/java/com/baeldung/crud/UserUnitTest.java b/spring-boot-crud/src/test/java/com/baeldung/crud/UserUnitTest.java deleted file mode 100644 index 565f6727c3..0000000000 --- a/spring-boot-crud/src/test/java/com/baeldung/crud/UserUnitTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.crud; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; - -import com.baeldung.crud.entities.User; - -public class UserUnitTest { - - @Test - public void whenCalledGetName_thenCorrect() { - User user = new User("Julie", "julie@domain.com"); - - assertThat(user.getName()).isEqualTo("Julie"); - } - - @Test - public void whenCalledGetEmail_thenCorrect() { - User user = new User("Julie", "julie@domain.com"); - - assertThat(user.getEmail()).isEqualTo("julie@domain.com"); - } - - @Test - public void whenCalledSetName_thenCorrect() { - User user = new User("Julie", "julie@domain.com"); - - user.setName("John"); - - assertThat(user.getName()).isEqualTo("John"); - } - - @Test - public void whenCalledSetEmail_thenCorrect() { - User user = new User("Julie", "julie@domain.com"); - - user.setEmail("john@domain.com"); - - assertThat(user.getEmail()).isEqualTo("john@domain.com"); - } - - @Test - public void whenCalledtoString_thenCorrect() { - User user = new User("Julie", "julie@domain.com"); - assertThat(user.toString()).isEqualTo("User{id=0, name=Julie, email=julie@domain.com}"); - } -} diff --git a/spring-boot-ctx-fluent/pom.xml b/spring-boot-ctx-fluent/pom.xml deleted file mode 100644 index 782e1fd7f6..0000000000 --- a/spring-boot-ctx-fluent/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - 4.0.0 - spring-boot-ctx-fluent - 0.0.1-SNAPSHOT - spring-boot-ctx-fluent - jar - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - - diff --git a/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index ff3e795778..0000000000 --- a/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung; - -import org.junit.Test; - -import com.baeldung.parent.App; - -public class SpringContextTest { - - @Test - public final void testMain() throws Exception { - App.main(new String[] {}); - } -} diff --git a/spring-boot-custom-starter/README.md b/spring-boot-custom-starter/README.md deleted file mode 100644 index d74dc222d5..0000000000 --- a/spring-boot-custom-starter/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Spring Boot Custom Starter - -This module contains articles about writing [Spring Boot Starters](https://www.baeldung.com/spring-boot-starters). - -### Relevant Articles: -- [Creating a Custom Starter with Spring Boot](https://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](https://www.baeldung.com/spring-boot-multiple-modules) diff --git a/spring-boot-custom-starter/greeter-library/pom.xml b/spring-boot-custom-starter/greeter-library/pom.xml deleted file mode 100644 index da30f2e4be..0000000000 --- a/spring-boot-custom-starter/greeter-library/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - 4.0.0 - greeter-library - 0.0.1-SNAPSHOT - greeter-library - - - com.baeldung - spring-boot-custom-starter - 0.0.1-SNAPSHOT - ../../spring-boot-custom-starter - - - \ No newline at end of file diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml deleted file mode 100644 index 58dd683131..0000000000 --- a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - greeter-spring-boot-autoconfigure - 0.0.1-SNAPSHOT - greeter-spring-boot-autoconfigure - - - com.baeldung - spring-boot-custom-starter - 0.0.1-SNAPSHOT - ../../spring-boot-custom-starter - - - - - org.springframework.boot - spring-boot - ${spring-boot.version} - - - - org.springframework.boot - spring-boot-autoconfigure - ${spring-boot.version} - - - - org.springframework.boot - spring-boot-configuration-processor - ${spring-boot.version} - true - - - - com.baeldung - greeter-library - ${greeter.version} - true - - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot.version} - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${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/test/java/org/baeldung/SpringContextTest.java b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e6ce83fab5..0000000000 --- a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.greeter.autoconfigure.GreeterAutoConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = GreeterAutoConfiguration.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} 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 deleted file mode 100644 index bb1e656963..0000000000 --- a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - 4.0.0 - greeter-spring-boot-sample-app - 0.0.1-SNAPSHOT - greeter-spring-boot-sample-app - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../spring-boot-custom-starter - - - - - com.baeldung - greeter-spring-boot-starter - ${greeter-starter.version} - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - - - - - - 0.0.1-SNAPSHOT - - - diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index b82b67df68..0000000000 --- a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.greeter.sample.GreeterSampleApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = GreeterSampleApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml deleted file mode 100644 index d298756b8e..0000000000 --- a/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - 4.0.0 - greeter-spring-boot-starter - 0.0.1-SNAPSHOT - greeter-spring-boot-starter - - - com.baeldung - spring-boot-custom-starter - 0.0.1-SNAPSHOT - ../../spring-boot-custom-starter - - - - - - org.springframework.boot - spring-boot-starter - ${spring-boot.version} - - - - com.baeldung - greeter-spring-boot-autoconfigure - ${project.version} - - - - com.baeldung - greeter-library - ${greeter.version} - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${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 deleted file mode 100644 index 3117cfa355..0000000000 --- a/spring-boot-custom-starter/greeter/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - 4.0.0 - greeter - 0.0.1-SNAPSHOT - greeter - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../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 deleted file mode 100644 index 96c0d0a585..0000000000 --- a/spring-boot-custom-starter/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - 4.0.0 - spring-boot-custom-starter - 0.0.1-SNAPSHOT - spring-boot-custom-starter - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - greeter-library - greeter-spring-boot-autoconfigure - greeter-spring-boot-starter - greeter-spring-boot-sample-app - - - \ No newline at end of file diff --git a/spring-boot-data/README.md b/spring-boot-data/README.md deleted file mode 100644 index f023bb772f..0000000000 --- a/spring-boot-data/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Spring Boot Data - -This module contains articles about Spring Boot with Spring Data - -## Relevant Articles: - -- [Formatting JSON Dates in Spring Boot](https://www.baeldung.com/spring-boot-formatting-json-dates) -- [Rendering Exceptions in JSON with Spring](https://www.baeldung.com/spring-exceptions-json) -- [Disable Spring Data Auto Configuration](https://www.baeldung.com/spring-data-disable-auto-config) -- [Repositories with Multiple Spring Data Modules](https://www.baeldung.com/spring-multiple-data-modules) -- [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) diff --git a/spring-boot-data/pom.xml b/spring-boot-data/pom.xml deleted file mode 100644 index 663ee640f3..0000000000 --- a/spring-boot-data/pom.xml +++ /dev/null @@ -1,173 +0,0 @@ - - - 4.0.0 - spring-boot-data - spring-boot-data - war - Spring Boot Data Module - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.javers - javers-spring-boot-starter-sql - ${javers.version} - - - org.springframework.boot - spring-boot-starter-data-mongodb - - - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - ${h2.version} - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - org.springframework.boot - spring-boot-starter-test - test - - - - - spring-boot-data - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-war-plugin - - - pl.project13.maven - git-commit-id-plugin - ${git-commit-id-plugin.version} - - - get-the-git-infos - - revision - - initialize - - - validate-the-git-infos - - validateRevision - - package - - - - true - ${project.build.outputDirectory}/git.properties - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 8 - 8 - - - - - - - - autoconfiguration - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.javers.SpringBootJaVersApplication - JAR - - - - org.apache.maven.plugins - maven-compiler-plugin - - 8 - 8 - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - - - - - 5.6.3 - 2.2.4 - - - diff --git a/spring-boot-deployment/pom.xml b/spring-boot-deployment/pom.xml deleted file mode 100644 index 6f724f312b..0000000000 --- a/spring-boot-deployment/pom.xml +++ /dev/null @@ -1,203 +0,0 @@ - - - 4.0.0 - spring-boot-deployment - spring-boot-deployment - war - Demo project for Spring Boot - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-thymeleaf - provided - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - 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} - - - - org.springframework.cloud - spring-cloud-context - ${springcloud.version} - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - - - - ${project.artifactId} - - - src/main/resources - true - - **/conf.properties - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - com.baeldung.webjar.WebjarsdemoApplication - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.18 - - - - integration-tests - - integration-test - verify - - - - - **/ExternalPropertyFileLoaderIntegrationTest.java - - - - - - - - - - - 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 - 2.0.2.RELEASE - 4.5.8 - - - diff --git a/spring-boot-di/pom.xml b/spring-boot-di/pom.xml deleted file mode 100644 index 61059630c4..0000000000 --- a/spring-boot-di/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - 4.0.0 - spring-boot-di - spring-boot-di - jar - Module For Spring Boot DI - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.aspectj - aspectjweaver - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - - org.apache.tomcat.embed - tomcat-embed-jasper - provided - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.SpringBootDiApplication - JAR - - - - - - - com.baeldung.SpringBootDiApplication - - - diff --git a/spring-boot-environment/pom.xml b/spring-boot-environment/pom.xml deleted file mode 100644 index 531ef697d7..0000000000 --- a/spring-boot-environment/pom.xml +++ /dev/null @@ -1,148 +0,0 @@ - - - 4.0.0 - spring-boot-environment - spring-boot-environment - war - Demo project for Spring Boot - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-thymeleaf - provided - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - 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.springframework.cloud - spring-cloud-context - ${springcloud.version} - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - - - - ${project.artifactId} - - - src/main/resources - true - - **/conf.properties - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - - - 2.2 - 18.0 - 3.1.7 - 2.0.2.RELEASE - 4.5.8 - - - diff --git a/spring-boot-flowable/pom.xml b/spring-boot-flowable/pom.xml deleted file mode 100644 index 96558b8595..0000000000 --- a/spring-boot-flowable/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - 4.0.0 - spring-boot-flowable - spring-boot-flowable - war - Spring Boot Flowable Module - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - com.h2database - h2 - runtime - - - org.flowable - flowable-spring-boot-starter-rest - ${flowable.version} - - - org.flowable - flowable-spring-boot-starter-actuator - ${flowable.version} - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - 6.4.1 - - \ No newline at end of file diff --git a/spring-boot-gradle/build.gradle b/spring-boot-gradle/build.gradle deleted file mode 100644 index 96055536c3..0000000000 --- a/spring-boot-gradle/build.gradle +++ /dev/null @@ -1,67 +0,0 @@ -buildscript { - ext { - 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("${springBootPlugin}:${springBootVersion}") - classpath("${thinPlugin}:${thinVersion}") - } -} - -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' -sourceCompatibility = 1.8 - -repositories { - mavenCentral() -} - -dependencies { - compile('org.springframework.boot:spring-boot-starter') - testCompile('org.springframework.boot:spring-boot-starter-test') -} - -springBoot { - mainClassName = 'org.baeldung.DemoApplication' -} - -bootJar { -// This is overridden by the mainClassName in springBoot{} and added here for reference purposes. - mainClassName = 'org.baeldung.DemoApplication' - -// This block serves the same purpose as the above thus commented out. Added here for reference purposes -// manifest { -// 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.jar b/spring-boot-gradle/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 1ce6e58f1c..0000000000 Binary files a/spring-boot-gradle/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/spring-boot-gradle/gradlew.bat b/spring-boot-gradle/gradlew.bat deleted file mode 100644 index e95643d6a2..0000000000 --- a/spring-boot-gradle/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@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/spring-boot-gradle/src/main/java/org/baeldung/DemoApplication.java b/spring-boot-gradle/src/main/java/org/baeldung/DemoApplication.java deleted file mode 100644 index f8df823f25..0000000000 --- a/spring-boot-gradle/src/main/java/org/baeldung/DemoApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class DemoApplication { - - public static void main(String[] args) { - SpringApplication.run(DemoApplication.class, args); - } -} diff --git a/spring-boot-groovy/pom.xml b/spring-boot-groovy/pom.xml new file mode 100644 index 0000000000..f61398c5d6 --- /dev/null +++ b/spring-boot-groovy/pom.xml @@ -0,0 +1,83 @@ + + + + 4.0.0 + com.baeldung.app + spring-boot-groovy + spring-boot-groovy + war + Spring Boot Todo Application with Groovy + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.codehaus.groovy + groovy + + + + org.springframework.boot + spring-boot-starter-test + test + + + com.h2database + h2 + runtime + + + net.bytebuddy + byte-buddy-dep + 1.10.9 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.codehaus.gmavenplus + gmavenplus-plugin + 1.9.0 + + + + addSources + addTestSources + generateStubs + compile + generateTestStubs + compileTests + removeStubs + removeTestStubs + + + + + + + + + com.baeldung.app.SpringBootGroovyApplication + + + diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy new file mode 100644 index 0000000000..4912b75a66 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy @@ -0,0 +1,13 @@ +package com.baeldung.springwithgroovy + +import org.springframework.boot.SpringApplication +import org.springframework.boot.autoconfigure.SpringBootApplication + +import com.baeldung.springwithgroovy.SpringBootGroovyApplication + +@SpringBootApplication +class SpringBootGroovyApplication { + static void main(String[] args) { + SpringApplication.run SpringBootGroovyApplication, args + } +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy new file mode 100644 index 0000000000..9c6aee20d3 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy @@ -0,0 +1,48 @@ +package com.baeldung.springwithgroovy.controller + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.web.bind.annotation.DeleteMapping +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.PutMapping +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 com.baeldung.springwithgroovy.entity.Todo +import com.baeldung.springwithgroovy.service.TodoService + +@RestController +@RequestMapping('todo') +public class TodoController { + + @Autowired + TodoService todoService + + @GetMapping + List getAllTodoList(){ + todoService.findAll() + } + + @PostMapping + Todo saveTodo(@RequestBody Todo todo){ + todoService.saveTodo todo + } + + @PutMapping + Todo updateTodo(@RequestBody Todo todo){ + todoService.updateTodo todo + } + + @DeleteMapping('/{todoId}') + deleteTodo(@PathVariable Integer todoId){ + todoService.deleteTodo todoId + } + + @GetMapping('/{todoId}') + Todo getTodoById(@PathVariable Integer todoId){ + todoService.findById todoId + } +} \ No newline at end of file diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy new file mode 100644 index 0000000000..000d981701 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy @@ -0,0 +1,23 @@ +package com.baeldung.springwithgroovy.entity + +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 = 'todo') +class Todo { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Integer id + + @Column + String task + + @Column + Boolean isCompleted + +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy new file mode 100644 index 0000000000..eb58cc0791 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy @@ -0,0 +1,9 @@ +package com.baeldung.springwithgroovy.repository + +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository + +import com.baeldung.springwithgroovy.entity.Todo + +@Repository +interface TodoRepository extends JpaRepository {} \ No newline at end of file diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy new file mode 100644 index 0000000000..c57af34cde --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy @@ -0,0 +1,16 @@ +package com.baeldung.springwithgroovy.service + +import com.baeldung.springwithgroovy.entity.Todo + +interface TodoService { + + List findAll() + + Todo findById(Integer todoId) + + Todo saveTodo(Todo todo) + + Todo updateTodo(Todo todo) + + Todo deleteTodo(Integer todoId) +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy new file mode 100644 index 0000000000..943c1c6944 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy @@ -0,0 +1,40 @@ +package com.baeldung.springwithgroovy.service.impl + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Service + +import com.baeldung.springwithgroovy.entity.Todo +import com.baeldung.springwithgroovy.repository.TodoRepository +import com.baeldung.springwithgroovy.service.TodoService + +@Service +class TodoServiceImpl implements TodoService { + + @Autowired + TodoRepository todoRepository + + @Override + List findAll() { + todoRepository.findAll() + } + + @Override + Todo findById(Integer todoId) { + todoRepository.findById todoId get() + } + + @Override + Todo saveTodo(Todo todo){ + todoRepository.save todo + } + + @Override + Todo updateTodo(Todo todo){ + todoRepository.save todo + } + + @Override + Todo deleteTodo(Integer todoId){ + todoRepository.deleteById todoId + } +} diff --git a/spring-boot-groovy/src/main/resources/application.properties b/spring-boot-groovy/src/main/resources/application.properties new file mode 100644 index 0000000000..8d53a190bb --- /dev/null +++ b/spring-boot-groovy/src/main/resources/application.properties @@ -0,0 +1,5 @@ +spring.datasource.url=jdbc:h2:mem:todo +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password=sa +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy b/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy new file mode 100644 index 0000000000..bf8b0ff27f --- /dev/null +++ b/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy @@ -0,0 +1,97 @@ +package com.baeldung.springwithgroovy + +import static org.junit.jupiter.api.Assertions.assertEquals +import static org.junit.jupiter.api.Assertions.assertTrue + +import org.junit.BeforeClass +import org.junit.Test +import org.junit.runner.RunWith +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.test.context.event.annotation.BeforeTestClass +import org.springframework.test.context.junit4.SpringRunner + +import com.baeldung.springwithgroovy.entity.Todo + +import io.restassured.RestAssured +import io.restassured.response.Response + +class TodoAppUnitTest { + static API_ROOT = 'http://localhost:8081/todo' + static readingTodoId + static writingTodoId + + @BeforeClass + static void populateDummyData() { + Todo readingTodo = new Todo(task: 'Reading', isCompleted: false) + Todo writingTodo = new Todo(task: 'Writing', isCompleted: false) + + final Response readingResponse = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(readingTodo).post(API_ROOT) + + Todo cookingTodoResponse = readingResponse.as Todo.class + readingTodoId = cookingTodoResponse.getId() + + final Response writingResponse = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(writingTodo).post(API_ROOT) + + Todo writingTodoResponse = writingResponse.as Todo.class + writingTodoId = writingTodoResponse.getId() + } + + @Test + void whenGetAllTodoList_thenOk(){ + final Response response = RestAssured.get(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + assertTrue response.as(List.class).size() > 0 + } + + @Test + void whenGetTodoById_thenOk(){ + final Response response = + RestAssured.get("$API_ROOT/$readingTodoId") + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + Todo todoResponse = response.as Todo.class + assertEquals readingTodoId,todoResponse.getId() + } + + @Test + void whenUpdateTodoById_thenOk(){ + Todo todo = new Todo(id:readingTodoId, isCompleted: true) + final Response response = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(todo).put(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + Todo todoResponse = response.as Todo.class + assertTrue todoResponse.getIsCompleted() + } + + @Test + void whenDeleteTodoById_thenOk(){ + final Response response = + RestAssured.given() + .delete("$API_ROOT/$writingTodoId") + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + } + + @Test + void whenSaveTodo_thenOk(){ + Todo todo = new Todo(task: 'Blogging', isCompleted: false) + final Response response = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(todo).post(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + } +} \ No newline at end of file diff --git a/spring-boot-jasypt/pom.xml b/spring-boot-jasypt/pom.xml deleted file mode 100644 index 76a501c455..0000000000 --- a/spring-boot-jasypt/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - 4.0.0 - com.example.jasypt - spring-boot-jasypt - spring-boot-jasypt - jar - Demo project for Spring Boot - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.github.ulisesbocchio - jasypt-spring-boot-starter - ${jasypt.version} - - - - com.github.ulisesbocchio - jasypt-spring-boot - ${jasypt.version} - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - 2.0.0 - - - diff --git a/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index ab6e4557d5..0000000000 --- a/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.jasypt.Main; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Main.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-keycloak/pom.xml b/spring-boot-keycloak/pom.xml deleted file mode 100644 index 609b4d1dec..0000000000 --- a/spring-boot-keycloak/pom.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - 4.0.0 - com.baeldung.keycloak - spring-boot-keycloak - 0.0.1 - spring-boot-keycloak - jar - This is a simple application demonstrating integration between Keycloak and Spring Boot. - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../parent-boot-1 - - - - - - org.keycloak.bom - keycloak-adapter-bom - ${keycloak-adapter-bom.version} - pom - import - - - - - - - org.springframework.boot - spring-boot-starter - - - org.keycloak - keycloak-spring-boot-starter - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - org.hsqldb - hsqldb - runtime - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - 3.3.0.Final - - - diff --git a/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 4effccc083..0000000000 --- a/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.keycloak.SpringBoot; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringBoot.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-kotlin/README.md b/spring-boot-kotlin/README.md deleted file mode 100644 index d393805ed1..0000000000 --- a/spring-boot-kotlin/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Spring Boot Kotlin - -This module contains articles about Kotlin in Spring Boot projects. - -### Relevant Articles: -- [Non-blocking Spring Boot with Kotlin Coroutines](https://www.baeldung.com/non-blocking-spring-boot-with-kotlin-coroutines) diff --git a/spring-boot-kotlin/pom.xml b/spring-boot-kotlin/pom.xml deleted file mode 100644 index a98d76a398..0000000000 --- a/spring-boot-kotlin/pom.xml +++ /dev/null @@ -1,151 +0,0 @@ - - - 4.0.0 - spring-boot-kotlin - spring-boot-kotlin - jar - Demo project showing how to use non-blocking in Kotlin with Spring Boot - - - com.baeldung - parent-kotlin - 1.0.0-SNAPSHOT - ../parent-kotlin - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - - - - org.jetbrains.kotlin - kotlin-reflect - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - - - org.jetbrains.kotlinx - kotlinx-coroutines-core - ${kotlinx-coroutines.version} - - - org.jetbrains.kotlinx - kotlinx-coroutines-reactor - ${kotlinx-coroutines.version} - - - org.springframework.boot - spring-boot-starter-webflux - - - com.fasterxml.jackson.module - jackson-module-kotlin - - - org.springframework.data - spring-data-r2dbc - ${r2dbc.version} - - - io.r2dbc - r2dbc-h2 - ${h2-r2dbc.version} - - - io.r2dbc - r2dbc-spi - ${r2dbc-spi.version} - - - org.springframework.boot - spring-boot-starter-test - test - - - junit - junit - - - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - io.projectreactor - reactor-test - test - - - - - - - org.jetbrains.kotlin - kotlin-maven-plugin - - - -Xjsr305=strict - - - spring - - - - - org.jetbrains.kotlin - kotlin-maven-allopen - ${kotlin.version} - - - - - - - - 1.3.31 - 1.0.0.M1 - 1.0.0.M7 - 1.0.0.BUILD-SNAPSHOT - 1.2.1 - - - diff --git a/spring-boot-libraries/.mvn/wrapper/maven-wrapper.jar b/spring-boot-libraries/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 5fd4d5023f..0000000000 Binary files a/spring-boot-libraries/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/spring-boot-libraries/README.md b/spring-boot-libraries/README.md deleted file mode 100644 index f0bc3c9e89..0000000000 --- a/spring-boot-libraries/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Spring Boot Libraries - -This module contains articles about various Spring Boot libraries - -### The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles: - -- [Guide to ShedLock with Spring](https://www.baeldung.com/shedlock-spring) -- [A Guide to the Problem Spring Web Library](https://www.baeldung.com/problem-spring-web) diff --git a/spring-boot-libraries/pom.xml b/spring-boot-libraries/pom.xml deleted file mode 100644 index d9c9073542..0000000000 --- a/spring-boot-libraries/pom.xml +++ /dev/null @@ -1,158 +0,0 @@ - - - 4.0.0 - spring-boot-libraries - spring-boot-libraries - war - This is simple boot application for Spring boot actuator test - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-test - test - - - - - org.zalando - problem-spring-web - ${problem-spring-web.version} - - - - - net.javacrumbs.shedlock - shedlock-spring - ${shedlock.version} - - - net.javacrumbs.shedlock - shedlock-provider-jdbc-template - ${shedlock.version} - - - - - - spring-boot-libraries - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-war-plugin - - - - pl.project13.maven - git-commit-id-plugin - ${git-commit-id-plugin.version} - - - get-the-git-infos - - revision - - initialize - - - validate-the-git-infos - - validateRevision - - package - - - - true - ${project.build.outputDirectory}/git.properties - - - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - - - - com.baeldung.intro.App - 8.5.11 - 2.4.1.Final - 1.9.0 - 2.0.0 - 5.0.2 - 5.0.2 - 5.2.4 - 18.0 - 2.2.4 - 2.3.2 - 0.23.0 - 2.1.0 - - - diff --git a/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java b/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java deleted file mode 100644 index 74ea39683d..0000000000 --- a/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.scheduling.shedlock; - -import org.springframework.context.annotation.Configuration; -import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; -import org.springframework.scheduling.annotation.EnableScheduling; - -@Configuration -@EnableScheduling -@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") -public class SchedulerConfiguration { - -} \ No newline at end of file diff --git a/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java b/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java deleted file mode 100644 index 060afe660e..0000000000 --- a/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.scheduling.shedlock; - -import net.javacrumbs.shedlock.core.SchedulerLock; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -@Component -class TaskScheduler { - - @Scheduled(cron = "*/15 * * * *") - @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M") - public void scheduledTask() { - System.out.println("Running ShedLock task"); - } -} diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml deleted file mode 100644 index a7065bc925..0000000000 --- a/spring-boot-logging-log4j2/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - 4.0.0 - spring-boot-logging-log4j2 - spring-boot-logging-log4j2 - jar - Demo project for Spring Boot Logging with Log4J2 - - - - - org.springframework.boot - spring-boot-starter-parent - 2.2.1.RELEASE - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-logging - - - - - org.springframework.boot - spring-boot-starter-test - - - org.springframework.boot - spring-boot-starter-log4j2 - - - org.projectlombok - lombok - ${lombok.version} - provided - - - - - - org.springframework.boot - spring-boot-starter-log4j - ${spring-boot-starter-log4j.version} - - - org.graylog2 - gelfj - ${gelfj.version} - compile - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*ManualTest.java - **/*LiveTest.java - - - - - - - - com.baeldung.springbootlogging.SpringBootLoggingApplication - 1.3.8.RELEASE - 1.1.16 - 1.18.4 - - - diff --git a/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 9817522e68..0000000000 --- a/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.springbootlogging.SpringBootLoggingApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringBootLoggingApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml new file mode 100644 index 0000000000..228e7ce481 --- /dev/null +++ b/spring-boot-modules/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + com.baeldung.spring-boot-modules + spring-boot-modules + spring-boot-modules + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + spring-boot + spring-boot-admin + spring-boot-angular + spring-boot-annotations + spring-boot-artifacts + spring-boot-autoconfiguration + spring-boot-basic-customization + spring-boot-bootstrap + spring-boot-client + spring-boot-config-jpa-error + spring-boot-ctx-fluent + spring-boot-deployment + spring-boot-di + spring-boot-camel + + spring-boot-custom-starter + spring-boot-crud + spring-boot-data + spring-boot-environment + spring-boot-exceptions + spring-boot-flowable + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-libraries + spring-boot-logging-log4j2 + spring-boot-kotlin + spring-boot-mvc + spring-boot-mvc-2 + spring-boot-mvc-birt + spring-boot-nashorn + spring-boot-parent + spring-boot-performance + spring-boot-properties + spring-boot-property-exp + spring-boot-runtime + spring-boot-security + spring-boot-springdoc + spring-boot-testing + spring-boot-vue + + + diff --git a/spring-boot-admin/README.md b/spring-boot-modules/spring-boot-admin/README.md similarity index 100% rename from spring-boot-admin/README.md rename to spring-boot-modules/spring-boot-admin/README.md diff --git a/spring-boot-modules/spring-boot-admin/pom.xml b/spring-boot-modules/spring-boot-admin/pom.xml new file mode 100644 index 0000000000..f7dc98770a --- /dev/null +++ b/spring-boot-modules/spring-boot-admin/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + spring-boot-admin + 0.0.1-SNAPSHOT + spring-boot-admin + pom + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + spring-boot-admin-server + spring-boot-admin-client + + + diff --git a/spring-boot-admin/spring-boot-admin-client/.gitignore b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/.gitignore similarity index 100% rename from spring-boot-admin/spring-boot-admin-client/.gitignore rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-client/.gitignore diff --git a/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/pom.xml b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/pom.xml new file mode 100644 index 0000000000..8bb8c7bac3 --- /dev/null +++ b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + spring-boot-admin-client + 0.0.1-SNAPSHOT + spring-boot-admin-client + jar + Spring Boot Admin Client + + + com.baeldung + spring-boot-admin + 0.0.1-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-security + + + de.codecentric + spring-boot-admin-starter-client + ${spring-boot-admin-starter-client.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + build-info + + + + + + + + + 2.2.2 + 2.0.4.RELEASE + + + diff --git a/spring-boot-admin/spring-boot-admin-client/src/main/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplication.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/main/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplication.java similarity index 100% rename from spring-boot-admin/spring-boot-admin-client/src/main/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplication.java rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/main/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplication.java diff --git a/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties similarity index 100% rename from spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties diff --git a/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml similarity index 100% rename from spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml diff --git a/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationIntegrationTest.java similarity index 100% rename from spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..78a1ab7a54 --- /dev/null +++ b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.springbootadminclient.SpringBootAdminClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootAdminClientApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/.gitignore b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/.gitignore similarity index 100% rename from spring-boot-admin/spring-boot-admin-server/.gitignore rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-server/.gitignore diff --git a/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/pom.xml b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/pom.xml new file mode 100644 index 0000000000..118b270812 --- /dev/null +++ b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + spring-boot-admin-server + 0.0.1-SNAPSHOT + spring-boot-admin-server + Spring Boot Admin Server + jar + + + com.baeldung + spring-boot-admin + 0.0.1-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + + + + de.codecentric + spring-boot-admin-starter-server + ${spring-boot-admin-server.version} + + + + + de.codecentric + spring-boot-admin-server-ui-login + ${spring-boot-admin-server-ui-login.version} + + + org.springframework.boot + spring-boot-starter-security + + + com.hazelcast + hazelcast + + + + + de.codecentric + spring-boot-admin-starter-client + ${spring-boot-admin-starter-client.version} + + + + + org.springframework.boot + spring-boot-starter-mail + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + + + 2.2.2 + 2.2.2 + 1.5.7 + 2.0.4.RELEASE + + + diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/SpringBootAdminServerApplication.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/SpringBootAdminServerApplication.java similarity index 100% rename from spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/SpringBootAdminServerApplication.java rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/SpringBootAdminServerApplication.java diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/HazelcastConfig.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/HazelcastConfig.java similarity index 100% rename from spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/HazelcastConfig.java rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/HazelcastConfig.java diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/NotifierConfiguration.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/NotifierConfiguration.java similarity index 100% rename from spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/NotifierConfiguration.java rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/NotifierConfiguration.java diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/WebSecurityConfig.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/WebSecurityConfig.java similarity index 100% rename from spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/WebSecurityConfig.java rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/WebSecurityConfig.java diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties similarity index 100% rename from spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml similarity index 100% rename from spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigIntegrationTest.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigIntegrationTest.java similarity index 100% rename from spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigIntegrationTest.java rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigIntegrationTest.java diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationIntegrationTest.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationIntegrationTest.java similarity index 100% rename from spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationIntegrationTest.java rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationIntegrationTest.java diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigIntegrationTest.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigIntegrationTest.java similarity index 100% rename from spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigIntegrationTest.java rename to spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3322193134 --- /dev/null +++ b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.springbootadminserver.SpringBootAdminServerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootAdminServerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-angular/README.md b/spring-boot-modules/spring-boot-angular/README.md similarity index 100% rename from spring-boot-angular/README.md rename to spring-boot-modules/spring-boot-angular/README.md diff --git a/spring-boot-modules/spring-boot-angular/pom.xml b/spring-boot-modules/spring-boot-angular/pom.xml new file mode 100644 index 0000000000..5cfc530100 --- /dev/null +++ b/spring-boot-modules/spring-boot-angular/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + com.baeldung.springbootangular + spring-boot-angular + 1.0 + spring-boot-angular + jar + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + com.h2database + h2 + 1.4.197 + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/Application.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/Application.java new file mode 100644 index 0000000000..0101ea3a3b --- /dev/null +++ b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/Application.java @@ -0,0 +1,28 @@ +package com.baeldung.application; + +import com.baeldung.application.entities.User; +import com.baeldung.application.repositories.UserRepository; +import java.util.stream.Stream; +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 { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + CommandLineRunner init(UserRepository userRepository) { + return args -> { + Stream.of("John", "Julie", "Jennifer", "Helen", "Rachel").forEach(name -> { + User user = new User(name, name.toLowerCase() + "@domain.com"); + userRepository.save(user); + }); + userRepository.findAll().forEach(System.out::println); + }; + } +} diff --git a/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java new file mode 100644 index 0000000000..a87ac4e8d1 --- /dev/null +++ b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java @@ -0,0 +1,31 @@ +package com.baeldung.application.controllers; + +import com.baeldung.application.entities.User; +import com.baeldung.application.repositories.UserRepository; +import java.util.List; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@CrossOrigin(origins = "http://localhost:4200") +public class UserController { + + private final UserRepository userRepository; + + public UserController(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @GetMapping("/users") + public List getUsers() { + return (List) userRepository.findAll(); + } + + @PostMapping("/users") + void addUser(@RequestBody User user) { + userRepository.save(user); + } +} diff --git a/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/entities/User.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/entities/User.java new file mode 100644 index 0000000000..ea23edc7e2 --- /dev/null +++ b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/entities/User.java @@ -0,0 +1,43 @@ +package com.baeldung.application.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + private final String name; + private final String email; + + public User() { + this.name = ""; + this.email = ""; + } + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; + } +} diff --git a/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java new file mode 100644 index 0000000000..7bd71c2f86 --- /dev/null +++ b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.application.repositories; + +import com.baeldung.application.entities.User; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; +import org.springframework.web.bind.annotation.CrossOrigin; + +@Repository +public interface UserRepository extends CrudRepository{} diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/EcommerceApplication.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/EcommerceApplication.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/EcommerceApplication.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/EcommerceApplication.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/controller/OrderController.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/controller/OrderController.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/controller/OrderController.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/controller/OrderController.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/controller/ProductController.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/controller/ProductController.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/controller/ProductController.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/controller/ProductController.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/dto/OrderProductDto.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/dto/OrderProductDto.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/dto/OrderProductDto.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/dto/OrderProductDto.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/exception/ApiExceptionHandler.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/exception/ApiExceptionHandler.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/exception/ApiExceptionHandler.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/exception/ApiExceptionHandler.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/exception/ResourceNotFoundException.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/exception/ResourceNotFoundException.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/exception/ResourceNotFoundException.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/exception/ResourceNotFoundException.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/Order.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/Order.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/Order.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/Order.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderProduct.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderProduct.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderProduct.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderProduct.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderProductPK.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderProductPK.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderProductPK.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderProductPK.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderStatus.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderStatus.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderStatus.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/OrderStatus.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/Product.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/Product.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/Product.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/model/Product.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/OrderProductRepository.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/OrderProductRepository.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/OrderProductRepository.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/OrderProductRepository.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/OrderRepository.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/OrderRepository.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/OrderRepository.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/OrderRepository.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/ProductRepository.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/ProductRepository.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/ProductRepository.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/repository/ProductRepository.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderProductService.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderProductService.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderProductService.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderProductService.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderProductServiceImpl.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderProductServiceImpl.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderProductServiceImpl.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderProductServiceImpl.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderService.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderService.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderService.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderService.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderServiceImpl.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderServiceImpl.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderServiceImpl.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/OrderServiceImpl.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/ProductService.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/ProductService.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/ProductService.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/ProductService.java diff --git a/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/ProductServiceImpl.java b/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/ProductServiceImpl.java similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/ProductServiceImpl.java rename to spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/ecommerce/service/ProductServiceImpl.java diff --git a/spring-boot-angular/src/main/js/application/.angular-cli.json b/spring-boot-modules/spring-boot-angular/src/main/js/application/.angular-cli.json similarity index 100% rename from spring-boot-angular/src/main/js/application/.angular-cli.json rename to spring-boot-modules/spring-boot-angular/src/main/js/application/.angular-cli.json diff --git a/spring-boot-angular/src/main/js/application/.editorconfig b/spring-boot-modules/spring-boot-angular/src/main/js/application/.editorconfig similarity index 100% rename from spring-boot-angular/src/main/js/application/.editorconfig rename to spring-boot-modules/spring-boot-angular/src/main/js/application/.editorconfig diff --git a/spring-boot-angular/src/main/js/application/.gitignore b/spring-boot-modules/spring-boot-angular/src/main/js/application/.gitignore similarity index 100% rename from spring-boot-angular/src/main/js/application/.gitignore rename to spring-boot-modules/spring-boot-angular/src/main/js/application/.gitignore diff --git a/spring-boot-angular/src/main/js/application/README.md b/spring-boot-modules/spring-boot-angular/src/main/js/application/README.md similarity index 100% rename from spring-boot-angular/src/main/js/application/README.md rename to spring-boot-modules/spring-boot-angular/src/main/js/application/README.md diff --git a/spring-boot-angular/src/main/js/application/e2e/app.e2e-spec.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/e2e/app.e2e-spec.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/e2e/app.e2e-spec.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/e2e/app.e2e-spec.ts diff --git a/spring-boot-angular/src/main/js/application/e2e/app.po.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/e2e/app.po.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/e2e/app.po.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/e2e/app.po.ts diff --git a/spring-boot-angular/src/main/js/application/e2e/tsconfig.e2e.json b/spring-boot-modules/spring-boot-angular/src/main/js/application/e2e/tsconfig.e2e.json similarity index 100% rename from spring-boot-angular/src/main/js/application/e2e/tsconfig.e2e.json rename to spring-boot-modules/spring-boot-angular/src/main/js/application/e2e/tsconfig.e2e.json diff --git a/spring-boot-angular/src/main/js/application/karma.conf.js b/spring-boot-modules/spring-boot-angular/src/main/js/application/karma.conf.js similarity index 100% rename from spring-boot-angular/src/main/js/application/karma.conf.js rename to spring-boot-modules/spring-boot-angular/src/main/js/application/karma.conf.js diff --git a/spring-boot-angular/src/main/js/application/package-lock.json b/spring-boot-modules/spring-boot-angular/src/main/js/application/package-lock.json similarity index 100% rename from spring-boot-angular/src/main/js/application/package-lock.json rename to spring-boot-modules/spring-boot-angular/src/main/js/application/package-lock.json diff --git a/spring-boot-angular/src/main/js/application/package.json b/spring-boot-modules/spring-boot-angular/src/main/js/application/package.json similarity index 100% rename from spring-boot-angular/src/main/js/application/package.json rename to spring-boot-modules/spring-boot-angular/src/main/js/application/package.json diff --git a/spring-boot-angular/src/main/js/application/protractor.conf.js b/spring-boot-modules/spring-boot-angular/src/main/js/application/protractor.conf.js similarity index 100% rename from spring-boot-angular/src/main/js/application/protractor.conf.js rename to spring-boot-modules/spring-boot-angular/src/main/js/application/protractor.conf.js diff --git a/spring-boot-angular/src/main/js/application/src/app/app-routing.module.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app-routing.module.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/app-routing.module.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app-routing.module.ts diff --git a/spring-boot-angular/src/main/js/application/src/assets/.gitkeep b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app.component.css similarity index 100% rename from spring-boot-angular/src/main/js/application/src/assets/.gitkeep rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app.component.css diff --git a/spring-boot-angular/src/main/js/application/src/app/app.component.html b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app.component.html similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/app.component.html rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app.component.html diff --git a/spring-boot-angular/src/main/js/application/src/app/app.component.spec.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/app.component.spec.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app.component.spec.ts diff --git a/spring-boot-angular/src/main/js/application/src/app/app.component.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app.component.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/app.component.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app.component.ts diff --git a/spring-boot-angular/src/main/js/application/src/app/app.module.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app.module.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/app.module.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/app.module.ts diff --git a/spring-boot-angular/src/main/js/application/src/app/model/user.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/model/user.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/model/user.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/model/user.ts diff --git a/spring-boot-angular/src/main/js/application/src/app/service/user.service.spec.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/service/user.service.spec.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/service/user.service.spec.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/service/user.service.spec.ts diff --git a/spring-boot-angular/src/main/js/application/src/app/service/user.service.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/service/user.service.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/service/user.service.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/service/user.service.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.css b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.css similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.css rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.css diff --git a/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.html b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.html similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.html rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.html diff --git a/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.spec.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.spec.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.spec.ts diff --git a/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-form/user-form.component.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.css b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.css similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.css rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.css diff --git a/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.html b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.html similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.html rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.html diff --git a/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.spec.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.spec.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.spec.ts diff --git a/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/app/user-list/user-list.component.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/assets/.gitkeep b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/assets/.gitkeep similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/assets/.gitkeep rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/assets/.gitkeep diff --git a/spring-boot-angular/src/main/js/application/src/environments/environment.prod.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/environments/environment.prod.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/environments/environment.prod.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/environments/environment.prod.ts diff --git a/spring-boot-angular/src/main/js/application/src/environments/environment.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/environments/environment.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/environments/environment.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/environments/environment.ts diff --git a/spring-boot-angular/src/main/js/application/src/favicon.ico b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/favicon.ico similarity index 100% rename from spring-boot-angular/src/main/js/application/src/favicon.ico rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/favicon.ico diff --git a/spring-boot-modules/spring-boot-angular/src/main/js/application/src/index.html b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/index.html new file mode 100644 index 0000000000..398190f439 --- /dev/null +++ b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/index.html @@ -0,0 +1,17 @@ + + + + + + Spring Boot - Angular Application + + + + + + + + + + diff --git a/spring-boot-angular/src/main/js/application/src/main.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/main.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/main.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/main.ts diff --git a/spring-boot-angular/src/main/js/application/src/polyfills.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/polyfills.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/polyfills.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/polyfills.ts diff --git a/spring-boot-angular/src/main/js/application/src/styles.css b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/styles.css similarity index 100% rename from spring-boot-angular/src/main/js/application/src/styles.css rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/styles.css diff --git a/spring-boot-angular/src/main/js/application/src/tsconfig.app.json b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/tsconfig.app.json similarity index 100% rename from spring-boot-angular/src/main/js/application/src/tsconfig.app.json rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/tsconfig.app.json diff --git a/spring-boot-angular/src/main/js/application/src/tsconfig.spec.json b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/tsconfig.spec.json similarity index 100% rename from spring-boot-angular/src/main/js/application/src/tsconfig.spec.json rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/tsconfig.spec.json diff --git a/spring-boot-angular/src/main/js/application/src/typings.d.ts b/spring-boot-modules/spring-boot-angular/src/main/js/application/src/typings.d.ts similarity index 100% rename from spring-boot-angular/src/main/js/application/src/typings.d.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/application/src/typings.d.ts diff --git a/spring-boot-angular/src/main/js/application/tsconfig.json b/spring-boot-modules/spring-boot-angular/src/main/js/application/tsconfig.json similarity index 100% rename from spring-boot-angular/src/main/js/application/tsconfig.json rename to spring-boot-modules/spring-boot-angular/src/main/js/application/tsconfig.json diff --git a/spring-boot-angular/src/main/js/application/tslint.json b/spring-boot-modules/spring-boot-angular/src/main/js/application/tslint.json similarity index 100% rename from spring-boot-angular/src/main/js/application/tslint.json rename to spring-boot-modules/spring-boot-angular/src/main/js/application/tslint.json diff --git a/spring-boot-angular/src/main/js/ecommerce/.editorconfig b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/.editorconfig similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/.editorconfig rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/.editorconfig diff --git a/spring-boot-angular/src/main/js/ecommerce/README.md b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/README.md similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/README.md rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/README.md diff --git a/spring-boot-angular/src/main/js/ecommerce/angular.json b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/angular.json similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/angular.json rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/angular.json diff --git a/spring-boot-angular/src/main/js/ecommerce/e2e/protractor.conf.js b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/e2e/protractor.conf.js similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/e2e/protractor.conf.js rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/e2e/protractor.conf.js diff --git a/spring-boot-angular/src/main/js/ecommerce/e2e/src/app.e2e-spec.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/e2e/src/app.e2e-spec.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/e2e/src/app.e2e-spec.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/e2e/src/app.e2e-spec.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/e2e/src/app.po.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/e2e/src/app.po.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/e2e/src/app.po.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/e2e/src/app.po.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/e2e/tsconfig.e2e.json b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/e2e/tsconfig.e2e.json similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/e2e/tsconfig.e2e.json rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/e2e/tsconfig.e2e.json diff --git a/spring-boot-angular/src/main/js/ecommerce/package-lock.json b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/package-lock.json similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/package-lock.json rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/package-lock.json diff --git a/spring-boot-angular/src/main/js/ecommerce/package.json b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/package.json similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/package.json rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/package.json diff --git a/spring-boot-angular/src/main/js/ecommerce/proxy-conf.json b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/proxy-conf.json similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/proxy-conf.json rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/proxy-conf.json diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.css b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.css similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/app.component.css rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.css diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.html b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.html similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/app.component.html rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.html diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.spec.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/app.component.spec.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.spec.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/app.component.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/app.component.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/app.module.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/app.module.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/app.module.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/app.module.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.css b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.css similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.css rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.css diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.html b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.html similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.html rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.html diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.spec.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.spec.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.spec.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/ecommerce.component.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product-order.model.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product-order.model.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product-order.model.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product-order.model.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product-orders.model.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product-orders.model.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product-orders.model.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product-orders.model.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product.model.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product.model.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product.model.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/models/product.model.ts diff --git a/spring-boot-data/src/test/resources/application.properties b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.css similarity index 100% rename from spring-boot-data/src/test/resources/application.properties rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.css diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.html b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.html similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.html rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.html diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.spec.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.spec.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.spec.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/orders/orders.component.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.css b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.css similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.css rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.css diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.html b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.html similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.html rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.html diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.spec.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.spec.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.spec.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/products/products.component.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/services/EcommerceService.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/services/EcommerceService.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/services/EcommerceService.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/services/EcommerceService.ts diff --git a/spring-boot-gradle/src/main/resources/application.properties b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.css similarity index 100% rename from spring-boot-gradle/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.css diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.html b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.html similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.html rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.html diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.spec.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.spec.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.spec.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/app/ecommerce/shopping-cart/shopping-cart.component.ts diff --git a/spring-boot-logging-log4j2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/assets/.gitkeep similarity index 100% rename from spring-boot-logging-log4j2/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/assets/.gitkeep diff --git a/spring-boot-angular/src/main/js/ecommerce/src/browserslist b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/browserslist similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/browserslist rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/browserslist diff --git a/spring-boot-angular/src/main/js/ecommerce/src/environments/environment.prod.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/environments/environment.prod.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/environments/environment.prod.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/environments/environment.prod.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/environments/environment.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/environments/environment.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/environments/environment.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/environments/environment.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/favicon.ico b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/favicon.ico similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/favicon.ico rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/favicon.ico diff --git a/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/index.html b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/index.html new file mode 100644 index 0000000000..2578673a0f --- /dev/null +++ b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/index.html @@ -0,0 +1,14 @@ + + + + + Frontend + + + + + + + + + diff --git a/spring-boot-angular/src/main/js/ecommerce/src/karma.conf.js b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/karma.conf.js similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/karma.conf.js rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/karma.conf.js diff --git a/spring-boot-angular/src/main/js/ecommerce/src/main.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/main.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/main.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/main.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/polyfills.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/polyfills.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/polyfills.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/polyfills.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/styles.css b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/styles.css similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/styles.css rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/styles.css diff --git a/spring-boot-angular/src/main/js/ecommerce/src/test.ts b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/test.ts similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/test.ts rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/test.ts diff --git a/spring-boot-angular/src/main/js/ecommerce/src/tsconfig.app.json b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/tsconfig.app.json similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/tsconfig.app.json rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/tsconfig.app.json diff --git a/spring-boot-angular/src/main/js/ecommerce/src/tsconfig.spec.json b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/tsconfig.spec.json similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/tsconfig.spec.json rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/tsconfig.spec.json diff --git a/spring-boot-angular/src/main/js/ecommerce/src/tslint.json b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/tslint.json similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/src/tslint.json rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/src/tslint.json diff --git a/spring-boot-angular/src/main/js/ecommerce/tsconfig.json b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/tsconfig.json similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/tsconfig.json rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/tsconfig.json diff --git a/spring-boot-angular/src/main/js/ecommerce/tslint.json b/spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/tslint.json similarity index 100% rename from spring-boot-angular/src/main/js/ecommerce/tslint.json rename to spring-boot-modules/spring-boot-angular/src/main/js/ecommerce/tslint.json diff --git a/spring-boot-angular/src/main/resources/application.properties b/spring-boot-modules/spring-boot-angular/src/main/resources/application.properties similarity index 100% rename from spring-boot-angular/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-angular/src/main/resources/application.properties diff --git a/spring-boot-ctx-fluent/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-angular/src/main/resources/logback.xml similarity index 100% rename from spring-boot-ctx-fluent/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-angular/src/main/resources/logback.xml diff --git a/spring-boot-angular/src/test/java/com/baeldung/ecommerce/EcommerceApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-angular/src/test/java/com/baeldung/ecommerce/EcommerceApplicationIntegrationTest.java similarity index 100% rename from spring-boot-angular/src/test/java/com/baeldung/ecommerce/EcommerceApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-angular/src/test/java/com/baeldung/ecommerce/EcommerceApplicationIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0f4fa757d6 --- /dev/null +++ b/spring-boot-modules/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.ecommerce.EcommerceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = EcommerceApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-modules/spring-boot-annotations/README.md b/spring-boot-modules/spring-boot-annotations/README.md new file mode 100644 index 0000000000..a721f28d55 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/README.md @@ -0,0 +1,11 @@ +## Spring Boot Annotations + +This module contains articles about Spring Boot annotations + +### Relevant Articles: + +- [Spring Boot Annotations](https://www.baeldung.com/spring-boot-annotations) +- [Spring Scheduling Annotations](https://www.baeldung.com/spring-scheduling-annotations) +- [Spring Web Annotations](https://www.baeldung.com/spring-mvc-annotations) +- [Spring Core Annotations](https://www.baeldung.com/spring-core-annotations) +- [Spring Bean Annotations](https://www.baeldung.com/spring-bean-annotations) diff --git a/spring-boot-modules/spring-boot-annotations/pom.xml b/spring-boot-modules/spring-boot-annotations/pom.xml new file mode 100644 index 0000000000..59de83b4e5 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + spring-boot-annotations + spring-boot-annotations + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.aspectj + aspectjweaver + 1.9.1 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.zaxxer + HikariCP + + + + + + org.hibernate + hibernate-core + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/Bike.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Bike.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/Bike.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Bike.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/Biker.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Biker.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/Biker.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Biker.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/Car.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Car.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/Car.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Car.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/CarMechanic.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/CarMechanic.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/CarMechanic.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/CarMechanic.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/CarUtility.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/CarUtility.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/CarUtility.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/CarUtility.java diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/ConditionalBeanConfiguration.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/ConditionalBeanConfiguration.java new file mode 100644 index 0000000000..4719425663 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/ConditionalBeanConfiguration.java @@ -0,0 +1,16 @@ +package com.baeldung.annotations; + +import java.util.Properties; + +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ConditionalBeanConfiguration { + + @Conditional(HibernateCondition.class) + Properties additionalProperties() { + // application specific properties + return new Properties(); + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomException.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/CustomException.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomException.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/CustomException.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/Driver.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Driver.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/Driver.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Driver.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/Engine.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Engine.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/Engine.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Engine.java diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HealthCheckController.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HealthCheckController.java new file mode 100644 index 0000000000..e87ed6cb47 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HealthCheckController.java @@ -0,0 +1,16 @@ +package com.baeldung.annotations; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HealthCheckController { + + private static final String STATUS = "UP"; + + @GetMapping("/health") + public ResponseEntity healthCheck() { + return ResponseEntity.ok(STATUS); + } +} diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HibernateCondition.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HibernateCondition.java new file mode 100644 index 0000000000..e2d77cc5d0 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HibernateCondition.java @@ -0,0 +1,15 @@ +package com.baeldung.annotations; + +import org.springframework.context.annotation.Condition; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.core.type.AnnotatedTypeMetadata; + +public class HibernateCondition implements Condition { + + @Override + public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { + // application specific condition check + return true; + } + +} diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/MySQLAutoconfiguration.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/MySQLAutoconfiguration.java new file mode 100644 index 0000000000..ba23267525 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/MySQLAutoconfiguration.java @@ -0,0 +1,59 @@ +package com.baeldung.annotations; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import javax.sql.DataSource; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnResource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +@Configuration +@ConditionalOnClass(DataSource.class) +public class MySQLAutoconfiguration { + + @Bean + @ConditionalOnBean(name = "dataSource") + LocalContainerEntityManagerFactoryBean entityManagerFactory() throws IOException { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + return em; + } + + @Bean + @ConditionalOnProperty(name = "usemysql", havingValue = "local") + DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); + dataSource.setUrl("jdbc:hsqldb:mem:testdb"); + dataSource.setUsername( "sa" ); + dataSource.setPassword( "" ); + return dataSource; + } + + @ConditionalOnResource(resources = "classpath:mysql.properties") + Properties additionalProperties() throws IOException { + final Properties additionalProperties = new Properties(); + + try (InputStream inputStream = new ClassPathResource("classpath:mysql.properties").getInputStream()) { + additionalProperties.load(inputStream); + } + + return additionalProperties; + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/PerformanceAspect.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/PerformanceAspect.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/PerformanceAspect.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/PerformanceAspect.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/Vehicle.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Vehicle.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/Vehicle.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/Vehicle.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleController.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleController.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleController.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleController.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRepository.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleRepository.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRepository.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleRepository.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRestController.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleRestController.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRestController.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleRestController.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleService.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleService.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleService.java rename to spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/VehicleService.java diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/WebApplicationSpecificConfiguration.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/WebApplicationSpecificConfiguration.java new file mode 100644 index 0000000000..62f68bee29 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/WebApplicationSpecificConfiguration.java @@ -0,0 +1,13 @@ +package com.baeldung.annotations; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class WebApplicationSpecificConfiguration { + + @ConditionalOnWebApplication + HealthCheckController healthCheckController() { + return new HealthCheckController(); + } +} diff --git a/spring-boot-modules/spring-boot-artifacts/README.md b/spring-boot-modules/spring-boot-artifacts/README.md new file mode 100644 index 0000000000..cb77cfad4d --- /dev/null +++ b/spring-boot-modules/spring-boot-artifacts/README.md @@ -0,0 +1,13 @@ +## Spring Boot Artifacts + +This module contains articles about configuring the Spring Boot build process. + +### Relevant Articles: + - [Spring Boot Dependency Management with a Custom Parent](https://www.baeldung.com/spring-boot-dependency-management-custom-parent) + - [Create a Fat Jar App with Spring Boot](https://www.baeldung.com/deployable-fat-jar-spring-boot) + - [Intro to Spring Boot Starters](https://www.baeldung.com/spring-boot-starters) + - [Introduction to WebJars](https://www.baeldung.com/maven-webjars) + - [A Quick Guide to Maven Wrapper](https://www.baeldung.com/maven-wrapper) + - [Running a Spring Boot App with Maven vs an Executable War/Jar](https://www.baeldung.com/spring-boot-run-maven-vs-executable-jar) + - [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information) + - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) diff --git a/spring-boot-modules/spring-boot-artifacts/pom.xml b/spring-boot-modules/spring-boot-artifacts/pom.xml new file mode 100644 index 0000000000..de9f6ab635 --- /dev/null +++ b/spring-boot-modules/spring-boot-artifacts/pom.xml @@ -0,0 +1,222 @@ + + + 4.0.0 + spring-boot-artifacts + spring-boot-artifacts + war + Demo project for Spring Boot + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + provided + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + 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} + + + + org.springframework.cloud + spring-cloud-context + ${springcloud.version} + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + + + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.baeldung.webjar.WebjarsdemoApplication + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 2.18 + + + + integration-tests + + integration-test + verify + + + + + **/ExternalPropertyFileLoaderIntegrationTest.java + + + + + + + + pl.project13.maven + git-commit-id-plugin + ${git-commit-id-plugin.version} + + + get-the-git-infos + + revision + + initialize + + + validate-the-git-infos + + validateRevision + + package + + + + true + ${project.build.outputDirectory}/git.properties + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + + com.baeldung.boot.Application + 3.1.1 + 3.3.7-1 + 2.2 + 2.2.4 + 18.0 + 3.1.7 + 2.0.2.RELEASE + 4.5.8 + + + diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/git/CommitIdApplication.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java rename to spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/git/CommitIdApplication.java diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java b/spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/git/CommitInfoController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java rename to spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/git/CommitInfoController.java diff --git a/spring-boot-artifacts/src/main/java/com/baeldung/webjar/TestController.java b/spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/webjar/TestController.java similarity index 100% rename from spring-boot-artifacts/src/main/java/com/baeldung/webjar/TestController.java rename to spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/webjar/TestController.java diff --git a/spring-boot-artifacts/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java b/spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java similarity index 100% rename from spring-boot-artifacts/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java rename to spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java diff --git a/spring-boot-artifacts/src/main/resources/application.properties b/spring-boot-modules/spring-boot-artifacts/src/main/resources/application.properties similarity index 100% rename from spring-boot-artifacts/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-artifacts/src/main/resources/application.properties diff --git a/spring-boot-custom-starter/greeter-library/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-artifacts/src/main/resources/logback.xml similarity index 100% rename from spring-boot-custom-starter/greeter-library/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-artifacts/src/main/resources/logback.xml diff --git a/spring-boot-artifacts/src/main/resources/templates/index.html b/spring-boot-modules/spring-boot-artifacts/src/main/resources/templates/index.html similarity index 100% rename from spring-boot-artifacts/src/main/resources/templates/index.html rename to spring-boot-modules/spring-boot-artifacts/src/main/resources/templates/index.html diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java b/spring-boot-modules/spring-boot-artifacts/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java rename to spring-boot-modules/spring-boot-artifacts/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java diff --git a/spring-boot-artifacts/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-artifacts/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java similarity index 100% rename from spring-boot-artifacts/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-artifacts/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java diff --git a/spring-boot-autoconfiguration/.gitignore b/spring-boot-modules/spring-boot-autoconfiguration/.gitignore similarity index 100% rename from spring-boot-autoconfiguration/.gitignore rename to spring-boot-modules/spring-boot-autoconfiguration/.gitignore diff --git a/spring-boot-modules/spring-boot-autoconfiguration/README.md b/spring-boot-modules/spring-boot-autoconfiguration/README.md new file mode 100644 index 0000000000..d1b5fde7ed --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/README.md @@ -0,0 +1,13 @@ +## Spring Boot Auto Configuration + +This module contains articles about Spring Boot Auto Configuration + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Create a Custom Auto-Configuration with Spring Boot](https://www.baeldung.com/spring-boot-custom-auto-configuration) +- [Guide to ApplicationContextRunner in Spring Boot](https://www.baeldung.com/spring-boot-context-runner) +- [A Guide to Spring Boot Configuration Metadata](https://www.baeldung.com/spring-boot-configuration-metadata) +- [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-autoconfiguration/pom.xml b/spring-boot-modules/spring-boot-autoconfiguration/pom.xml new file mode 100644 index 0000000000..34db784176 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/pom.xml @@ -0,0 +1,118 @@ + + + 4.0.0 + spring-boot-autoconfiguration + 0.0.1-SNAPSHOT + spring-boot-autoconfiguration + war + This is simple boot application demonstrating a custom auto-configuration + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-test + test + + + + mysql + mysql-connector-java + + + + org.springframework.boot + spring-boot-configuration-processor + 2.1.6.RELEASE + true + + + + org.hsqldb + hsqldb + runtime + + + + + spring-boot + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + 3.1.1 + 3.3.7-1 + 3.1.7 + 8.5.11 + + + \ No newline at end of file diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java similarity index 100% rename from spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/AnnotationProcessorApplication.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/AnnotationProcessorApplication.java similarity index 100% rename from spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/AnnotationProcessorApplication.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/AnnotationProcessorApplication.java diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/DatabaseProperties.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/DatabaseProperties.java similarity index 100% rename from spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/DatabaseProperties.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/DatabaseProperties.java diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/AutoconfigurationApplication.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/AutoconfigurationApplication.java similarity index 100% rename from spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/AutoconfigurationApplication.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/AutoconfigurationApplication.java diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUser.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUser.java similarity index 100% rename from spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUser.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUser.java diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java similarity index 100% rename from spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/CustomService.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/CustomService.java similarity index 100% rename from spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/CustomService.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/CustomService.java diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/DefaultService.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/DefaultService.java similarity index 100% rename from spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/DefaultService.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/DefaultService.java diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/SimpleService.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/SimpleService.java similarity index 100% rename from spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/SimpleService.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/SimpleService.java diff --git a/spring-boot-autoconfiguration/src/main/resources/META-INF/spring.factories b/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-boot-autoconfiguration/src/main/resources/META-INF/spring.factories rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/META-INF/spring.factories diff --git a/spring-boot-autoconfiguration/src/main/resources/application.properties b/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties similarity index 100% rename from spring-boot-autoconfiguration/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/logback.xml similarity index 100% rename from spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/logback.xml diff --git a/spring-boot-autoconfiguration/src/main/resources/mysql.properties b/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/mysql.properties similarity index 100% rename from spring-boot-autoconfiguration/src/main/resources/mysql.properties rename to spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/mysql.properties diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextLiveTest.java similarity index 100% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextLiveTest.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextLiveTest.java diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationLiveTest.java b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationLiveTest.java similarity index 100% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationLiveTest.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationLiveTest.java diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanIntegrationTest.java b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanIntegrationTest.java similarity index 100% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanIntegrationTest.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanIntegrationTest.java diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassIntegrationTest.java b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassIntegrationTest.java similarity index 100% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassIntegrationTest.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassIntegrationTest.java diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyIntegrationTest.java b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyIntegrationTest.java similarity index 100% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyIntegrationTest.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyIntegrationTest.java diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/SpringContextLiveTest.java b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/SpringContextLiveTest.java similarity index 100% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/SpringContextLiveTest.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/SpringContextLiveTest.java diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/annotationprocessor/DatabasePropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/annotationprocessor/DatabasePropertiesIntegrationTest.java similarity index 100% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/annotationprocessor/DatabasePropertiesIntegrationTest.java rename to spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/annotationprocessor/DatabasePropertiesIntegrationTest.java diff --git a/spring-boot-autoconfiguration/src/test/resources/ConditionalOnPropertyTest.properties b/spring-boot-modules/spring-boot-autoconfiguration/src/test/resources/ConditionalOnPropertyTest.properties similarity index 100% rename from spring-boot-autoconfiguration/src/test/resources/ConditionalOnPropertyTest.properties rename to spring-boot-modules/spring-boot-autoconfiguration/src/test/resources/ConditionalOnPropertyTest.properties diff --git a/spring-boot-autoconfiguration/src/test/resources/databaseproperties-test.properties b/spring-boot-modules/spring-boot-autoconfiguration/src/test/resources/databaseproperties-test.properties similarity index 100% rename from spring-boot-autoconfiguration/src/test/resources/databaseproperties-test.properties rename to spring-boot-modules/spring-boot-autoconfiguration/src/test/resources/databaseproperties-test.properties diff --git a/spring-boot-modules/spring-boot-basic-customization/README.md b/spring-boot-modules/spring-boot-basic-customization/README.md new file mode 100644 index 0000000000..6c067fc5a1 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/README.md @@ -0,0 +1,14 @@ +## Spring Boot Basic Customization + +This module contains articles about Spring Boot customization + +### Relevant Articles: + + - [How to Change the Default Port in Spring Boot](https://www.baeldung.com/spring-boot-change-port) + - [Using Custom Banners in Spring Boot](https://www.baeldung.com/spring-boot-custom-banners) + - [Create a Custom FailureAnalyzer with Spring Boot](https://www.baeldung.com/spring-boot-failure-analyzer) + - [Spring Boot: Customize Whitelabel Error Page](https://www.baeldung.com/spring-boot-custom-error-page) + - [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) + - [How to Define a Spring Boot Filter?](https://www.baeldung.com/spring-boot-add-filter) + - [Guide to the Favicon in Spring Boot](https://www.baeldung.com/spring-boot-favicon) + - [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) diff --git a/spring-boot-modules/spring-boot-basic-customization/pom.xml b/spring-boot-modules/spring-boot-basic-customization/pom.xml new file mode 100644 index 0000000000..7c2c89def4 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + spring-boot-basic-customization + spring-boot-basic-customization + jar + Module For Spring Boot Basic Customization + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + com.baeldung.changeport.CustomApplication + + diff --git a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java similarity index 93% rename from spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java index aa794182de..42da61fe14 100644 --- a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java @@ -1,10 +1,8 @@ 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; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Configuration; @Configuration public class FilterConfig { diff --git a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java new file mode 100644 index 0000000000..50d5f4ea71 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java @@ -0,0 +1,34 @@ +package com.baeldung.bootcustomfilters.controller; + +import com.baeldung.bootcustomfilters.model.User; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +/** + * Rest controller for User + * @author hemant + * + */ +@RestController +@RequestMapping("/users") +public class UserController { + + private static final Logger LOG = LoggerFactory.getLogger(UserController.class); + + @GetMapping("") + public List getAllUsers() { + LOG.info("Fetching all the users"); + return Arrays.asList( + new User(UUID.randomUUID().toString(), "User1", "user1@test.com"), + new User(UUID.randomUUID().toString(), "User1", "user1@test.com"), + new User(UUID.randomUUID().toString(), "User1", "user1@test.com")); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java similarity index 86% rename from spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java index e42ea7d2dd..3924354932 100644 --- a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java @@ -1,21 +1,15 @@ package com.baeldung.bootcustomfilters.filters; -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 javax.servlet.http.HttpServletResponse; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + /** * A servlet filter to log request and response * The logging implementation is pretty native and for demonstration only diff --git a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java similarity index 85% rename from spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java index d92b723e73..604829c3d3 100644 --- a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java @@ -1,20 +1,14 @@ package com.baeldung.bootcustomfilters.filters; -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.core.annotation.Order; import org.springframework.stereotype.Component; +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + /** * A filter to create transaction before and commit it once request completes * The current implemenatation is just for demo diff --git a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/model/User.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/model/User.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/bootcustomfilters/model/User.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/model/User.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/changeport/CustomApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/CustomApplication.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/changeport/CustomApplication.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/CustomApplication.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java new file mode 100644 index 0000000000..9f6c209deb --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.errorhandling; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = "com.baeldung.errorhandling") +public class ErrorHandlingApplication { + + public static void main(String [] args) { + System.setProperty("spring.profiles.active", "errorhandling"); + SpringApplication.run(ErrorHandlingApplication.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java diff --git a/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java new file mode 100644 index 0000000000..c28f908fb8 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java @@ -0,0 +1,31 @@ +package com.baeldung.exitcode.event; + +import org.springframework.boot.ExitCodeEvent; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.event.EventListener; + +@SpringBootApplication +public class ExitCodeEventDemoApplication { + + public static void main(String[] args) { + System.exit( + SpringApplication.exit( + SpringApplication.run(ExitCodeEventDemoApplication.class, args) + ) + ); + } + + @Bean + DemoListener demoListenerBean() { + return new DemoListener(); + } + + private static class DemoListener { + @EventListener + public void exitEvent(ExitCodeEvent event) { + System.out.println("Exit code: " + event.getExitCode()); + } + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java new file mode 100644 index 0000000000..44b4ff36f5 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java @@ -0,0 +1,31 @@ +package com.baeldung.exitcode.exception; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeExceptionMapper; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class ExitCodeExceptionMapperDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(ExitCodeExceptionMapperDemoApplication.class, args); + } + + @Bean + CommandLineRunner createException() { + return args -> Integer.parseInt("test"); + } + + @Bean + ExitCodeExceptionMapper exitCodeToExceptionMapper() { + return exception -> { + // set exit code based on the exception type + if (exception.getCause() instanceof NumberFormatException) { + return 80; + } + return 1; + }; + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java new file mode 100644 index 0000000000..7f7acbe86e --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java @@ -0,0 +1,22 @@ +package com.baeldung.exitcode.generator; + +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ExitCodeGeneratorDemoApplication implements ExitCodeGenerator { + + public static void main(String[] args) { + System.exit( + SpringApplication.exit( + SpringApplication.run(ExitCodeGeneratorDemoApplication.class, args) + ) + ); + } + + @Override + public int getExitCode() { + return 42; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java index 7bd5c36786..d08fa05c6e 100644 --- a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java @@ -1,10 +1,10 @@ package com.baeldung.failureanalyzer; -import javax.annotation.security.RolesAllowed; - import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import javax.annotation.security.RolesAllowed; + @SpringBootApplication public class FailureAnalyzerApplication { @RolesAllowed("*") diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyDAO.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyDAO.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/failureanalyzer/MyDAO.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyDAO.java diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyService.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyService.java new file mode 100644 index 0000000000..f31b67615f --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyService.java @@ -0,0 +1,13 @@ +package com.baeldung.failureanalyzer; + +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +@Service +public class MyService { + + @Resource(name = "myDAO") + private MyDAO myDAO; + +} diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/FaviconApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/FaviconApplication.java new file mode 100644 index 0000000000..f94549b988 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/FaviconApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.favicon; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class FaviconApplication { + + public static void main(String[] args) { + SpringApplication.run(FaviconApplication.class, args); + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/config/FaviconConfiguration.java similarity index 94% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/config/FaviconConfiguration.java index 9a1f47b5cb..f2a173caf3 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/config/FaviconConfiguration.java @@ -1,8 +1,4 @@ -package com.baeldung.springbootmvc.config; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +package com.baeldung.favicon.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -14,8 +10,13 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import org.springframework.web.servlet.resource.ResourceHttpRequestHandler; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + @Configuration public class FaviconConfiguration { + @Bean public SimpleUrlHandlerMapping myFaviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); @@ -27,13 +28,13 @@ public class FaviconConfiguration { @Bean protected ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); - ClassPathResource classPathResource = new ClassPathResource("com/baeldung/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) diff --git a/spring-boot/src/main/resources/META-INF/spring.factories b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-boot/src/main/resources/META-INF/spring.factories rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/META-INF/spring.factories diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application-errorhandling.properties b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application-errorhandling.properties new file mode 100644 index 0000000000..0a6d68763c --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application-errorhandling.properties @@ -0,0 +1,10 @@ +#server +server.port=9000 +spring.mvc.servlet.path=/ +server.servlet.context-path=/ +server.error.whitelabel.enabled=false + +#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration + +#for Spring Boot 2.0+ +#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties new file mode 100644 index 0000000000..4d4a6ec7bd --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties @@ -0,0 +1,7 @@ +#spring.banner.charset=UTF-8 +#spring.banner.location=classpath:banner.txt +#spring.banner.image.location=classpath:banner.gif +#spring.banner.image.width= //TODO +#spring.banner.image.height= //TODO +#spring.banner.image.margin= //TODO +#spring.banner.image.invert= //TODO diff --git a/spring-boot/src/main/resources/banner.txt b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/banner.txt similarity index 100% rename from spring-boot/src/main/resources/banner.txt rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/banner.txt diff --git a/spring-boot-mvc/src/main/resources/com/baeldung/images/favicon.ico b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/com/baeldung/images/favicon.ico similarity index 100% rename from spring-boot-mvc/src/main/resources/com/baeldung/images/favicon.ico rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/com/baeldung/images/favicon.ico diff --git a/spring-boot-mvc/src/main/resources/favicon.ico b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/favicon.ico similarity index 100% rename from spring-boot-mvc/src/main/resources/favicon.ico rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/favicon.ico diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/logback.xml similarity index 100% rename from spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/logback.xml diff --git a/spring-boot-mvc/src/main/resources/static/favicon.ico b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/static/favicon.ico similarity index 100% rename from spring-boot-mvc/src/main/resources/static/favicon.ico rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/static/favicon.ico diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-404.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-404.html new file mode 100644 index 0000000000..555cf52de4 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-404.html @@ -0,0 +1,7 @@ + + + +

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

+

Go Home

+ + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-500.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-500.html new file mode 100644 index 0000000000..fc64c7e180 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-500.html @@ -0,0 +1,9 @@ + + + +

Sorry, something went wrong!

+ +

We're fixing it.

+

Go Home

+ + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error.html new file mode 100644 index 0000000000..4e953059e2 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error.html @@ -0,0 +1,8 @@ + + + +

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-modules/spring-boot-basic-customization/src/main/resources/templates/error/404.html similarity index 100% rename from spring-boot/src/main/resources/templates/error/404.html rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error/404.html diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/index.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/index.html new file mode 100644 index 0000000000..95c68c8600 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/index.html @@ -0,0 +1,6 @@ + + +

Welcome Home

+

Success! It is working as we expected.

+ + diff --git a/spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java similarity index 99% rename from spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java rename to spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java index b3555f55da..2d9fb56217 100644 --- a/spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java @@ -1,18 +1,16 @@ package com.baeldung.failureanalyzer; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Collection; -import java.util.stream.Collectors; - +import ch.qos.logback.classic.spi.ILoggingEvent; +import com.baeldung.failureanalyzer.utils.ListAppender; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.SpringApplication; -import com.baeldung.failureanalyzer.utils.ListAppender; +import java.util.Collection; +import java.util.stream.Collectors; -import ch.qos.logback.classic.spi.ILoggingEvent; +import static org.assertj.core.api.Assertions.assertThat; public class FailureAnalyzerAppIntegrationTest { diff --git a/spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java similarity index 99% rename from spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java rename to spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java index a298f49ff5..091cd687f1 100644 --- a/spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java @@ -1,11 +1,11 @@ package com.baeldung.failureanalyzer.utils; -import java.util.ArrayList; -import java.util.List; - import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import java.util.ArrayList; +import java.util.List; + public class ListAppender extends AppenderBase { static private List events = new ArrayList<>(); diff --git a/spring-boot-modules/spring-boot-basic-customization/src/test/resources/logback-test.xml b/spring-boot-modules/spring-boot-basic-customization/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..6919a457cb --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/test/resources/logback-test.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-bootstrap/.gitignore b/spring-boot-modules/spring-boot-bootstrap/.gitignore similarity index 100% rename from spring-boot-bootstrap/.gitignore rename to spring-boot-modules/spring-boot-bootstrap/.gitignore diff --git a/spring-boot-modules/spring-boot-bootstrap/README.md b/spring-boot-modules/spring-boot-bootstrap/README.md new file mode 100644 index 0000000000..146cd04551 --- /dev/null +++ b/spring-boot-modules/spring-boot-bootstrap/README.md @@ -0,0 +1,13 @@ +## Spring Boot Bootstrap + +This module contains articles about bootstrapping Spring Boot applications. + +### Relevant Articles: +- [Spring Boot Tutorial – Bootstrap a Simple Application](https://www.baeldung.com/spring-boot-start) +- [Thin JARs with Spring Boot](https://www.baeldung.com/spring-boot-thin-jar) +- [Deploying a Spring Boot Application to Cloud Foundry](https://www.baeldung.com/spring-boot-app-deploy-to-cloud-foundry) +- [Deploy a Spring Boot Application to Google App Engine](https://www.baeldung.com/spring-boot-google-app-engine) +- [Deploy a Spring Boot Application to OpenShift](https://www.baeldung.com/spring-boot-deploy-openshift) +- [Deploy a Spring Boot Application to AWS Beanstalk](https://www.baeldung.com/spring-boot-deploy-aws-beanstalk) +- [Guide to @SpringBootConfiguration in Spring Boot](https://www.baeldung.com/springbootconfiguration-annotation) +- [Implement Health Checks in OpenShift](https://www.baeldung.com/openshift-health-checks) diff --git a/spring-boot-bootstrap/cloudfoundry/manifest.yml b/spring-boot-modules/spring-boot-bootstrap/cloudfoundry/manifest.yml similarity index 100% rename from spring-boot-bootstrap/cloudfoundry/manifest.yml rename to spring-boot-modules/spring-boot-bootstrap/cloudfoundry/manifest.yml diff --git a/spring-boot-bootstrap/openshift/configmap.yml b/spring-boot-modules/spring-boot-bootstrap/openshift/configmap.yml similarity index 100% rename from spring-boot-bootstrap/openshift/configmap.yml rename to spring-boot-modules/spring-boot-bootstrap/openshift/configmap.yml diff --git a/spring-boot-modules/spring-boot-bootstrap/pom.xml b/spring-boot-modules/spring-boot-bootstrap/pom.xml new file mode 100644 index 0000000000..1dc75c7e61 --- /dev/null +++ b/spring-boot-modules/spring-boot-bootstrap/pom.xml @@ -0,0 +1,335 @@ + + + 4.0.0 + spring-boot-bootstrap + spring-boot-bootstrap + jar + Demo project for Spring Boot + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + mysql + mysql-connector-java + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-test + test + + + io.rest-assured + rest-assured + ${rest-assured.version} + test + + + javax.servlet + javax.servlet-api + ${servlet.version} + + + + + + beanstalk + + ${project.name}-eb + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/config/*.java + + + + + + + + openshift + + 0.3.0.RELEASE + Greenwich.RELEASE + 3.5.37 + + + + + org.springframework.cloud + spring-cloud-kubernetes-dependencies + ${spring-cloud-k8s.version} + pom + import + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + org.springframework.cloud + spring-cloud-starter-kubernetes-config + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-actuator + + + + + + src/main/resources + + **/logback.xml + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/config/*.java + + + + + org.springframework.boot + spring-boot-maven-plugin + + + io.fabric8 + fabric8-maven-plugin + ${fabric8.maven.plugin.version} + + + fmp + + resource + build + + + + + + + + + cloud-gcp + + + + org.springframework.cloud + spring-cloud-dependencies + Greenwich.RELEASE + pom + import + + + + + + org.springframework.cloud + spring-cloud-gcp-starter + 1.0.0.RELEASE + + + org.springframework.cloud + spring-cloud-gcp-starter-sql-mysql + 1.0.0.RELEASE + + + + ${project.name}-gcp + + + src/main/resources + + **/logback.xml + + + + + + com.google.cloud.tools + appengine-maven-plugin + 1.3.2 + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + cloudfoundry + + + + org.springframework.cloud + spring-cloud-dependencies + Greenwich.RELEASE + pom + import + + + + + + org.springframework.cloud + spring-cloud-starter + + + org.springframework.boot + spring-boot-starter-cloud-connectors + + + + ${project.name}-cf + + + src/main/resources + + **/logback.xml + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/config/*.java + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + thin-jar + + + + org.springframework.boot.experimental + spring-boot-thin-maven-plugin + ${thin.version} + + + + resolve + + resolve + + false + + + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/config/*.java + + + + + + + + 4.0.0 + + + diff --git a/spring-boot-bootstrap/src/main/appengine/app.yaml b/spring-boot-modules/spring-boot-bootstrap/src/main/appengine/app.yaml similarity index 100% rename from spring-boot-bootstrap/src/main/appengine/app.yaml rename to spring-boot-modules/spring-boot-bootstrap/src/main/appengine/app.yaml diff --git a/spring-boot-bootstrap/src/main/fabric8/deployment.yml b/spring-boot-modules/spring-boot-bootstrap/src/main/fabric8/deployment.yml similarity index 100% rename from spring-boot-bootstrap/src/main/fabric8/deployment.yml rename to spring-boot-modules/spring-boot-bootstrap/src/main/fabric8/deployment.yml diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/Application.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/Application.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/Application.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/cloud/config/CloudDataSourceConfig.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/cloud/config/CloudDataSourceConfig.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/cloud/config/CloudDataSourceConfig.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/cloud/config/CloudDataSourceConfig.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/repo/BookRepository.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/repo/BookRepository.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/persistence/repo/BookRepository.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/repo/BookRepository.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/web/BookController.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/web/BookController.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/web/BookController.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/web/BookController.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/web/RestExceptionHandler.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/web/RestExceptionHandler.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/web/RestExceptionHandler.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/web/RestExceptionHandler.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/web/SimpleController.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/web/SimpleController.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/web/SimpleController.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/web/SimpleController.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookIdMismatchException.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookIdMismatchException.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookIdMismatchException.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookIdMismatchException.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookNotFoundException.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookNotFoundException.java similarity index 100% rename from spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookNotFoundException.java rename to spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookNotFoundException.java diff --git a/spring-boot-bootstrap/src/main/resources/application-beanstalk.properties b/spring-boot-modules/spring-boot-bootstrap/src/main/resources/application-beanstalk.properties similarity index 100% rename from spring-boot-bootstrap/src/main/resources/application-beanstalk.properties rename to spring-boot-modules/spring-boot-bootstrap/src/main/resources/application-beanstalk.properties diff --git a/spring-boot-bootstrap/src/main/resources/application-gcp.properties b/spring-boot-modules/spring-boot-bootstrap/src/main/resources/application-gcp.properties similarity index 100% rename from spring-boot-bootstrap/src/main/resources/application-gcp.properties rename to spring-boot-modules/spring-boot-bootstrap/src/main/resources/application-gcp.properties diff --git a/spring-boot-bootstrap/src/main/resources/application-local.properties b/spring-boot-modules/spring-boot-bootstrap/src/main/resources/application-local.properties similarity index 100% rename from spring-boot-bootstrap/src/main/resources/application-local.properties rename to spring-boot-modules/spring-boot-bootstrap/src/main/resources/application-local.properties diff --git a/spring-boot-modules/spring-boot-bootstrap/src/main/resources/application-mysql.properties b/spring-boot-modules/spring-boot-bootstrap/src/main/resources/application-mysql.properties new file mode 100644 index 0000000000..069bf2e9d6 --- /dev/null +++ b/spring-boot-modules/spring-boot-bootstrap/src/main/resources/application-mysql.properties @@ -0,0 +1,4 @@ +spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect +spring.application.name = spring-boot-bootstrap +spring.datasource.username = ${SPRING_DATASOURCE_USER} +spring.datasource.password = ${SPRING_DATASOURCE_PASSWORD} \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/application.properties b/spring-boot-modules/spring-boot-bootstrap/src/main/resources/application.properties similarity index 100% rename from spring-boot-bootstrap/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-bootstrap/src/main/resources/application.properties diff --git a/spring-boot-bootstrap/src/main/resources/logback-gcp.xml b/spring-boot-modules/spring-boot-bootstrap/src/main/resources/logback-gcp.xml similarity index 100% rename from spring-boot-bootstrap/src/main/resources/logback-gcp.xml rename to spring-boot-modules/spring-boot-bootstrap/src/main/resources/logback-gcp.xml diff --git a/spring-boot-deployment/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-bootstrap/src/main/resources/logback.xml similarity index 100% rename from spring-boot-deployment/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-bootstrap/src/main/resources/logback.xml diff --git a/spring-boot-bootstrap/src/main/resources/spring-cloud-bootstrap.properties b/spring-boot-modules/spring-boot-bootstrap/src/main/resources/spring-cloud-bootstrap.properties similarity index 100% rename from spring-boot-bootstrap/src/main/resources/spring-cloud-bootstrap.properties rename to spring-boot-modules/spring-boot-bootstrap/src/main/resources/spring-cloud-bootstrap.properties diff --git a/spring-boot-bootstrap/src/main/resources/templates/error.html b/spring-boot-modules/spring-boot-bootstrap/src/main/resources/templates/error.html similarity index 100% rename from spring-boot-bootstrap/src/main/resources/templates/error.html rename to spring-boot-modules/spring-boot-bootstrap/src/main/resources/templates/error.html diff --git a/spring-boot-bootstrap/src/main/resources/templates/home.html b/spring-boot-modules/spring-boot-bootstrap/src/main/resources/templates/home.html similarity index 100% rename from spring-boot-bootstrap/src/main/resources/templates/home.html rename to spring-boot-modules/spring-boot-bootstrap/src/main/resources/templates/home.html diff --git a/spring-boot-bootstrap/src/test/java/com/baeldung/SpringBootBootstrapLiveTest.java b/spring-boot-modules/spring-boot-bootstrap/src/test/java/com/baeldung/SpringBootBootstrapLiveTest.java similarity index 100% rename from spring-boot-bootstrap/src/test/java/com/baeldung/SpringBootBootstrapLiveTest.java rename to spring-boot-modules/spring-boot-bootstrap/src/test/java/com/baeldung/SpringBootBootstrapLiveTest.java diff --git a/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-boot-camel/README.md b/spring-boot-modules/spring-boot-camel/README.md similarity index 100% rename from spring-boot-camel/README.md rename to spring-boot-modules/spring-boot-camel/README.md diff --git a/spring-boot-modules/spring-boot-camel/pom.xml b/spring-boot-modules/spring-boot-camel/pom.xml new file mode 100644 index 0000000000..7c1e28b3ee --- /dev/null +++ b/spring-boot-modules/spring-boot-camel/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + com.example + spring-boot-camel + 0.0.1-SNAPSHOT + spring-boot-camel + + + com.baeldung.spring-boot-modules + spring-boot-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} + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot-starter.version} + test + + + + + 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/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java b/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java similarity index 100% rename from spring-boot-camel/src/main/java/com/baeldung/camel/Application.java rename to spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java diff --git a/spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java b/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java similarity index 100% rename from spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java rename to spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java diff --git a/spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java b/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java similarity index 100% rename from spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java rename to spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java diff --git a/spring-boot-camel/src/main/resources/application.properties b/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties similarity index 100% rename from spring-boot-camel/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-camel/src/main/resources/application.properties diff --git a/spring-boot-camel/src/main/resources/application.yml b/spring-boot-modules/spring-boot-camel/src/main/resources/application.yml similarity index 100% rename from spring-boot-camel/src/main/resources/application.yml rename to spring-boot-modules/spring-boot-camel/src/main/resources/application.yml diff --git a/spring-boot-camel/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-camel/src/main/resources/logback.xml similarity index 100% rename from spring-boot-camel/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-camel/src/main/resources/logback.xml diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ce743e0f77 --- /dev/null +++ b/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.camel.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-cli/README.md b/spring-boot-modules/spring-boot-cli/README.md similarity index 100% rename from spring-boot-cli/README.md rename to spring-boot-modules/spring-boot-cli/README.md diff --git a/spring-boot-cli/bash/groovy.sh b/spring-boot-modules/spring-boot-cli/bash/groovy.sh similarity index 100% rename from spring-boot-cli/bash/groovy.sh rename to spring-boot-modules/spring-boot-cli/bash/groovy.sh diff --git a/spring-boot-cli/bash/setup.sh b/spring-boot-modules/spring-boot-cli/bash/setup.sh similarity index 100% rename from spring-boot-cli/bash/setup.sh rename to spring-boot-modules/spring-boot-cli/bash/setup.sh diff --git a/spring-boot-cli/groovy/data/DataConfig.groovy b/spring-boot-modules/spring-boot-cli/groovy/data/DataConfig.groovy similarity index 100% rename from spring-boot-cli/groovy/data/DataConfig.groovy rename to spring-boot-modules/spring-boot-cli/groovy/data/DataConfig.groovy diff --git a/spring-boot-cli/groovy/security/Security.groovy b/spring-boot-modules/spring-boot-cli/groovy/security/Security.groovy similarity index 100% rename from spring-boot-cli/groovy/security/Security.groovy rename to spring-boot-modules/spring-boot-cli/groovy/security/Security.groovy diff --git a/spring-boot-cli/groovy/test/Test.groovy b/spring-boot-modules/spring-boot-cli/groovy/test/Test.groovy similarity index 100% rename from spring-boot-cli/groovy/test/Test.groovy rename to spring-boot-modules/spring-boot-cli/groovy/test/Test.groovy diff --git a/spring-boot-cli/groovy/yml/Application.groovy b/spring-boot-modules/spring-boot-cli/groovy/yml/Application.groovy similarity index 100% rename from spring-boot-cli/groovy/yml/Application.groovy rename to spring-boot-modules/spring-boot-cli/groovy/yml/Application.groovy diff --git a/spring-boot-cli/groovy/yml/config/application.yml b/spring-boot-modules/spring-boot-cli/groovy/yml/config/application.yml similarity index 100% rename from spring-boot-cli/groovy/yml/config/application.yml rename to spring-boot-modules/spring-boot-cli/groovy/yml/config/application.yml diff --git a/spring-boot-client/.gitignore b/spring-boot-modules/spring-boot-client/.gitignore similarity index 100% rename from spring-boot-client/.gitignore rename to spring-boot-modules/spring-boot-client/.gitignore diff --git a/spring-boot-client/README.MD b/spring-boot-modules/spring-boot-client/README.MD similarity index 100% rename from spring-boot-client/README.MD rename to spring-boot-modules/spring-boot-client/README.MD diff --git a/spring-boot-modules/spring-boot-client/pom.xml b/spring-boot-modules/spring-boot-client/pom.xml new file mode 100644 index 0000000000..40a8690953 --- /dev/null +++ b/spring-boot-modules/spring-boot-client/pom.xml @@ -0,0 +1,141 @@ + + + 4.0.0 + spring-boot-client + 0.0.1-SNAPSHOT + spring-boot-client + war + This is simple boot client application for Spring boot actuator test + + + com.baeldung + parent-boot-2 + 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-libraries/src/main/java/com/baeldung/boot/Application.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/Application.java similarity index 100% rename from spring-boot-libraries/src/main/java/com/baeldung/boot/Application.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/Application.java diff --git a/spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/Details.java similarity index 93% rename from spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/Details.java index 1e3ddf7b21..c806476634 100644 --- a/spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/Details.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.client; +package com.baeldung.boot.client; public class Details { diff --git a/spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/DetailsServiceClient.java similarity index 93% rename from spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/DetailsServiceClient.java index f2b9d6d030..a9f1b08c97 100644 --- a/spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/DetailsServiceClient.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.client; +package com.baeldung.boot.client; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Service; diff --git a/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/Message.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/Message.java new file mode 100644 index 0000000000..19140f76a2 --- /dev/null +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/Message.java @@ -0,0 +1,24 @@ +package com.baeldung.websocket.client; + +public class Message { + + private String from; + private String text; + + public String getText() { + return text; + } + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public void setText(String text) { + this.text = text; + } + +} diff --git a/spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/MyStompSessionHandler.java similarity index 97% rename from spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/MyStompSessionHandler.java index 92beab9430..8ccc42c58a 100644 --- a/spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/MyStompSessionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.websocket.client; +package com.baeldung.websocket.client; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/StompClient.java similarity index 96% rename from spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/StompClient.java index 2bff07186d..04d87dd2ed 100644 --- a/spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/StompClient.java @@ -1,4 +1,4 @@ -package org.baeldung.websocket.client; +package com.baeldung.websocket.client; import java.util.Scanner; diff --git a/jackson/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-client/src/main/resources/logback.xml similarity index 100% rename from jackson/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-client/src/main/resources/logback.xml diff --git a/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1341f17eac --- /dev/null +++ b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import com.baeldung.boot.Application; +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(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/boot/client/DetailsServiceClientIntegrationTest.java similarity index 90% rename from spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java rename to spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/boot/client/DetailsServiceClientIntegrationTest.java index d423300b85..4af5370950 100644 --- a/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/boot/client/DetailsServiceClientIntegrationTest.java @@ -1,10 +1,12 @@ -package org.baeldung.boot.client; +package com.baeldung.boot.client; 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.Application; +import com.baeldung.boot.Application; +import com.baeldung.boot.client.Details; +import com.baeldung.boot.client.DetailsServiceClient; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java similarity index 92% rename from spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java rename to spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java index bb1b5e254e..57eec935f6 100644 --- a/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.websocket.client; -import org.baeldung.websocket.client.MyStompSessionHandler; import org.junit.Test; import org.mockito.Mockito; import org.springframework.messaging.simp.stomp.StompHeaders; diff --git a/spring-boot-config-jpa-error/README.md b/spring-boot-modules/spring-boot-config-jpa-error/README.md similarity index 100% rename from spring-boot-config-jpa-error/README.md rename to spring-boot-modules/spring-boot-config-jpa-error/README.md diff --git a/spring-boot-config-jpa-error/data-jpa-application/pom.xml b/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-application/pom.xml similarity index 100% rename from spring-boot-config-jpa-error/data-jpa-application/pom.xml rename to spring-boot-modules/spring-boot-config-jpa-error/data-jpa-application/pom.xml diff --git a/spring-boot-config-jpa-error/data-jpa-application/src/main/java/com/baeldung/data/jpa/ApplicationFound.java b/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-application/src/main/java/com/baeldung/data/jpa/ApplicationFound.java similarity index 100% rename from spring-boot-config-jpa-error/data-jpa-application/src/main/java/com/baeldung/data/jpa/ApplicationFound.java rename to spring-boot-modules/spring-boot-config-jpa-error/data-jpa-application/src/main/java/com/baeldung/data/jpa/ApplicationFound.java diff --git a/spring-boot-config-jpa-error/data-jpa-application/src/main/java/com/baeldung/data/jpa/application/ApplicationNotFound.java b/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-application/src/main/java/com/baeldung/data/jpa/application/ApplicationNotFound.java similarity index 100% rename from spring-boot-config-jpa-error/data-jpa-application/src/main/java/com/baeldung/data/jpa/application/ApplicationNotFound.java rename to spring-boot-modules/spring-boot-config-jpa-error/data-jpa-application/src/main/java/com/baeldung/data/jpa/application/ApplicationNotFound.java diff --git a/spring-boot-config-jpa-error/data-jpa-application/src/test/java/com/baeldung/data/jpa/DataJpaUnitTest.java b/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-application/src/test/java/com/baeldung/data/jpa/DataJpaUnitTest.java similarity index 100% rename from spring-boot-config-jpa-error/data-jpa-application/src/test/java/com/baeldung/data/jpa/DataJpaUnitTest.java rename to spring-boot-modules/spring-boot-config-jpa-error/data-jpa-application/src/test/java/com/baeldung/data/jpa/DataJpaUnitTest.java diff --git a/spring-boot-config-jpa-error/data-jpa-library/pom.xml b/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-library/pom.xml similarity index 100% rename from spring-boot-config-jpa-error/data-jpa-library/pom.xml rename to spring-boot-modules/spring-boot-config-jpa-error/data-jpa-library/pom.xml diff --git a/spring-boot-config-jpa-error/data-jpa-library/src/main/java/com/baeldung/data/jpa/libarary/model/Example.java b/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-library/src/main/java/com/baeldung/data/jpa/libarary/model/Example.java similarity index 100% rename from spring-boot-config-jpa-error/data-jpa-library/src/main/java/com/baeldung/data/jpa/libarary/model/Example.java rename to spring-boot-modules/spring-boot-config-jpa-error/data-jpa-library/src/main/java/com/baeldung/data/jpa/libarary/model/Example.java diff --git a/spring-boot-config-jpa-error/data-jpa-library/src/test/java/com/baeldung/data/jpa/TestApplication.java b/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-library/src/test/java/com/baeldung/data/jpa/TestApplication.java similarity index 100% rename from spring-boot-config-jpa-error/data-jpa-library/src/test/java/com/baeldung/data/jpa/TestApplication.java rename to spring-boot-modules/spring-boot-config-jpa-error/data-jpa-library/src/test/java/com/baeldung/data/jpa/TestApplication.java diff --git a/spring-boot-config-jpa-error/data-jpa-library/src/test/java/com/baeldung/data/jpa/libarary/DataJpaUnitTest.java b/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-library/src/test/java/com/baeldung/data/jpa/libarary/DataJpaUnitTest.java similarity index 100% rename from spring-boot-config-jpa-error/data-jpa-library/src/test/java/com/baeldung/data/jpa/libarary/DataJpaUnitTest.java rename to spring-boot-modules/spring-boot-config-jpa-error/data-jpa-library/src/test/java/com/baeldung/data/jpa/libarary/DataJpaUnitTest.java diff --git a/spring-boot-modules/spring-boot-config-jpa-error/pom.xml b/spring-boot-modules/spring-boot-config-jpa-error/pom.xml new file mode 100644 index 0000000000..f578957a1a --- /dev/null +++ b/spring-boot-modules/spring-boot-config-jpa-error/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + com.baeldung.spring-boot-config-jpa-error + spring-boot-config-jpa-error + 0.0.1-SNAPSHOT + pom + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2/pom.xml + + + + data-jpa-library + data-jpa-application + + + + + + 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-test + ${spring-boot.version} + test + + + + com.h2database + h2 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-boot-crud/README.md b/spring-boot-modules/spring-boot-crud/README.md similarity index 100% rename from spring-boot-crud/README.md rename to spring-boot-modules/spring-boot-crud/README.md diff --git a/spring-boot-modules/spring-boot-crud/pom.xml b/spring-boot-modules/spring-boot-crud/pom.xml new file mode 100644 index 0000000000..676d522f84 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + spring-boot-crud + spring-boot-crud + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-test + + + org.mockito + mockito-core + test + + + com.h2database + h2 + runtime + + + + + spring-boot-crud + + + src/main/resources + true + + + + + org.springframework.boot + spring-boot-maven-plugin + + exec + + + + org.apache.maven.plugins + maven-assembly-plugin + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + + + + UTF-8 + + + diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/Application.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/Application.java new file mode 100644 index 0000000000..a56a2a04c0 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/Application.java @@ -0,0 +1,23 @@ +package com.baeldung.crud; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +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.crud"}) +@EnableJpaRepositories(basePackages="com.baeldung.crud.repositories") +@EnableTransactionManagement +@EntityScan(basePackages="com.baeldung.crud.entities") +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/controllers/UserController.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/controllers/UserController.java new file mode 100644 index 0000000000..726be6a384 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/controllers/UserController.java @@ -0,0 +1,68 @@ +package com.baeldung.crud.controllers; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; + +import com.baeldung.crud.entities.User; +import com.baeldung.crud.repositories.UserRepository; + +@Controller +public class UserController { + + private final UserRepository userRepository; + + @Autowired + public UserController(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @GetMapping("/signup") + public String showSignUpForm(User user) { + return "add-user"; + } + + @PostMapping("/adduser") + public String addUser(@Valid User user, BindingResult result, Model model) { + if (result.hasErrors()) { + return "add-user"; + } + + userRepository.save(user); + model.addAttribute("users", userRepository.findAll()); + return "index"; + } + + @GetMapping("/edit/{id}") + public String showUpdateForm(@PathVariable("id") long id, Model model) { + User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); + model.addAttribute("user", user); + return "update-user"; + } + + @PostMapping("/update/{id}") + public String updateUser(@PathVariable("id") long id, @Valid User user, BindingResult result, Model model) { + if (result.hasErrors()) { + user.setId(id); + return "update-user"; + } + + userRepository.save(user); + model.addAttribute("users", userRepository.findAll()); + return "index"; + } + + @GetMapping("/delete/{id}") + public String deleteUser(@PathVariable("id") long id, Model model) { + User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); + userRepository.delete(user); + model.addAttribute("users", userRepository.findAll()); + return "index"; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/entities/User.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/entities/User.java new file mode 100644 index 0000000000..372327532f --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/entities/User.java @@ -0,0 +1,56 @@ +package com.baeldung.crud.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.validation.constraints.NotBlank; + +@Entity +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + @NotBlank(message = "Name is mandatory") + private String name; + + @NotBlank(message = "Email is mandatory") + private String email; + + public User() {} + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public void setId(long id) { + this.id = id; + } + + public long getId() { + return id; + } + + public void setName(String name) { + this.name = name; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/repositories/UserRepository.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/repositories/UserRepository.java new file mode 100644 index 0000000000..c17ebc56ba --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/repositories/UserRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.crud.repositories; + +import com.baeldung.crud.entities.User; +import java.util.List; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends CrudRepository { + + List findByName(String name); + +} diff --git a/spring-boot-crud/src/main/resources/css/shards.min.css b/spring-boot-modules/spring-boot-crud/src/main/resources/css/shards.min.css similarity index 100% rename from spring-boot-crud/src/main/resources/css/shards.min.css rename to spring-boot-modules/spring-boot-crud/src/main/resources/css/shards.min.css diff --git a/spring-boot-crud/src/main/resources/templates/add-user.html b/spring-boot-modules/spring-boot-crud/src/main/resources/templates/add-user.html similarity index 100% rename from spring-boot-crud/src/main/resources/templates/add-user.html rename to spring-boot-modules/spring-boot-crud/src/main/resources/templates/add-user.html diff --git a/spring-boot-crud/src/main/resources/templates/index.html b/spring-boot-modules/spring-boot-crud/src/main/resources/templates/index.html similarity index 100% rename from spring-boot-crud/src/main/resources/templates/index.html rename to spring-boot-modules/spring-boot-crud/src/main/resources/templates/index.html diff --git a/spring-boot-crud/src/main/resources/templates/update-user.html b/spring-boot-modules/spring-boot-crud/src/main/resources/templates/update-user.html similarity index 100% rename from spring-boot-crud/src/main/resources/templates/update-user.html rename to spring-boot-modules/spring-boot-crud/src/main/resources/templates/update-user.html diff --git a/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java similarity index 97% rename from spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java rename to spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java index 2de0828ae5..033108c195 100644 --- a/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java @@ -1,83 +1,83 @@ -package com.baeldung.crud; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; - -import com.baeldung.crud.controllers.UserController; -import com.baeldung.crud.entities.User; -import com.baeldung.crud.repositories.UserRepository; - -public class UserControllerUnitTest { - - private static UserController userController; - private static UserRepository mockedUserRepository; - private static BindingResult mockedBindingResult; - private static Model mockedModel; - - @BeforeClass - public static void setUpUserControllerInstance() { - mockedUserRepository = mock(UserRepository.class); - mockedBindingResult = mock(BindingResult.class); - mockedModel = mock(Model.class); - userController = new UserController(mockedUserRepository); - } - - @Test - public void whenCalledshowSignUpForm_thenCorrect() { - User user = new User("John", "john@domain.com"); - - assertThat(userController.showSignUpForm(user)).isEqualTo("add-user"); - } - - @Test - public void whenCalledaddUserAndValidUser_thenCorrect() { - User user = new User("John", "john@domain.com"); - - when(mockedBindingResult.hasErrors()).thenReturn(false); - - assertThat(userController.addUser(user, mockedBindingResult, mockedModel)).isEqualTo("index"); - } - - @Test - public void whenCalledaddUserAndInValidUser_thenCorrect() { - User user = new User("John", "john@domain.com"); - - when(mockedBindingResult.hasErrors()).thenReturn(true); - - assertThat(userController.addUser(user, mockedBindingResult, mockedModel)).isEqualTo("add-user"); - } - - @Test(expected = IllegalArgumentException.class) - public void whenCalledshowUpdateForm_thenIllegalArgumentException() { - assertThat(userController.showUpdateForm(0, mockedModel)).isEqualTo("update-user"); - } - - @Test - public void whenCalledupdateUserAndValidUser_thenCorrect() { - User user = new User("John", "john@domain.com"); - - when(mockedBindingResult.hasErrors()).thenReturn(false); - - assertThat(userController.updateUser(1l, user, mockedBindingResult, mockedModel)).isEqualTo("index"); - } - - @Test - public void whenCalledupdateUserAndInValidUser_thenCorrect() { - User user = new User("John", "john@domain.com"); - - when(mockedBindingResult.hasErrors()).thenReturn(true); - - assertThat(userController.updateUser(1l, user, mockedBindingResult, mockedModel)).isEqualTo("update-user"); - } - - @Test(expected = IllegalArgumentException.class) - public void whenCalleddeleteUser_thenIllegalArgumentException() { - assertThat(userController.deleteUser(1l, mockedModel)).isEqualTo("index"); - } -} +package com.baeldung.crud; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; + +import com.baeldung.crud.controllers.UserController; +import com.baeldung.crud.entities.User; +import com.baeldung.crud.repositories.UserRepository; + +public class UserControllerUnitTest { + + private static UserController userController; + private static UserRepository mockedUserRepository; + private static BindingResult mockedBindingResult; + private static Model mockedModel; + + @BeforeClass + public static void setUpUserControllerInstance() { + mockedUserRepository = mock(UserRepository.class); + mockedBindingResult = mock(BindingResult.class); + mockedModel = mock(Model.class); + userController = new UserController(mockedUserRepository); + } + + @Test + public void whenCalledshowSignUpForm_thenCorrect() { + User user = new User("John", "john@domain.com"); + + assertThat(userController.showSignUpForm(user)).isEqualTo("add-user"); + } + + @Test + public void whenCalledaddUserAndValidUser_thenCorrect() { + User user = new User("John", "john@domain.com"); + + when(mockedBindingResult.hasErrors()).thenReturn(false); + + assertThat(userController.addUser(user, mockedBindingResult, mockedModel)).isEqualTo("index"); + } + + @Test + public void whenCalledaddUserAndInValidUser_thenCorrect() { + User user = new User("John", "john@domain.com"); + + when(mockedBindingResult.hasErrors()).thenReturn(true); + + assertThat(userController.addUser(user, mockedBindingResult, mockedModel)).isEqualTo("add-user"); + } + + @Test(expected = IllegalArgumentException.class) + public void whenCalledshowUpdateForm_thenIllegalArgumentException() { + assertThat(userController.showUpdateForm(0, mockedModel)).isEqualTo("update-user"); + } + + @Test + public void whenCalledupdateUserAndValidUser_thenCorrect() { + User user = new User("John", "john@domain.com"); + + when(mockedBindingResult.hasErrors()).thenReturn(false); + + assertThat(userController.updateUser(1l, user, mockedBindingResult, mockedModel)).isEqualTo("index"); + } + + @Test + public void whenCalledupdateUserAndInValidUser_thenCorrect() { + User user = new User("John", "john@domain.com"); + + when(mockedBindingResult.hasErrors()).thenReturn(true); + + assertThat(userController.updateUser(1l, user, mockedBindingResult, mockedModel)).isEqualTo("update-user"); + } + + @Test(expected = IllegalArgumentException.class) + public void whenCalleddeleteUser_thenIllegalArgumentException() { + assertThat(userController.deleteUser(1l, mockedModel)).isEqualTo("index"); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/crud/UserUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/crud/UserUnitTest.java new file mode 100644 index 0000000000..3e33e868ad --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/crud/UserUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.crud; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +import com.baeldung.crud.entities.User; + +public class UserUnitTest { + + @Test + public void whenCalledGetName_thenCorrect() { + User user = new User("Julie", "julie@domain.com"); + + assertThat(user.getName()).isEqualTo("Julie"); + } + + @Test + public void whenCalledGetEmail_thenCorrect() { + User user = new User("Julie", "julie@domain.com"); + + assertThat(user.getEmail()).isEqualTo("julie@domain.com"); + } + + @Test + public void whenCalledSetName_thenCorrect() { + User user = new User("Julie", "julie@domain.com"); + + user.setName("John"); + + assertThat(user.getName()).isEqualTo("John"); + } + + @Test + public void whenCalledSetEmail_thenCorrect() { + User user = new User("Julie", "julie@domain.com"); + + user.setEmail("john@domain.com"); + + assertThat(user.getEmail()).isEqualTo("john@domain.com"); + } + + @Test + public void whenCalledtoString_thenCorrect() { + User user = new User("Julie", "julie@domain.com"); + assertThat(user.toString()).isEqualTo("User{id=0, name=Julie, email=julie@domain.com}"); + } +} diff --git a/spring-boot-ctx-fluent/README.md b/spring-boot-modules/spring-boot-ctx-fluent/README.md similarity index 100% rename from spring-boot-ctx-fluent/README.md rename to spring-boot-modules/spring-boot-ctx-fluent/README.md diff --git a/spring-boot-modules/spring-boot-ctx-fluent/pom.xml b/spring-boot-modules/spring-boot-ctx-fluent/pom.xml new file mode 100644 index 0000000000..872e15d307 --- /dev/null +++ b/spring-boot-modules/spring-boot-ctx-fluent/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + spring-boot-ctx-fluent + 0.0.1-SNAPSHOT + spring-boot-ctx-fluent + jar + + + com.baeldung + parent-boot-2 + 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-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java similarity index 100% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java b/spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java similarity index 100% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java b/spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java similarity index 100% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java b/spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java similarity index 100% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java b/spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java similarity index 100% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java b/spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java similarity index 100% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java b/spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java similarity index 100% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java b/spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java similarity index 100% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java b/spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java similarity index 100% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java diff --git a/spring-boot-ctx-fluent/src/main/resources/ctx1.properties b/spring-boot-modules/spring-boot-ctx-fluent/src/main/resources/ctx1.properties similarity index 100% rename from spring-boot-ctx-fluent/src/main/resources/ctx1.properties rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/resources/ctx1.properties diff --git a/spring-boot-ctx-fluent/src/main/resources/ctx2.properties b/spring-boot-modules/spring-boot-ctx-fluent/src/main/resources/ctx2.properties similarity index 100% rename from spring-boot-ctx-fluent/src/main/resources/ctx2.properties rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/resources/ctx2.properties diff --git a/spring-boot-environment/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-ctx-fluent/src/main/resources/logback.xml similarity index 100% rename from spring-boot-environment/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-ctx-fluent/src/main/resources/logback.xml diff --git a/spring-boot-modules/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ca8989724b --- /dev/null +++ b/spring-boot-modules/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.junit.Test; + +import com.baeldung.parent.App; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + App.main(new String[] {}); + } +} diff --git a/spring-boot-modules/spring-boot-custom-starter/README.md b/spring-boot-modules/spring-boot-custom-starter/README.md new file mode 100644 index 0000000000..667be7ca40 --- /dev/null +++ b/spring-boot-modules/spring-boot-custom-starter/README.md @@ -0,0 +1,16 @@ +## Spring Boot Custom Starter + +This module contains articles about writing Spring Boot Starters. + +### Relevant Articles: +- [Creating a Custom Starter with Spring Boot](https://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](https://www.baeldung.com/spring-boot-multiple-modules) diff --git a/spring-boot-custom-starter/greeter-library/README.md b/spring-boot-modules/spring-boot-custom-starter/greeter-library/README.md similarity index 100% rename from spring-boot-custom-starter/greeter-library/README.md rename to spring-boot-modules/spring-boot-custom-starter/greeter-library/README.md diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-library/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-library/pom.xml new file mode 100644 index 0000000000..34cc530f2f --- /dev/null +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-library/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + greeter-library + 0.0.1-SNAPSHOT + greeter-library + + + com.baeldung.spring-boot-modules + spring-boot-custom-starter + 0.0.1-SNAPSHOT + + + \ No newline at end of file diff --git a/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/Greeter.java b/spring-boot-modules/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/Greeter.java similarity index 100% rename from spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/Greeter.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/Greeter.java diff --git a/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreeterConfigParams.java b/spring-boot-modules/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreeterConfigParams.java similarity index 100% rename from spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreeterConfigParams.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreeterConfigParams.java diff --git a/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreetingConfig.java b/spring-boot-modules/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreetingConfig.java similarity index 100% rename from spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreetingConfig.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreetingConfig.java diff --git a/spring-boot-gradle/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-library/src/main/resources/logback.xml similarity index 100% rename from spring-boot-gradle/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-custom-starter/greeter-library/src/main/resources/logback.xml diff --git a/spring-boot-custom-starter/greeter-library/src/test/java/com/baeldung/greeter/GreeterIntegrationTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-library/src/test/java/com/baeldung/greeter/GreeterIntegrationTest.java similarity index 100% rename from spring-boot-custom-starter/greeter-library/src/test/java/com/baeldung/greeter/GreeterIntegrationTest.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-library/src/test/java/com/baeldung/greeter/GreeterIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml new file mode 100644 index 0000000000..532f45cf3e --- /dev/null +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml @@ -0,0 +1,70 @@ + + + 4.0.0 + greeter-spring-boot-autoconfigure + 0.0.1-SNAPSHOT + greeter-spring-boot-autoconfigure + + + com.baeldung.spring-boot-modules + spring-boot-custom-starter + 0.0.1-SNAPSHOT + + + + + org.springframework.boot + spring-boot + ${spring-boot.version} + + + + org.springframework.boot + spring-boot-autoconfigure + ${spring-boot.version} + + + + org.springframework.boot + spring-boot-configuration-processor + ${spring-boot.version} + true + + + + com.baeldung.spring-boot-modules + greeter-library + ${greeter.version} + true + + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + + + + UTF-8 + 2.2.6.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-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/java/com/baeldung/greeter/autoconfigure/GreeterAutoConfiguration.java similarity index 100% rename from spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/java/com/baeldung/greeter/autoconfigure/GreeterAutoConfiguration.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/java/com/baeldung/greeter/autoconfigure/GreeterAutoConfiguration.java diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/java/com/baeldung/greeter/autoconfigure/GreeterProperties.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/java/com/baeldung/greeter/autoconfigure/GreeterProperties.java similarity index 100% rename from spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/java/com/baeldung/greeter/autoconfigure/GreeterProperties.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/java/com/baeldung/greeter/autoconfigure/GreeterProperties.java diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories diff --git a/spring-boot-jasypt/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/resources/logback.xml similarity index 100% rename from spring-boot-jasypt/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/resources/logback.xml diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b4668e7d2b --- /dev/null +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.greeter.autoconfigure.GreeterAutoConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = GreeterAutoConfiguration.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml new file mode 100644 index 0000000000..8d328b88be --- /dev/null +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + greeter-spring-boot-sample-app + 0.0.1-SNAPSHOT + greeter-spring-boot-sample-app + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../../parent-boot-2 + + + + + com.baeldung.spring-boot-modules + greeter-spring-boot-starter + ${greeter-starter.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + + + + + + 0.0.1-SNAPSHOT + + + diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java similarity index 100% rename from spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/resources/application.properties b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/resources/application.properties similarity index 100% rename from spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/resources/application.properties diff --git a/spring-boot-keycloak/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/resources/logback.xml similarity index 100% rename from spring-boot-keycloak/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/resources/logback.xml diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7103da97f3 --- /dev/null +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.greeter.sample.GreeterSampleApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GreeterSampleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java similarity index 100% rename from spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml new file mode 100644 index 0000000000..0e8fb4cbc9 --- /dev/null +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + greeter-spring-boot-starter + 0.0.1-SNAPSHOT + greeter-spring-boot-starter + + + com.baeldung.spring-boot-modules + spring-boot-custom-starter + 0.0.1-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-starter + ${spring-boot.version} + + + + com.baeldung.spring-boot-modules + greeter-spring-boot-autoconfigure + ${project.version} + + + + com.baeldung.spring-boot-modules + greeter-library + ${greeter.version} + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + + + + UTF-8 + 0.0.1-SNAPSHOT + 2.2.6.RELEASE + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml new file mode 100644 index 0000000000..47296990aa --- /dev/null +++ b/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + greeter + 0.0.1-SNAPSHOT + greeter + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../../parent-boot-2 + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-custom-starter/pom.xml b/spring-boot-modules/spring-boot-custom-starter/pom.xml new file mode 100644 index 0000000000..596b993f81 --- /dev/null +++ b/spring-boot-modules/spring-boot-custom-starter/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + spring-boot-custom-starter + 0.0.1-SNAPSHOT + spring-boot-custom-starter + pom + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + + + + greeter-library + greeter-spring-boot-autoconfigure + greeter-spring-boot-starter + greeter-spring-boot-sample-app + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data/README.md b/spring-boot-modules/spring-boot-data/README.md new file mode 100644 index 0000000000..faa38d475e --- /dev/null +++ b/spring-boot-modules/spring-boot-data/README.md @@ -0,0 +1,12 @@ +## Spring Boot Data + +This module contains articles about Spring Boot with Spring Data + +## Relevant Articles: + +- [Formatting JSON Dates in Spring Boot](https://www.baeldung.com/spring-boot-formatting-json-dates) +- [Rendering Exceptions in JSON with Spring](https://www.baeldung.com/spring-exceptions-json) +- [Disable Spring Data Auto Configuration](https://www.baeldung.com/spring-data-disable-auto-config) +- [Repositories with Multiple Spring Data Modules](https://www.baeldung.com/spring-multiple-data-modules) +- [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) +- [Using @JsonComponent in Spring Boot](https://www.baeldung.com/spring-boot-jsoncomponent) diff --git a/spring-boot-modules/spring-boot-data/pom.xml b/spring-boot-modules/spring-boot-data/pom.xml new file mode 100644 index 0000000000..f25b4ee472 --- /dev/null +++ b/spring-boot-modules/spring-boot-data/pom.xml @@ -0,0 +1,175 @@ + + + 4.0.0 + spring-boot-data + spring-boot-data + war + Spring Boot Data Module + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.javers + javers-spring-boot-starter-sql + ${javers.version} + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + ${h2.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + + + spring-boot-data + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-war-plugin + + + pl.project13.maven + git-commit-id-plugin + ${git-commit-id-plugin.version} + + + get-the-git-infos + + revision + + initialize + + + validate-the-git-infos + + validateRevision + + package + + + + true + ${project.build.outputDirectory}/git.properties + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${source.version} + ${target.version} + + + + + + + + autoconfiguration + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.javers.SpringBootJaVersApplication + JAR + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${source.version} + ${target.version} + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${source.version} + ${target.version} + + + + + + + + + 5.6.3 + 2.2.4 + 1.8 + 1.8 + + + diff --git a/spring-boot-data/src/main/java/com/baeldung/SpringBootDataApplication.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/SpringBootDataApplication.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/SpringBootDataApplication.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/SpringBootDataApplication.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/User.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/User.java new file mode 100644 index 0000000000..ca22dc57ea --- /dev/null +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/User.java @@ -0,0 +1,15 @@ +package com.baeldung.boot.jsoncomponent; + +import javafx.scene.paint.Color; + +public class User { + private final Color favoriteColor; + + public User(Color favoriteColor) { + this.favoriteColor = favoriteColor; + } + + public Color getFavoriteColor() { + return favoriteColor; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserCombinedSerializer.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/UserCombinedSerializer.java similarity index 97% rename from spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserCombinedSerializer.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/UserCombinedSerializer.java index f4d7505342..d0a14da1f2 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserCombinedSerializer.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/UserCombinedSerializer.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.jsoncomponent; +package com.baeldung.boot.jsoncomponent; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; diff --git a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializer.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/UserJsonDeserializer.java similarity index 95% rename from spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializer.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/UserJsonDeserializer.java index f7bd822c8a..05b1cb10a0 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializer.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/UserJsonDeserializer.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.jsoncomponent; +package com.baeldung.boot.jsoncomponent; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; diff --git a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonSerializer.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/UserJsonSerializer.java similarity index 96% rename from spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonSerializer.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/UserJsonSerializer.java index 03330d81a4..1df37728ba 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonSerializer.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jsoncomponent/UserJsonSerializer.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.jsoncomponent; +package com.baeldung.boot.jsoncomponent; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/README.md b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/README.md similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/README.md rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/README.md diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/config/JaversConfiguration.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/config/JaversConfiguration.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/config/JaversConfiguration.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/config/JaversConfiguration.java diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/domain/Address.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Address.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/domain/Address.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Address.java diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/domain/Product.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Product.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/domain/Product.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Product.java diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/domain/Store.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Store.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/domain/Store.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Store.java diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/repo/ProductRepository.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/ProductRepository.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/repo/ProductRepository.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/ProductRepository.java diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/repo/StoreRepository.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/StoreRepository.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/repo/StoreRepository.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/StoreRepository.java diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/service/StoreService.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/service/StoreService.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/service/StoreService.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/service/StoreService.java diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/web/StoreController.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/StoreController.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/web/StoreController.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/StoreController.java diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java diff --git a/spring-boot-data/src/main/java/com/baeldung/jsondateformat/Contact.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/Contact.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/jsondateformat/Contact.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/Contact.java diff --git a/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactApp.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactApp.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactApp.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactApp.java diff --git a/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java diff --git a/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactController.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactController.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactController.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactController.java diff --git a/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java diff --git a/spring-boot-data/src/main/java/com/baeldung/jsondateformat/PlainContact.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/PlainContact.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/jsondateformat/PlainContact.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/PlainContact.java diff --git a/spring-boot-data/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java diff --git a/spring-boot-data/src/main/java/com/baeldung/jsonexception/CustomException.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsonexception/CustomException.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/jsonexception/CustomException.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsonexception/CustomException.java diff --git a/spring-boot-data/src/main/java/com/baeldung/jsonexception/ErrorHandler.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsonexception/ErrorHandler.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/jsonexception/ErrorHandler.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsonexception/ErrorHandler.java diff --git a/spring-boot-data/src/main/java/com/baeldung/jsonexception/MainController.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsonexception/MainController.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/jsonexception/MainController.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/jsonexception/MainController.java diff --git a/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java diff --git a/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java diff --git a/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java diff --git a/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java diff --git a/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java diff --git a/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java similarity index 100% rename from spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java diff --git a/spring-boot-data/src/main/resources/application.properties b/spring-boot-modules/spring-boot-data/src/main/resources/application.properties similarity index 100% rename from spring-boot-data/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-data/src/main/resources/application.properties diff --git a/spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializerIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jsoncomponent/UserJsonDeserializerIntegrationTest.java similarity index 89% rename from spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializerIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jsoncomponent/UserJsonDeserializerIntegrationTest.java index f8b47a23fc..868d40c38b 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jsoncomponent/UserJsonDeserializerIntegrationTest.java @@ -1,9 +1,9 @@ -package org.baeldung.boot.jsoncomponent; +package com.baeldung.boot.jsoncomponent; +import com.baeldung.boot.jsoncomponent.User; import com.fasterxml.jackson.databind.ObjectMapper; import javafx.scene.paint.Color; -import org.baeldung.boot.jsoncomponent.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonSerializerIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jsoncomponent/UserJsonSerializerIntegrationTest.java similarity index 90% rename from spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonSerializerIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jsoncomponent/UserJsonSerializerIntegrationTest.java index 060374e8fa..aef99921a5 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/jsoncomponent/UserJsonSerializerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jsoncomponent/UserJsonSerializerIntegrationTest.java @@ -1,5 +1,6 @@ -package org.baeldung.boot.jsoncomponent; +package com.baeldung.boot.jsoncomponent; +import com.baeldung.boot.jsoncomponent.User; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import javafx.scene.paint.Color; @@ -11,8 +12,6 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertEquals; -import org.baeldung.boot.jsoncomponent.User; - @JsonTest @RunWith(SpringRunner.class) public class UserJsonSerializerIntegrationTest { diff --git a/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java similarity index 100% rename from spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java diff --git a/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java similarity index 100% rename from spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java diff --git a/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java similarity index 100% rename from spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java diff --git a/spring-boot-data/src/test/java/com/baeldung/jsondateformat/ContactAppIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/jsondateformat/ContactAppIntegrationTest.java similarity index 100% rename from spring-boot-data/src/test/java/com/baeldung/jsondateformat/ContactAppIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/jsondateformat/ContactAppIntegrationTest.java diff --git a/spring-boot-data/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerIntegrationTest.java similarity index 100% rename from spring-boot-data/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerIntegrationTest.java diff --git a/spring-boot-data/src/test/java/com/baeldung/jsonexception/MainControllerIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/jsonexception/MainControllerIntegrationTest.java similarity index 100% rename from spring-boot-data/src/test/java/com/baeldung/jsonexception/MainControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/jsonexception/MainControllerIntegrationTest.java diff --git a/spring-boot-data/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java similarity index 100% rename from spring-boot-data/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java diff --git a/spring-boot-vue/src/main/resources/application.properties b/spring-boot-modules/spring-boot-data/src/test/resources/application.properties similarity index 100% rename from spring-boot-vue/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-data/src/test/resources/application.properties diff --git a/spring-boot-deployment/README.md b/spring-boot-modules/spring-boot-deployment/README.md similarity index 100% rename from spring-boot-deployment/README.md rename to spring-boot-modules/spring-boot-deployment/README.md diff --git a/spring-boot-modules/spring-boot-deployment/pom.xml b/spring-boot-modules/spring-boot-deployment/pom.xml new file mode 100644 index 0000000000..b3fc3eabd1 --- /dev/null +++ b/spring-boot-modules/spring-boot-deployment/pom.xml @@ -0,0 +1,203 @@ + + + 4.0.0 + spring-boot-deployment + spring-boot-deployment + war + Demo project for Spring Boot + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + provided + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + 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} + + + + org.springframework.cloud + spring-cloud-context + ${springcloud.version} + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + + + + ${project.artifactId} + + + src/main/resources + true + + **/conf.properties + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.baeldung.webjar.WebjarsdemoApplication + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 2.18 + + + + integration-tests + + integration-test + verify + + + + + **/ExternalPropertyFileLoaderIntegrationTest.java + + + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + + com.baeldung.boot.Application + 3.1.1 + 3.3.7-1 + 2.2 + 18.0 + 3.1.7 + 2.0.2.RELEASE + 4.5.8 + + + diff --git a/spring-boot-deployment/src/main/java/com/baeldung/compare/ComparisonApplication.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/compare/ComparisonApplication.java similarity index 100% rename from spring-boot-deployment/src/main/java/com/baeldung/compare/ComparisonApplication.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/compare/ComparisonApplication.java diff --git a/spring-boot-deployment/src/main/java/com/baeldung/compare/StartupEventHandler.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/compare/StartupEventHandler.java similarity index 100% rename from spring-boot-deployment/src/main/java/com/baeldung/compare/StartupEventHandler.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/compare/StartupEventHandler.java diff --git a/spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/GracefulShutdownApplication.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/GracefulShutdownApplication.java similarity index 100% rename from spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/GracefulShutdownApplication.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/GracefulShutdownApplication.java diff --git a/spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/beans/LongRunningProcessBean.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/beans/LongRunningProcessBean.java similarity index 100% rename from spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/beans/LongRunningProcessBean.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/beans/LongRunningProcessBean.java diff --git a/spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/config/SpringConfiguration.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/config/SpringConfiguration.java similarity index 100% rename from spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/config/SpringConfiguration.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/gracefulshutdown/config/SpringConfiguration.java diff --git a/spring-boot-deployment/src/main/java/com/baeldung/springbootconfiguration/SpringBootConfigurationApplication.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/springbootconfiguration/SpringBootConfigurationApplication.java similarity index 100% rename from spring-boot-deployment/src/main/java/com/baeldung/springbootconfiguration/SpringBootConfigurationApplication.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/springbootconfiguration/SpringBootConfigurationApplication.java diff --git a/spring-boot-deployment/src/main/java/com/baeldung/springbootconfiguration/controller/GreetingsController.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/springbootconfiguration/controller/GreetingsController.java similarity index 100% rename from spring-boot-deployment/src/main/java/com/baeldung/springbootconfiguration/controller/GreetingsController.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/springbootconfiguration/controller/GreetingsController.java diff --git a/spring-boot-deployment/src/main/java/com/baeldung/springbootnonwebapp/SpringBootConsoleApplication.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/springbootnonwebapp/SpringBootConsoleApplication.java similarity index 100% rename from spring-boot-deployment/src/main/java/com/baeldung/springbootnonwebapp/SpringBootConsoleApplication.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/springbootnonwebapp/SpringBootConsoleApplication.java diff --git a/spring-boot-deployment/src/main/java/com/baeldung/springbootsimple/SpringBootTomcatApplication.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/springbootsimple/SpringBootTomcatApplication.java similarity index 100% rename from spring-boot-deployment/src/main/java/com/baeldung/springbootsimple/SpringBootTomcatApplication.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/springbootsimple/SpringBootTomcatApplication.java diff --git a/spring-boot-deployment/src/main/java/com/baeldung/springbootsimple/TomcatController.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/springbootsimple/TomcatController.java similarity index 100% rename from spring-boot-deployment/src/main/java/com/baeldung/springbootsimple/TomcatController.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/springbootsimple/TomcatController.java diff --git a/spring-boot-deployment/src/main/resources/application.properties b/spring-boot-modules/spring-boot-deployment/src/main/resources/application.properties similarity index 100% rename from spring-boot-deployment/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-deployment/src/main/resources/application.properties diff --git a/spring-boot-kotlin/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-deployment/src/main/resources/logback.xml similarity index 100% rename from spring-boot-kotlin/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-deployment/src/main/resources/logback.xml diff --git a/spring-boot-deployment/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java b/spring-boot-modules/spring-boot-deployment/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java similarity index 100% rename from spring-boot-deployment/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java rename to spring-boot-modules/spring-boot-deployment/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java diff --git a/spring-boot-deployment/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-deployment/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java similarity index 100% rename from spring-boot-deployment/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-deployment/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java diff --git a/spring-boot-di/README.MD b/spring-boot-modules/spring-boot-di/README.MD similarity index 100% rename from spring-boot-di/README.MD rename to spring-boot-modules/spring-boot-di/README.MD diff --git a/spring-boot-modules/spring-boot-di/pom.xml b/spring-boot-modules/spring-boot-di/pom.xml new file mode 100644 index 0000000000..b24e4a9037 --- /dev/null +++ b/spring-boot-modules/spring-boot-di/pom.xml @@ -0,0 +1,64 @@ + + + 4.0.0 + spring-boot-di + spring-boot-di + jar + Module For Spring Boot DI + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.aspectj + aspectjweaver + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.SpringBootDiApplication + JAR + + + + + + + com.baeldung.SpringBootDiApplication + + + diff --git a/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/ExampleBean.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/ExampleBean.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/ExampleBean.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/ExampleBean.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/Animal.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/Animal.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/Animal.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/Animal.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/ComponentScanAnnotationFilterApp.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/ComponentScanAnnotationFilterApp.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/ComponentScanAnnotationFilterApp.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/ComponentScanAnnotationFilterApp.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/Elephant.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/Elephant.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/Elephant.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/filter/annotation/Elephant.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java diff --git a/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java similarity index 100% rename from spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java diff --git a/spring-boot-environment/README.md b/spring-boot-modules/spring-boot-environment/README.md similarity index 100% rename from spring-boot-environment/README.md rename to spring-boot-modules/spring-boot-environment/README.md diff --git a/spring-boot-modules/spring-boot-environment/pom.xml b/spring-boot-modules/spring-boot-environment/pom.xml new file mode 100644 index 0000000000..138c59847d --- /dev/null +++ b/spring-boot-modules/spring-boot-environment/pom.xml @@ -0,0 +1,148 @@ + + + 4.0.0 + spring-boot-environment + spring-boot-environment + war + Demo project for Spring Boot + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + provided + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + 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.springframework.cloud + spring-cloud-context + ${springcloud.version} + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + + + + ${project.artifactId} + + + src/main/resources + true + + **/conf.properties + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + 2.2 + 18.0 + 3.1.7 + 2.0.2.RELEASE + 4.5.8 + + + diff --git a/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java similarity index 100% rename from spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java rename to spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java diff --git a/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java similarity index 100% rename from spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java rename to spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java diff --git a/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java similarity index 100% rename from spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java rename to spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java diff --git a/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java similarity index 100% rename from spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java rename to spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java diff --git a/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java similarity index 100% rename from spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java rename to spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java diff --git a/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java similarity index 100% rename from spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java rename to spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java diff --git a/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java similarity index 100% rename from spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java rename to spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java diff --git a/spring-boot-environment/src/main/java/com/baeldung/properties/ConfProperties.java b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/properties/ConfProperties.java similarity index 100% rename from spring-boot-environment/src/main/java/com/baeldung/properties/ConfProperties.java rename to spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/properties/ConfProperties.java diff --git a/spring-boot-environment/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java similarity index 100% rename from spring-boot-environment/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java rename to spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java diff --git a/spring-boot-environment/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java similarity index 100% rename from spring-boot-environment/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java rename to spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java diff --git a/spring-boot-environment/src/main/resources/META-INF/spring.factories b/spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-boot-environment/src/main/resources/META-INF/spring.factories rename to spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring.factories diff --git a/spring-boot-environment/src/main/resources/application.properties b/spring-boot-modules/spring-boot-environment/src/main/resources/application.properties similarity index 100% rename from spring-boot-environment/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-environment/src/main/resources/application.properties diff --git a/spring-boot-environment/src/main/resources/external/conf.properties b/spring-boot-modules/spring-boot-environment/src/main/resources/external/conf.properties similarity index 100% rename from spring-boot-environment/src/main/resources/external/conf.properties rename to spring-boot-modules/spring-boot-environment/src/main/resources/external/conf.properties diff --git a/spring-boot-mvc-2/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-environment/src/main/resources/logback.xml similarity index 100% rename from spring-boot-mvc-2/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-environment/src/main/resources/logback.xml diff --git a/spring-boot-environment/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java b/spring-boot-modules/spring-boot-environment/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java similarity index 100% rename from spring-boot-environment/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java rename to spring-boot-modules/spring-boot-environment/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java diff --git a/spring-boot-environment/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderIntegrationTest.java b/spring-boot-modules/spring-boot-environment/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderIntegrationTest.java similarity index 100% rename from spring-boot-environment/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderIntegrationTest.java rename to spring-boot-modules/spring-boot-environment/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-exceptions/README.MD b/spring-boot-modules/spring-boot-exceptions/README.MD new file mode 100644 index 0000000000..33ae193fb8 --- /dev/null +++ b/spring-boot-modules/spring-boot-exceptions/README.MD @@ -0,0 +1,7 @@ +## Spring Boot + +This module contains articles about Spring Boot Exceptions + +### Relevant Articles: + +- [The BeanDefinitionOverrideException in Spring Boot](https://www.baeldung.com/spring-boot-bean-definition-override-exception) diff --git a/spring-boot-modules/spring-boot-exceptions/pom.xml b/spring-boot-modules/spring-boot-exceptions/pom.xml new file mode 100644 index 0000000000..f69beccf5d --- /dev/null +++ b/spring-boot-modules/spring-boot-exceptions/pom.xml @@ -0,0 +1,96 @@ + + + 4.0.0 + spring-boot-exceptions + spring-boot-exceptions + jar + Demo project for working with Spring Boot exceptions + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter + 2.2.3.RELEASE + + + + + spring-boot-exceptions + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.apache.maven.plugins + maven-resources-plugin + + + @ + + false + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + + com.baeldung.intro.App + + diff --git a/spring-boot-modules/spring-boot-exceptions/src/test/java/com/baeldung/beandefinitionoverrideexception/SpringBootBeanDefinitionOverrideExceptionIntegrationTest.java b/spring-boot-modules/spring-boot-exceptions/src/test/java/com/baeldung/beandefinitionoverrideexception/SpringBootBeanDefinitionOverrideExceptionIntegrationTest.java new file mode 100644 index 0000000000..c900bab26c --- /dev/null +++ b/spring-boot-modules/spring-boot-exceptions/src/test/java/com/baeldung/beandefinitionoverrideexception/SpringBootBeanDefinitionOverrideExceptionIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.beandefinitionoverrideexception; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {TestConfiguration1.class, TestConfiguration2.class}, properties = {"spring.main.allow-bean-definition-overriding=true"}) +public class SpringBootBeanDefinitionOverrideExceptionIntegrationTest { + + @Autowired + private ApplicationContext applicationContext; + + @Test + public void whenBeanOverridingAllowed_thenTestBean2OverridesTestBean1() { + Object testBean = applicationContext.getBean("testBean"); + + assertThat(testBean.getClass()).isEqualTo(TestConfiguration2.TestBean2.class); + } +} diff --git a/spring-boot-modules/spring-boot-exceptions/src/test/java/com/baeldung/beandefinitionoverrideexception/TestConfiguration1.java b/spring-boot-modules/spring-boot-exceptions/src/test/java/com/baeldung/beandefinitionoverrideexception/TestConfiguration1.java new file mode 100644 index 0000000000..a0e8ea3028 --- /dev/null +++ b/spring-boot-modules/spring-boot-exceptions/src/test/java/com/baeldung/beandefinitionoverrideexception/TestConfiguration1.java @@ -0,0 +1,27 @@ +package com.baeldung.beandefinitionoverrideexception; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class TestConfiguration1 { + + class TestBean1 { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + @Bean + public TestBean1 testBean() { + return new TestBean1(); + } + +} diff --git a/spring-boot-modules/spring-boot-exceptions/src/test/java/com/baeldung/beandefinitionoverrideexception/TestConfiguration2.java b/spring-boot-modules/spring-boot-exceptions/src/test/java/com/baeldung/beandefinitionoverrideexception/TestConfiguration2.java new file mode 100644 index 0000000000..842b84c866 --- /dev/null +++ b/spring-boot-modules/spring-boot-exceptions/src/test/java/com/baeldung/beandefinitionoverrideexception/TestConfiguration2.java @@ -0,0 +1,28 @@ +package com.baeldung.beandefinitionoverrideexception; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class TestConfiguration2 { + + class TestBean2 { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + + @Bean + public TestBean2 testBean() { + return new TestBean2(); + } + +} diff --git a/spring-boot-properties/src/main/resources/valueswithdefaults.properties b/spring-boot-modules/spring-boot-exceptions/src/test/resources/application.properties similarity index 100% rename from spring-boot-properties/src/main/resources/valueswithdefaults.properties rename to spring-boot-modules/spring-boot-exceptions/src/test/resources/application.properties diff --git a/spring-boot-modules/spring-boot-exceptions/src/test/resources/logback-test.xml b/spring-boot-modules/spring-boot-exceptions/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..2398bfec50 --- /dev/null +++ b/spring-boot-modules/spring-boot-exceptions/src/test/resources/logback-test.xml @@ -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-flowable/README.md b/spring-boot-modules/spring-boot-flowable/README.md similarity index 100% rename from spring-boot-flowable/README.md rename to spring-boot-modules/spring-boot-flowable/README.md diff --git a/spring-boot-modules/spring-boot-flowable/pom.xml b/spring-boot-modules/spring-boot-flowable/pom.xml new file mode 100644 index 0000000000..7d9fb97cba --- /dev/null +++ b/spring-boot-modules/spring-boot-flowable/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + spring-boot-flowable + spring-boot-flowable + war + Spring Boot Flowable Module + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + com.h2database + h2 + runtime + + + org.flowable + flowable-spring-boot-starter-rest + ${flowable.version} + + + org.flowable + flowable-spring-boot-starter-actuator + ${flowable.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + 6.4.1 + + \ No newline at end of file diff --git a/spring-boot-flowable/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/Application.java similarity index 100% rename from spring-boot-flowable/src/main/java/com/baeldung/Application.java rename to spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/Application.java diff --git a/spring-boot-flowable/src/main/java/com/baeldung/controller/ArticleWorkflowController.java b/spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/controller/ArticleWorkflowController.java similarity index 100% rename from spring-boot-flowable/src/main/java/com/baeldung/controller/ArticleWorkflowController.java rename to spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/controller/ArticleWorkflowController.java diff --git a/spring-boot-flowable/src/main/java/com/baeldung/domain/Approval.java b/spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/domain/Approval.java similarity index 100% rename from spring-boot-flowable/src/main/java/com/baeldung/domain/Approval.java rename to spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/domain/Approval.java diff --git a/spring-boot-flowable/src/main/java/com/baeldung/domain/Article.java b/spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/domain/Article.java similarity index 100% rename from spring-boot-flowable/src/main/java/com/baeldung/domain/Article.java rename to spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/domain/Article.java diff --git a/spring-boot-flowable/src/main/java/com/baeldung/service/ArticleWorkflowService.java b/spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/service/ArticleWorkflowService.java similarity index 100% rename from spring-boot-flowable/src/main/java/com/baeldung/service/ArticleWorkflowService.java rename to spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/service/ArticleWorkflowService.java diff --git a/spring-boot-flowable/src/main/java/com/baeldung/service/PublishArticleService.java b/spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/service/PublishArticleService.java similarity index 100% rename from spring-boot-flowable/src/main/java/com/baeldung/service/PublishArticleService.java rename to spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/service/PublishArticleService.java diff --git a/spring-boot-flowable/src/main/java/com/baeldung/service/SendMailService.java b/spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/service/SendMailService.java similarity index 100% rename from spring-boot-flowable/src/main/java/com/baeldung/service/SendMailService.java rename to spring-boot-modules/spring-boot-flowable/src/main/java/com/baeldung/service/SendMailService.java diff --git a/spring-boot-flowable/src/main/resources/application.properties b/spring-boot-modules/spring-boot-flowable/src/main/resources/application.properties similarity index 100% rename from spring-boot-flowable/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-flowable/src/main/resources/application.properties diff --git a/spring-boot-flowable/src/main/resources/processes/article-workflow.bpmn20.xml b/spring-boot-modules/spring-boot-flowable/src/main/resources/processes/article-workflow.bpmn20.xml similarity index 100% rename from spring-boot-flowable/src/main/resources/processes/article-workflow.bpmn20.xml rename to spring-boot-modules/spring-boot-flowable/src/main/resources/processes/article-workflow.bpmn20.xml diff --git a/spring-boot-flowable/src/test/java/com/baeldung/processes/ArticleWorkflowIntegrationTest.java b/spring-boot-modules/spring-boot-flowable/src/test/java/com/baeldung/processes/ArticleWorkflowIntegrationTest.java similarity index 100% rename from spring-boot-flowable/src/test/java/com/baeldung/processes/ArticleWorkflowIntegrationTest.java rename to spring-boot-modules/spring-boot-flowable/src/test/java/com/baeldung/processes/ArticleWorkflowIntegrationTest.java diff --git a/spring-boot-gradle/.gitignore b/spring-boot-modules/spring-boot-gradle/.gitignore similarity index 100% rename from spring-boot-gradle/.gitignore rename to spring-boot-modules/spring-boot-gradle/.gitignore diff --git a/spring-boot-gradle/README.md b/spring-boot-modules/spring-boot-gradle/README.md similarity index 100% rename from spring-boot-gradle/README.md rename to spring-boot-modules/spring-boot-gradle/README.md diff --git a/spring-boot-modules/spring-boot-gradle/build.gradle b/spring-boot-modules/spring-boot-gradle/build.gradle new file mode 100644 index 0000000000..faae01a1a5 --- /dev/null +++ b/spring-boot-modules/spring-boot-gradle/build.gradle @@ -0,0 +1,67 @@ +buildscript { + ext { + 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("${springBootPlugin}:${springBootVersion}") + classpath("${thinPlugin}:${thinVersion}") + } +} + +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 = 'com.baeldung' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = 1.8 + +repositories { + mavenCentral() +} + +dependencies { + compile('org.springframework.boot:spring-boot-starter') + testCompile('org.springframework.boot:spring-boot-starter-test') +} + +springBoot { + mainClassName = 'com.baeldung.DemoApplication' +} + +bootJar { +// This is overridden by the mainClassName in springBoot{} and added here for reference purposes. + mainClassName = 'com.baeldung.DemoApplication' + +// This block serves the same purpose as the above thus commented out. Added here for reference purposes +// manifest { +// attributes 'Start-Class': 'com.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-modules/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties similarity index 100% rename from spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties rename to spring-boot-modules/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties diff --git a/spring-boot-gradle/gradlew b/spring-boot-modules/spring-boot-gradle/gradlew similarity index 100% rename from spring-boot-gradle/gradlew rename to spring-boot-modules/spring-boot-gradle/gradlew diff --git a/spring-boot-modules/spring-boot-gradle/gradlew.bat b/spring-boot-modules/spring-boot-gradle/gradlew.bat new file mode 100644 index 0000000000..f9553162f1 --- /dev/null +++ b/spring-boot-modules/spring-boot-gradle/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/spring-boot-gradle/settings.gradle b/spring-boot-modules/spring-boot-gradle/settings.gradle similarity index 100% rename from spring-boot-gradle/settings.gradle rename to spring-boot-modules/spring-boot-gradle/settings.gradle diff --git a/spring-boot-modules/spring-boot-gradle/src/main/java/com/baeldung/DemoApplication.java b/spring-boot-modules/spring-boot-gradle/src/main/java/com/baeldung/DemoApplication.java new file mode 100644 index 0000000000..64bac6936b --- /dev/null +++ b/spring-boot-modules/spring-boot-gradle/src/main/java/com/baeldung/DemoApplication.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } +} diff --git a/spring-core-2/src/main/java/org/baeldung/spring/config/ScopesConfig.java b/spring-boot-modules/spring-boot-gradle/src/main/resources/application.properties similarity index 100% rename from spring-core-2/src/main/java/org/baeldung/spring/config/ScopesConfig.java rename to spring-boot-modules/spring-boot-gradle/src/main/resources/application.properties diff --git a/spring-boot-mvc/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-gradle/src/main/resources/logback.xml similarity index 100% rename from spring-boot-mvc/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-gradle/src/main/resources/logback.xml diff --git a/spring-boot-gradle/src/test/java/org/baeldung/DemoApplicationTests.java b/spring-boot-modules/spring-boot-gradle/src/test/java/com/baeldung/DemoApplicationTests.java similarity index 93% rename from spring-boot-gradle/src/test/java/org/baeldung/DemoApplicationTests.java rename to spring-boot-modules/spring-boot-gradle/src/test/java/com/baeldung/DemoApplicationTests.java index b24bfb2cb6..65395582cb 100644 --- a/spring-boot-gradle/src/test/java/org/baeldung/DemoApplicationTests.java +++ b/spring-boot-modules/spring-boot-gradle/src/test/java/com/baeldung/DemoApplicationTests.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-jasypt/.gitignore b/spring-boot-modules/spring-boot-jasypt/.gitignore similarity index 100% rename from spring-boot-jasypt/.gitignore rename to spring-boot-modules/spring-boot-jasypt/.gitignore diff --git a/spring-boot-jasypt/README.md b/spring-boot-modules/spring-boot-jasypt/README.md similarity index 100% rename from spring-boot-jasypt/README.md rename to spring-boot-modules/spring-boot-jasypt/README.md diff --git a/spring-boot-modules/spring-boot-jasypt/pom.xml b/spring-boot-modules/spring-boot-jasypt/pom.xml new file mode 100644 index 0000000000..e63a02729f --- /dev/null +++ b/spring-boot-modules/spring-boot-jasypt/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + com.example.jasypt + spring-boot-jasypt + spring-boot-jasypt + jar + Demo project for Spring Boot + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.github.ulisesbocchio + jasypt-spring-boot-starter + ${jasypt.version} + + + + com.github.ulisesbocchio + jasypt-spring-boot + ${jasypt.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + 2.0.0 + + + diff --git a/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/Main.java b/spring-boot-modules/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/Main.java similarity index 100% rename from spring-boot-jasypt/src/main/java/com/baeldung/jasypt/Main.java rename to spring-boot-modules/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/Main.java diff --git a/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/AppConfigForJasyptSimple.java b/spring-boot-modules/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/AppConfigForJasyptSimple.java similarity index 100% rename from spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/AppConfigForJasyptSimple.java rename to spring-boot-modules/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/AppConfigForJasyptSimple.java diff --git a/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/PropertyServiceForJasyptSimple.java b/spring-boot-modules/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/PropertyServiceForJasyptSimple.java similarity index 100% rename from spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/PropertyServiceForJasyptSimple.java rename to spring-boot-modules/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/PropertyServiceForJasyptSimple.java diff --git a/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/AppConfigForJasyptStarter.java b/spring-boot-modules/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/AppConfigForJasyptStarter.java similarity index 100% rename from spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/AppConfigForJasyptStarter.java rename to spring-boot-modules/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/AppConfigForJasyptStarter.java diff --git a/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/PropertyServiceForJasyptStarter.java b/spring-boot-modules/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/PropertyServiceForJasyptStarter.java similarity index 100% rename from spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/PropertyServiceForJasyptStarter.java rename to spring-boot-modules/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/PropertyServiceForJasyptStarter.java diff --git a/spring-boot-jasypt/src/main/resources/application.properties b/spring-boot-modules/spring-boot-jasypt/src/main/resources/application.properties similarity index 100% rename from spring-boot-jasypt/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-jasypt/src/main/resources/application.properties diff --git a/spring-boot-jasypt/src/main/resources/encrypted.properties b/spring-boot-modules/spring-boot-jasypt/src/main/resources/encrypted.properties similarity index 100% rename from spring-boot-jasypt/src/main/resources/encrypted.properties rename to spring-boot-modules/spring-boot-jasypt/src/main/resources/encrypted.properties diff --git a/spring-boot-jasypt/src/main/resources/encryptedv2.properties b/spring-boot-modules/spring-boot-jasypt/src/main/resources/encryptedv2.properties similarity index 100% rename from spring-boot-jasypt/src/main/resources/encryptedv2.properties rename to spring-boot-modules/spring-boot-jasypt/src/main/resources/encryptedv2.properties diff --git a/spring-boot-property-exp/property-exp-custom-config/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-jasypt/src/main/resources/logback.xml similarity index 100% rename from spring-boot-property-exp/property-exp-custom-config/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-jasypt/src/main/resources/logback.xml diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java b/spring-boot-modules/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java similarity index 100% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java rename to spring-boot-modules/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java b/spring-boot-modules/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java similarity index 100% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java rename to spring-boot-modules/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java b/spring-boot-modules/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java similarity index 100% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java rename to spring-boot-modules/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..97810cf590 --- /dev/null +++ b/spring-boot-modules/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.jasypt.Main; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Main.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-keycloak/.gitignore b/spring-boot-modules/spring-boot-keycloak/.gitignore similarity index 100% rename from spring-boot-keycloak/.gitignore rename to spring-boot-modules/spring-boot-keycloak/.gitignore diff --git a/spring-boot-keycloak/.mvn/wrapper/maven-wrapper.jar b/spring-boot-modules/spring-boot-keycloak/.mvn/wrapper/maven-wrapper.jar similarity index 100% rename from spring-boot-keycloak/.mvn/wrapper/maven-wrapper.jar rename to spring-boot-modules/spring-boot-keycloak/.mvn/wrapper/maven-wrapper.jar diff --git a/spring-boot-keycloak/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot-keycloak/.mvn/wrapper/maven-wrapper.properties similarity index 100% rename from spring-boot-keycloak/.mvn/wrapper/maven-wrapper.properties rename to spring-boot-modules/spring-boot-keycloak/.mvn/wrapper/maven-wrapper.properties diff --git a/spring-boot-keycloak/README.md b/spring-boot-modules/spring-boot-keycloak/README.md similarity index 100% rename from spring-boot-keycloak/README.md rename to spring-boot-modules/spring-boot-keycloak/README.md diff --git a/spring-boot-keycloak/mvnw b/spring-boot-modules/spring-boot-keycloak/mvnw similarity index 100% rename from spring-boot-keycloak/mvnw rename to spring-boot-modules/spring-boot-keycloak/mvnw diff --git a/spring-boot-keycloak/mvnw.cmd b/spring-boot-modules/spring-boot-keycloak/mvnw.cmd similarity index 100% rename from spring-boot-keycloak/mvnw.cmd rename to spring-boot-modules/spring-boot-keycloak/mvnw.cmd diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml new file mode 100644 index 0000000000..c29c1a738b --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + com.baeldung.keycloak + spring-boot-keycloak + 0.0.1 + spring-boot-keycloak + jar + This is a simple application demonstrating integration between Keycloak and Spring Boot. + + + com.baeldung + parent-boot-1 + 0.0.1-SNAPSHOT + ../../parent-boot-1 + + + + + + org.keycloak.bom + keycloak-adapter-bom + ${keycloak-adapter-bom.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter + + + org.keycloak + keycloak-spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.hsqldb + hsqldb + runtime + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + 3.3.0.Final + + + diff --git a/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/Customer.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/Customer.java similarity index 100% rename from spring-boot-keycloak/src/main/java/com/baeldung/keycloak/Customer.java rename to spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/Customer.java diff --git a/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomerDAO.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomerDAO.java similarity index 100% rename from spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomerDAO.java rename to spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomerDAO.java diff --git a/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java similarity index 100% rename from spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java rename to spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java diff --git a/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBoot.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBoot.java similarity index 100% rename from spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBoot.java rename to spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBoot.java diff --git a/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/WebController.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/WebController.java similarity index 100% rename from spring-boot-keycloak/src/main/java/com/baeldung/keycloak/WebController.java rename to spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/WebController.java diff --git a/spring-boot-keycloak/src/main/resources/application.properties b/spring-boot-modules/spring-boot-keycloak/src/main/resources/application.properties similarity index 100% rename from spring-boot-keycloak/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-keycloak/src/main/resources/application.properties diff --git a/spring-boot-property-exp/property-exp-default-config/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-keycloak/src/main/resources/logback.xml similarity index 100% rename from spring-boot-property-exp/property-exp-default-config/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-keycloak/src/main/resources/logback.xml diff --git a/spring-boot-keycloak/src/main/resources/templates/customers.html b/spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/customers.html similarity index 100% rename from spring-boot-keycloak/src/main/resources/templates/customers.html rename to spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/customers.html diff --git a/spring-boot-keycloak/src/main/resources/templates/external.html b/spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/external.html similarity index 100% rename from spring-boot-keycloak/src/main/resources/templates/external.html rename to spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/external.html diff --git a/spring-boot-keycloak/src/main/resources/templates/layout.html b/spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/layout.html similarity index 100% rename from spring-boot-keycloak/src/main/resources/templates/layout.html rename to spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/layout.html diff --git a/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationIntegrationTest.java b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationIntegrationTest.java similarity index 100% rename from spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationIntegrationTest.java rename to spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3f3ecd87d0 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.keycloak.SpringBoot; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBoot.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-modules/spring-boot-kotlin/README.md b/spring-boot-modules/spring-boot-kotlin/README.md new file mode 100644 index 0000000000..fb91fdee15 --- /dev/null +++ b/spring-boot-modules/spring-boot-kotlin/README.md @@ -0,0 +1,6 @@ +## Spring Boot Kotlin + +This module contains articles about Kotlin in Spring Boot projects. + +### Relevant Articles: +- [Non-blocking Spring Boot with Kotlin Coroutines](https://www.baeldung.com/spring-boot-kotlin-coroutines) diff --git a/spring-boot-modules/spring-boot-kotlin/pom.xml b/spring-boot-modules/spring-boot-kotlin/pom.xml new file mode 100644 index 0000000000..79d62645da --- /dev/null +++ b/spring-boot-modules/spring-boot-kotlin/pom.xml @@ -0,0 +1,151 @@ + + + 4.0.0 + spring-boot-kotlin + spring-boot-kotlin + jar + Demo project showing how to use non-blocking in Kotlin with Spring Boot + + + com.baeldung + parent-kotlin + 1.0.0-SNAPSHOT + ../../parent-kotlin + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + + org.jetbrains.kotlin + kotlin-reflect + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + + + org.jetbrains.kotlinx + kotlinx-coroutines-core + ${kotlinx-coroutines.version} + + + org.jetbrains.kotlinx + kotlinx-coroutines-reactor + ${kotlinx-coroutines.version} + + + org.springframework.boot + spring-boot-starter-webflux + + + com.fasterxml.jackson.module + jackson-module-kotlin + + + org.springframework.data + spring-data-r2dbc + ${r2dbc.version} + + + io.r2dbc + r2dbc-h2 + ${h2-r2dbc.version} + + + io.r2dbc + r2dbc-spi + ${r2dbc-spi.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + junit + junit + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + io.projectreactor + reactor-test + test + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + + + -Xjsr305=strict + + + spring + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + 1.3.31 + 1.0.0.M1 + 1.0.0.M7 + 1.0.0.BUILD-SNAPSHOT + 1.2.1 + + + diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt similarity index 100% rename from spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt rename to spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt similarity index 100% rename from spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt rename to spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt similarity index 100% rename from spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt rename to spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt similarity index 100% rename from spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt rename to spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt similarity index 100% rename from spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt rename to spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt similarity index 100% rename from spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt rename to spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt similarity index 100% rename from spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt rename to spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt similarity index 100% rename from spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt rename to spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt similarity index 100% rename from spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt rename to spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt similarity index 100% rename from spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt rename to spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt similarity index 100% rename from spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt rename to spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt diff --git a/spring-boot-kotlin/src/main/resources/application.properties b/spring-boot-modules/spring-boot-kotlin/src/main/resources/application.properties similarity index 100% rename from spring-boot-kotlin/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-kotlin/src/main/resources/application.properties diff --git a/spring-boot-runtime/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-kotlin/src/main/resources/logback.xml similarity index 100% rename from spring-boot-runtime/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-kotlin/src/main/resources/logback.xml diff --git a/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt b/spring-boot-modules/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt similarity index 100% rename from spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt rename to spring-boot-modules/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt diff --git a/spring-boot-libraries/.gitignore b/spring-boot-modules/spring-boot-libraries/.gitignore similarity index 100% rename from spring-boot-libraries/.gitignore rename to spring-boot-modules/spring-boot-libraries/.gitignore diff --git a/spring-boot-modules/spring-boot-libraries/README.md b/spring-boot-modules/spring-boot-libraries/README.md new file mode 100644 index 0000000000..c02fb69e5d --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/README.md @@ -0,0 +1,12 @@ +## Spring Boot Libraries + +This module contains articles about various Spring Boot libraries + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Guide to ShedLock with Spring](https://www.baeldung.com/shedlock-spring) +- [A Guide to the Problem Spring Web Library](https://www.baeldung.com/problem-spring-web) +- [Generating Barcodes and QR Codes in Java](https://www.baeldung.com/java-generating-barcodes-qr-codes) diff --git a/spring-boot-libraries/mvnw b/spring-boot-modules/spring-boot-libraries/mvnw similarity index 100% rename from spring-boot-libraries/mvnw rename to spring-boot-modules/spring-boot-libraries/mvnw diff --git a/spring-boot-libraries/mvnw.cmd b/spring-boot-modules/spring-boot-libraries/mvnw.cmd similarity index 100% rename from spring-boot-libraries/mvnw.cmd rename to spring-boot-modules/spring-boot-libraries/mvnw.cmd diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml new file mode 100644 index 0000000000..090967d8a8 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -0,0 +1,205 @@ + + + 4.0.0 + spring-boot-libraries + spring-boot-libraries + war + This is simple boot application for Spring boot actuator test + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.zalando + problem-spring-web + ${problem-spring-web.version} + + + + + net.javacrumbs.shedlock + shedlock-spring + ${shedlock.version} + + + net.javacrumbs.shedlock + shedlock-provider-jdbc-template + ${shedlock.version} + + + com.h2database + h2 + ${h2.version} + + + + net.sourceforge.barbecue + barbecue + ${barbecue.version} + + + net.sf.barcode4j + barcode4j + ${barcode4j.version} + + + com.github.kenglxn.qrgen + javase + ${qrgen.version} + + + com.google.zxing + core + ${zxing.version} + + + com.google.zxing + javase + ${zxing.version} + + + + + + + jitpack.io + https://jitpack.io + + + + + spring-boot-libraries + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + pl.project13.maven + git-commit-id-plugin + ${git-commit-id-plugin.version} + + + get-the-git-infos + + revision + + initialize + + + validate-the-git-infos + + validateRevision + + package + + + + true + ${project.build.outputDirectory}/git.properties + + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + + com.baeldung.intro.App + 8.5.11 + 2.4.1.Final + 1.9.0 + 2.0.0 + 5.0.2 + 5.0.2 + 5.2.4 + 18.0 + 2.2.4 + 2.3.2 + 0.23.0 + 1.4.200 + 2.1.0 + 1.5-beta1 + 2.1 + 2.6.0 + 3.3.0 + + + diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/BarcodesController.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/BarcodesController.java new file mode 100644 index 0000000000..171d703621 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/BarcodesController.java @@ -0,0 +1,99 @@ +package com.baeldung.barcodes; + +import com.baeldung.barcodes.generators.BarbecueBarcodeGenerator; +import com.baeldung.barcodes.generators.Barcode4jBarcodeGenerator; +import com.baeldung.barcodes.generators.QRGenBarcodeGenerator; +import com.baeldung.barcodes.generators.ZxingBarcodeGenerator; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.awt.image.BufferedImage; + +@RestController +@RequestMapping("/barcodes") +public class BarcodesController { + + //Barbecue library + + @GetMapping(value = "/barbecue/upca/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barbecueUPCABarcode(@PathVariable("barcode") String barcode) throws Exception { + return okResponse(BarbecueBarcodeGenerator.generateUPCABarcodeImage(barcode)); + } + + @GetMapping(value = "/barbecue/ean13/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barbecueEAN13Barcode(@PathVariable("barcode") String barcode) throws Exception { + return okResponse(BarbecueBarcodeGenerator.generateEAN13BarcodeImage(barcode)); + } + + @PostMapping(value = "/barbecue/code128", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barbecueCode128Barcode(@RequestBody String barcode) throws Exception { + return okResponse(BarbecueBarcodeGenerator.generateCode128BarcodeImage(barcode)); + } + + @PostMapping(value = "/barbecue/pdf417", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barbecuePDF417Barcode(@RequestBody String barcode) throws Exception { + return okResponse(BarbecueBarcodeGenerator.generatePDF417BarcodeImage(barcode)); + } + + //Barcode4j library + + @GetMapping(value = "/barcode4j/upca/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barcode4jUPCABarcode(@PathVariable("barcode") String barcode) { + return okResponse(Barcode4jBarcodeGenerator.generateUPCABarcodeImage(barcode)); + } + + @GetMapping(value = "/barcode4j/ean13/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barcode4jEAN13Barcode(@PathVariable("barcode") String barcode) { + return okResponse(Barcode4jBarcodeGenerator.generateEAN13BarcodeImage(barcode)); + } + + @PostMapping(value = "/barcode4j/code128", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barcode4jCode128Barcode(@RequestBody String barcode) { + return okResponse(Barcode4jBarcodeGenerator.generateCode128BarcodeImage(barcode)); + } + + @PostMapping(value = "/barcode4j/pdf417", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barcode4jPDF417Barcode(@RequestBody String barcode) { + return okResponse(Barcode4jBarcodeGenerator.generatePDF417BarcodeImage(barcode)); + } + + //Zxing library + + @GetMapping(value = "/zxing/upca/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity zxingUPCABarcode(@PathVariable("barcode") String barcode) throws Exception { + return okResponse(ZxingBarcodeGenerator.generateUPCABarcodeImage(barcode)); + } + + @GetMapping(value = "/zxing/ean13/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity zxingEAN13Barcode(@PathVariable("barcode") String barcode) throws Exception { + return okResponse(ZxingBarcodeGenerator.generateEAN13BarcodeImage(barcode)); + } + + @PostMapping(value = "/zxing/code128", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity zxingCode128Barcode(@RequestBody String barcode) throws Exception { + return okResponse(ZxingBarcodeGenerator.generateCode128BarcodeImage(barcode)); + } + + @PostMapping(value = "/zxing/pdf417", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity zxingPDF417Barcode(@RequestBody String barcode) throws Exception { + return okResponse(ZxingBarcodeGenerator.generatePDF417BarcodeImage(barcode)); + } + + @PostMapping(value = "/zxing/qrcode", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity zxingQRCode(@RequestBody String barcode) throws Exception { + return okResponse(ZxingBarcodeGenerator.generateQRCodeImage(barcode)); + } + + //QRGen + + @PostMapping(value = "/qrgen/qrcode", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity qrgenQRCode(@RequestBody String barcode) throws Exception { + return okResponse(QRGenBarcodeGenerator.generateQRCodeImage(barcode)); + } + + private ResponseEntity okResponse(BufferedImage image) { + return new ResponseEntity<>(image, HttpStatus.OK); + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/SpringBootApp.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/SpringBootApp.java new file mode 100644 index 0000000000..991b3b11ce --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/SpringBootApp.java @@ -0,0 +1,23 @@ +package com.baeldung.barcodes; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.http.converter.BufferedImageHttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverter; + +import java.awt.image.BufferedImage; + +@SpringBootApplication +public class SpringBootApp { + + public static void main(String[] args) { + SpringApplication.run(SpringBootApp.class, args); + } + + @Bean + public HttpMessageConverter createImageHttpMessageConverter() { + return new BufferedImageHttpMessageConverter(); + } + +} diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java new file mode 100644 index 0000000000..353f824d98 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java @@ -0,0 +1,43 @@ +package com.baeldung.barcodes.generators; + +import net.sourceforge.barbecue.Barcode; +import net.sourceforge.barbecue.BarcodeFactory; +import net.sourceforge.barbecue.BarcodeImageHandler; + +import java.awt.*; +import java.awt.image.BufferedImage; + +public class BarbecueBarcodeGenerator { + + private static final Font BARCODE_TEXT_FONT = new Font(Font.SANS_SERIF, Font.PLAIN, 14); + + public static BufferedImage generateUPCABarcodeImage(String barcodeText) throws Exception { + Barcode barcode = BarcodeFactory.createUPCA(barcodeText); //checksum is automatically added + barcode.setFont(BARCODE_TEXT_FONT); + barcode.setResolution(400); + + return BarcodeImageHandler.getImage(barcode); + } + + public static BufferedImage generateEAN13BarcodeImage(String barcodeText) throws Exception { + Barcode barcode = BarcodeFactory.createEAN13(barcodeText); //checksum is automatically added + barcode.setFont(BARCODE_TEXT_FONT); + + return BarcodeImageHandler.getImage(barcode); + } + + public static BufferedImage generateCode128BarcodeImage(String barcodeText) throws Exception { + Barcode barcode = BarcodeFactory.createCode128(barcodeText); + barcode.setFont(BARCODE_TEXT_FONT); + + return BarcodeImageHandler.getImage(barcode); + } + + public static BufferedImage generatePDF417BarcodeImage(String barcodeText) throws Exception { + Barcode barcode = BarcodeFactory.createPDF417(barcodeText); + barcode.setFont(BARCODE_TEXT_FONT); + + return BarcodeImageHandler.getImage(barcode); + } + +} diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java new file mode 100644 index 0000000000..a2fee044e5 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java @@ -0,0 +1,46 @@ +package com.baeldung.barcodes.generators; + +import org.krysalis.barcode4j.impl.code128.Code128Bean; +import org.krysalis.barcode4j.impl.pdf417.PDF417Bean; +import org.krysalis.barcode4j.impl.upcean.EAN13Bean; +import org.krysalis.barcode4j.impl.upcean.UPCABean; +import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider; + +import java.awt.image.BufferedImage; + +public class Barcode4jBarcodeGenerator { + + public static BufferedImage generateUPCABarcodeImage(String barcodeText) { + UPCABean barcodeGenerator = new UPCABean(); + BitmapCanvasProvider canvas = new BitmapCanvasProvider(160, BufferedImage.TYPE_BYTE_BINARY, false, 0); + + barcodeGenerator.generateBarcode(canvas, barcodeText); + return canvas.getBufferedImage(); + } + + public static BufferedImage generateEAN13BarcodeImage(String barcodeText) { + EAN13Bean barcodeGenerator = new EAN13Bean(); + BitmapCanvasProvider canvas = new BitmapCanvasProvider(160, BufferedImage.TYPE_BYTE_BINARY, false, 0); + + barcodeGenerator.generateBarcode(canvas, barcodeText); + return canvas.getBufferedImage(); + } + + public static BufferedImage generateCode128BarcodeImage(String barcodeText) { + Code128Bean barcodeGenerator = new Code128Bean(); + BitmapCanvasProvider canvas = new BitmapCanvasProvider(160, BufferedImage.TYPE_BYTE_BINARY, false, 0); + + barcodeGenerator.generateBarcode(canvas, barcodeText); + return canvas.getBufferedImage(); + } + + public static BufferedImage generatePDF417BarcodeImage(String barcodeText) { + PDF417Bean barcodeGenerator = new PDF417Bean(); + BitmapCanvasProvider canvas = new BitmapCanvasProvider(160, BufferedImage.TYPE_BYTE_BINARY, false, 0); + barcodeGenerator.setColumns(10); + + barcodeGenerator.generateBarcode(canvas, barcodeText); + return canvas.getBufferedImage(); + } + +} diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java new file mode 100644 index 0000000000..46d17ac500 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java @@ -0,0 +1,21 @@ +package com.baeldung.barcodes.generators; + +import net.glxn.qrgen.javase.QRCode; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +public class QRGenBarcodeGenerator { + + public static BufferedImage generateQRCodeImage(String barcodeText) throws Exception { + ByteArrayOutputStream stream = QRCode + .from(barcodeText) + .withSize(250, 250) + .stream(); + ByteArrayInputStream bis = new ByteArrayInputStream(stream.toByteArray()); + + return ImageIO.read(bis); + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java new file mode 100644 index 0000000000..e9aa2975da --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java @@ -0,0 +1,51 @@ +package com.baeldung.barcodes.generators; + +import com.google.zxing.BarcodeFormat; +import com.google.zxing.client.j2se.MatrixToImageWriter; +import com.google.zxing.common.BitMatrix; +import com.google.zxing.oned.Code128Writer; +import com.google.zxing.oned.EAN13Writer; +import com.google.zxing.oned.UPCAWriter; +import com.google.zxing.pdf417.PDF417Writer; +import com.google.zxing.qrcode.QRCodeWriter; + +import java.awt.image.BufferedImage; + +public class ZxingBarcodeGenerator { + + public static BufferedImage generateUPCABarcodeImage(String barcodeText) throws Exception { + UPCAWriter barcodeWriter = new UPCAWriter(); + BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.UPC_A, 300, 150); + + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } + + public static BufferedImage generateEAN13BarcodeImage(String barcodeText) throws Exception { + EAN13Writer barcodeWriter = new EAN13Writer(); + BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.EAN_13, 300, 150); + + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } + + public static BufferedImage generateCode128BarcodeImage(String barcodeText) throws Exception { + Code128Writer barcodeWriter = new Code128Writer(); + BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.CODE_128, 300, 150); + + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } + + public static BufferedImage generatePDF417BarcodeImage(String barcodeText) throws Exception { + PDF417Writer barcodeWriter = new PDF417Writer(); + BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.PDF_417, 700, 700); + + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } + + public static BufferedImage generateQRCodeImage(String barcodeText) throws Exception { + QRCodeWriter barcodeWriter = new QRCodeWriter(); + BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.QR_CODE, 200, 200); + + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } + +} \ No newline at end of file diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/SpringProblemApplication.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/SpringProblemApplication.java similarity index 100% rename from spring-boot-libraries/src/main/java/com/baeldung/boot/problem/SpringProblemApplication.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/SpringProblemApplication.java diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java similarity index 100% rename from spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/SecurityExceptionHandler.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/SecurityExceptionHandler.java similarity index 100% rename from spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/SecurityExceptionHandler.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/SecurityExceptionHandler.java diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java similarity index 100% rename from spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/SecurityConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/SecurityConfiguration.java similarity index 100% rename from spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/SecurityConfiguration.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/SecurityConfiguration.java diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/controller/ProblemDemoController.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/controller/ProblemDemoController.java similarity index 100% rename from spring-boot-libraries/src/main/java/com/baeldung/boot/problem/controller/ProblemDemoController.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/controller/ProblemDemoController.java diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/dto/Task.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/dto/Task.java similarity index 100% rename from spring-boot-libraries/src/main/java/com/baeldung/boot/problem/dto/Task.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/dto/Task.java diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/problems/TaskNotFoundProblem.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/problems/TaskNotFoundProblem.java similarity index 100% rename from spring-boot-libraries/src/main/java/com/baeldung/boot/problem/problems/TaskNotFoundProblem.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/problems/TaskNotFoundProblem.java diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java new file mode 100644 index 0000000000..cd5f63e962 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java @@ -0,0 +1,14 @@ +package com.baeldung.scheduling.shedlock; + +import net.javacrumbs.shedlock.core.SchedulerLock; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +class BaeldungTaskScheduler { + @Scheduled(cron = "0 0/15 * * * ?") + @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M") + public void scheduledTask() { + System.out.println("Running ShedLock task"); + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java new file mode 100644 index 0000000000..440e1ffc6a --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java @@ -0,0 +1,16 @@ +package com.baeldung.scheduling.shedlock; + +import net.javacrumbs.shedlock.core.LockProvider; +import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.sql.DataSource; + +@Configuration +public class SchedulerConfiguration { + @Bean + public LockProvider lockProvider(DataSource dataSource) { + return new JdbcTemplateLockProvider(dataSource); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java new file mode 100644 index 0000000000..cebb234036 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.scheduling.shedlock; + +import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@EnableScheduling +@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") +public class SpringBootShedlockApplication { + public static void main(String[] args) { + SpringApplication.run(SpringBootShedlockApplication.class, args); + } +} diff --git a/spring-boot-libraries/src/main/resources/application-problem.properties b/spring-boot-modules/spring-boot-libraries/src/main/resources/application-problem.properties similarity index 100% rename from spring-boot-libraries/src/main/resources/application-problem.properties rename to spring-boot-modules/spring-boot-libraries/src/main/resources/application-problem.properties diff --git a/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml new file mode 100644 index 0000000000..3477520208 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml @@ -0,0 +1,6 @@ +spring: + datasource: + driverClassName: org.h2.Driver + url: jdbc:h2:mem:shedlock_DB;INIT=CREATE SCHEMA IF NOT EXISTS shedlock;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + username: sa + password: diff --git a/spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java similarity index 100% rename from spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java new file mode 100644 index 0000000000..47f42c133f --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.scheduling.shedlock; + +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.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class BaeldungTaskSchedulerIntegrationTest { + @Autowired + private BaeldungTaskScheduler taskScheduler; + + @Test + public void whenShedLockConfigCorrect_thenSpringCtxtStartsWithoutError() { + // save the old out + PrintStream old = System.out; + + // Create a stream to hold the output for test + ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(consoleOutput); + System.setOut(ps); + //test + taskScheduler.scheduledTask(); + System.out.flush(); + String expected = "Running ShedLock task\n"; + assertThat(consoleOutput.toString()).isEqualTo(expected); + + //restore the old out + System.setOut(old); + } + +} \ No newline at end of file diff --git a/spring-boot-logging-log4j2/.gitignore b/spring-boot-modules/spring-boot-logging-log4j2/.gitignore similarity index 100% rename from spring-boot-logging-log4j2/.gitignore rename to spring-boot-modules/spring-boot-logging-log4j2/.gitignore diff --git a/spring-boot-logging-log4j2/README.md b/spring-boot-modules/spring-boot-logging-log4j2/README.md similarity index 100% rename from spring-boot-logging-log4j2/README.md rename to spring-boot-modules/spring-boot-logging-log4j2/README.md diff --git a/spring-boot-modules/spring-boot-logging-log4j2/pom.xml b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml new file mode 100644 index 0000000000..4422405187 --- /dev/null +++ b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + spring-boot-logging-log4j2 + spring-boot-logging-log4j2 + jar + Demo project for Spring Boot Logging with Log4J2 + + + + + org.springframework.boot + spring-boot-starter-parent + 2.2.2.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-test + + + org.springframework.boot + spring-boot-starter-log4j2 + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + + + org.springframework.boot + spring-boot-starter-log4j + ${spring-boot-starter-log4j.version} + + + org.graylog2 + gelfj + ${gelfj.version} + compile + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*ManualTest.java + **/*LiveTest.java + + + + + + + + com.baeldung.springbootlogging.SpringBootLoggingApplication + 1.3.8.RELEASE + 1.1.16 + 1.18.4 + + + diff --git a/spring-boot-logging-log4j2/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java b/spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java similarity index 100% rename from spring-boot-logging-log4j2/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java rename to spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java diff --git a/spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/group/LogGroupApplication.java b/spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/group/LogGroupApplication.java new file mode 100644 index 0000000000..021f27bd98 --- /dev/null +++ b/spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/group/LogGroupApplication.java @@ -0,0 +1,26 @@ +package com.baeldung.group; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@SpringBootApplication +@ActiveProfiles("log-group") +public class LogGroupApplication { + + private static final Logger LOGGER = LoggerFactory.getLogger(LogGroupApplication.class); + + @RequestMapping("/log-group") + public void justLog() { + LOGGER.debug("Received a request"); + } + + public static void main(String[] args) { + SpringApplication.run(LogGroupApplication.class, args); + } +} diff --git a/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LoggingController.java b/spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LoggingController.java similarity index 100% rename from spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LoggingController.java rename to spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LoggingController.java diff --git a/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java b/spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java similarity index 100% rename from spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java rename to spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java diff --git a/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java b/spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java similarity index 100% rename from spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java rename to spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java diff --git a/spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/application-log-group.properties b/spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/application-log-group.properties new file mode 100644 index 0000000000..6dfe11724e --- /dev/null +++ b/spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/application-log-group.properties @@ -0,0 +1 @@ +logging.level.web=debug \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-logging-log4j2/src/main/resources/log4j.xml b/spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/log4j.xml similarity index 100% rename from spring-boot-logging-log4j2/src/main/resources/log4j.xml rename to spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/log4j.xml diff --git a/spring-boot-logging-log4j2/src/main/resources/log4j2-spring.xml b/spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/log4j2-spring.xml similarity index 100% rename from spring-boot-logging-log4j2/src/main/resources/log4j2-spring.xml rename to spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/log4j2-spring.xml diff --git a/spring-boot-modules/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d2660ad84e --- /dev/null +++ b/spring-boot-modules/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.springbootlogging.SpringBootLoggingApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootLoggingApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-mvc-2/.gitignore b/spring-boot-modules/spring-boot-mvc-2/.gitignore similarity index 100% rename from spring-boot-mvc-2/.gitignore rename to spring-boot-modules/spring-boot-mvc-2/.gitignore diff --git a/spring-boot-modules/spring-boot-mvc-2/README.md b/spring-boot-modules/spring-boot-mvc-2/README.md new file mode 100644 index 0000000000..c42730f9cc --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/README.md @@ -0,0 +1,14 @@ +## Spring Boot MVC + +This module contains articles about Spring Web MVC in Spring Boot projects. + +### Relevant Articles: + +- [Functional Controllers in Spring MVC](https://www.baeldung.com/spring-mvc-functional-controllers) +- [Specify an Array of Strings as Body Parameters in Swagger](https://www.baeldung.com/swagger-body-array-of-strings) +- [Swagger @ApiParam vs @ApiModelProperty](https://www.baeldung.com/swagger-apiparam-vs-apimodelproperty) +- [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) +- [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) +- [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) +- [Spring Boot Consuming and Producing JSON](https://www.baeldung.com/spring-boot-json) +- More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc) diff --git a/spring-boot-modules/spring-boot-mvc-2/pom.xml b/spring-boot-modules/spring-boot-mvc-2/pom.xml new file mode 100644 index 0000000000..3c503eb23d --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/pom.xml @@ -0,0 +1,134 @@ + + + 4.0.0 + spring-boot-mvc-2 + spring-boot-mvc-2 + jar + Module For Spring Boot MVC Web Fn + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + true + + + + + io.springfox + springfox-swagger2 + ${spring.fox.version} + + + + io.springfox + springfox-swagger-ui + ${spring.fox.version} + + + + io.springfox + springfox-spring-webmvc + ${spring.fox.version} + + + + org.apache.commons + commons-lang3 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.fasterxml.jackson.core + jackson-databind + + + + com.h2database + h2 + + + + com.thoughtworks.xstream + xstream + ${xstream.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + ${start-class} + JAR + + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + jcenter-snapshots + jcenter + http://oss.jfrog.org/artifactory/oss-snapshot-local/ + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + 3.0.0-SNAPSHOT + com.baeldung.swagger2boot.SpringBootSwaggerApplication + + 2.2.0.BUILD-SNAPSHOT + 1.4.11.1 + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java new file mode 100644 index 0000000000..e553ca1b72 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java @@ -0,0 +1,95 @@ +package com.baeldung.etag; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Version; + +@Entity +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false) + private String name; + + @Version + private long version; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + 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; + } + + public long getVersion() { + return version; + } + + public void setVersion(long version) { + this.version = version; + } + + // + + @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-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java new file mode 100644 index 0000000000..58f366501d --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java @@ -0,0 +1,58 @@ +package com.baeldung.etag; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +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.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +@RestController +@RequestMapping(value = "/foos") +public class FooController { + + @Autowired + private FooDao fooDao; + + @GetMapping(value = "/{id}") + public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { + return fooDao.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + } + + // Note: the global filter overrides the ETag value we set here. We can still + // analyze its behaviour in the Integration Test. + @GetMapping(value = "/{id}/custom-etag") + public ResponseEntity findByIdWithCustomEtag(@PathVariable("id") final Long id, + final HttpServletResponse response) { + final Foo foo = fooDao.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + return ResponseEntity.ok().eTag(Long.toString(foo.getVersion())).body(foo); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { + return fooDao.save(resource); + } + + @PutMapping(value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { + fooDao.save(resource); + } + + @DeleteMapping(value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void delete(@PathVariable("id") final Long id) { + fooDao.deleteById(id); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java new file mode 100644 index 0000000000..aff011af4a --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java @@ -0,0 +1,8 @@ +package com.baeldung.etag; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface FooDao extends CrudRepository{ +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java new file mode 100644 index 0000000000..9e58a1550c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.etag; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootEtagApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootEtagApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java new file mode 100644 index 0000000000..bef468452a --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java @@ -0,0 +1,28 @@ +package com.baeldung.etag; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.ShallowEtagHeaderFilter; + +@Configuration +public class WebConfig { + + // Etags + + // If we're not using Spring Boot we can make use of + // AbstractAnnotationConfigDispatcherServletInitializer#getServletFilters + @Bean + public FilterRegistrationBean shallowEtagHeaderFilter() { + FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>( new ShallowEtagHeaderFilter()); + filterRegistrationBean.addUrlPatterns("/foos/*"); + filterRegistrationBean.setName("etagFilter"); + return filterRegistrationBean; + } + + // We can also just declare the filter directly + // @Bean + // public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { + // return new ShallowEtagHeaderFilter(); + // } +} \ No newline at end of file diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java similarity index 100% rename from spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java rename to spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java similarity index 100% rename from spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java rename to spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java similarity index 100% rename from spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java rename to spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java similarity index 100% rename from spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java rename to spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/SpringBootStudentsApplication.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/SpringBootStudentsApplication.java new file mode 100644 index 0000000000..9c499e6103 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/SpringBootStudentsApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.students; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootStudentsApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootStudentsApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/Student.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/Student.java new file mode 100644 index 0000000000..16d02fe14a --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/Student.java @@ -0,0 +1,53 @@ +package com.baeldung.students; + +public class Student { + + private long id; + private String firstName; + private String lastName; + + public Student() {} + + public Student(String firstName, String lastName) { + super(); + this.firstName = firstName; + this.lastName = lastName; + } + + public Student(long id, String firstName, String lastName) { + super(); + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + 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; + } + + @Override + public String toString() { + return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentController.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentController.java new file mode 100644 index 0000000000..c71bb6c6e6 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentController.java @@ -0,0 +1,74 @@ +package com.baeldung.students; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +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.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.baeldung.students.StudentService; + +@RestController +@RequestMapping("/students") +public class StudentController { + + @Autowired + private StudentService service; + + @GetMapping("/") + public List read() { + return service.readAll(); + } + + @GetMapping("/{id}") + public ResponseEntity read(@PathVariable("id") Long id) { + Student foundStudent = service.read(id); + if (foundStudent == null) { + return ResponseEntity.notFound().build(); + } else { + return ResponseEntity.ok(foundStudent); + } + } + + @PostMapping("/") + public ResponseEntity create(@RequestBody Student student) throws URISyntaxException { + Student createdStudent = service.create(student); + + URI uri = ServletUriComponentsBuilder.fromCurrentRequest() + .path("/{id}") + .buildAndExpand(createdStudent.getId()) + .toUri(); + + return ResponseEntity.created(uri) + .body(createdStudent); + + } + + @PutMapping("/{id}") + public ResponseEntity update(@RequestBody Student student, @PathVariable Long id) { + Student updatedStudent = service.update(id, student); + if (updatedStudent == null) { + return ResponseEntity.notFound().build(); + } else { + return ResponseEntity.ok(updatedStudent); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteStudent(@PathVariable Long id) { + service.delete(id); + + return ResponseEntity.noContent().build(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentService.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentService.java new file mode 100644 index 0000000000..80f6dfd514 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentService.java @@ -0,0 +1,51 @@ +package com.baeldung.students; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Service; + +@Service +public class StudentService { + + // DB repository mock + private Map repository = Arrays.asList( + new Student[]{ + new Student(1, "Alan","Turing"), + new Student(2, "Sebastian","Bach"), + new Student(3, "Pablo","Picasso"), + }).stream() + .collect(Collectors.toConcurrentMap(s -> s.getId(), Function.identity())); + + // DB id sequence mock + private AtomicLong sequence = new AtomicLong(3); + + public List readAll() { + return repository.values().stream().collect(Collectors.toList()); + } + + public Student read(Long id) { + return repository.get(id); + } + + public Student create(Student student) { + long key = sequence.incrementAndGet(); + student.setId(key); + repository.put(key, student); + return student; + } + + public Student update(Long id, Student student) { + student.setId(id); + Student oldStudent = repository.replace(id, student); + return oldStudent == null ? null : student; + } + + public void delete(Long id) { + repository.remove(id); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java new file mode 100644 index 0000000000..0f68f75d16 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.swagger2boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootSwaggerApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootSwaggerApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/config/Swagger2Config.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/config/Swagger2Config.java new file mode 100644 index 0000000000..6f3557d597 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/config/Swagger2Config.java @@ -0,0 +1,35 @@ +package com.baeldung.swagger2boot.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; + +@Configuration +@EnableSwagger2WebMvc +public class Swagger2Config { + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build() + .apiInfo(apiEndPointsInfo()); + } + + private ApiInfo apiEndPointsInfo() { + return new ApiInfoBuilder().title("Swagger Array") + .description("This is a sample Swagger description for an Array server") + .license("Apache 2.0") + .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") + .version("1.0.0") + .build(); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/controller/FooController.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/controller/FooController.java new file mode 100644 index 0000000000..ac6d99c40c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/controller/FooController.java @@ -0,0 +1,35 @@ +package com.baeldung.swagger2boot.controller; + +import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; + +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +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.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +import com.baeldung.swagger2boot.model.Foo; + +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; + +@Controller +public class FooController { + + public FooController() { + super(); + } + + // API - write + @RequestMapping(method = RequestMethod.POST, value = "/foos") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + @ApiImplicitParams({ @ApiImplicitParam(name = "foo", value = "List of strings", paramType = "body", dataType = "Foo") }) + public Foo create(@RequestBody final Foo foo) { + foo.setId(Long.parseLong(randomNumeric(2))); + return foo; + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/controller/UserController.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/controller/UserController.java new file mode 100644 index 0000000000..d8102a8407 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/controller/UserController.java @@ -0,0 +1,39 @@ +package com.baeldung.swagger2boot.controller; + +import com.baeldung.swagger2boot.model.Foo; +import com.baeldung.swagger2boot.model.User; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import javax.websocket.server.PathParam; + +import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; + +@Controller +public class UserController { + + public UserController() { + super(); + } //@formatter:off + + @RequestMapping(method = RequestMethod.POST, value = "/createUser", produces = "application/json; charset=UTF-8") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + @ApiOperation(value = "Create user", + notes = "This method creates a new user") + public User createUser(@ApiParam( + name = "firstName", + type = "String", + value = "First Name of the user", + example = "Vatsal", + required = true) @RequestParam String firstName) { //@formatter:on + User user = new User(firstName); + return user; + } +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/model/Foo.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/model/Foo.java new file mode 100644 index 0000000000..e48c2016c0 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/model/Foo.java @@ -0,0 +1,44 @@ +package com.baeldung.swagger2boot.model; + +import java.util.List; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel +public class Foo { + private long id; + + @ApiModelProperty(name = "name", dataType = "List", example = "[\"str1\", \"str2\", \"str3\"]") + private List name; + + public Foo() { + super(); + } + + public Foo(final long id, final List name) { + super(); + + this.id = id; + this.name = name; + } + + // + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public List getName() { + return name; + } + + public void setName(final List name) { + this.name = name; + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/model/User.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/model/User.java new file mode 100644 index 0000000000..d4a6479f4e --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/swagger2boot/model/User.java @@ -0,0 +1,28 @@ +package com.baeldung.swagger2boot.model; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel +public class User { + + @ApiModelProperty(value = "first name of the user", name = "firstName", dataType = "String", example = "Vatsal") + String firstName; + + public User() { + super(); + } + + public User(final String firstName) { + super(); + this.firstName = firstName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml new file mode 100644 index 0000000000..7f36b33b38 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties new file mode 100644 index 0000000000..7070d4c2f0 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties @@ -0,0 +1,4 @@ +spring.main.allow-bean-definition-overriding=true +spring.mvc.static-path-pattern=/content/** +spring.webflux.static-path-pattern=/content/** +spring.resources.static-locations=classpath:/files/,classpath:/static-files \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html new file mode 100644 index 0000000000..15df316612 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html @@ -0,0 +1,10 @@ + + + + + Hello World! + + +Hello World! + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/foo_API_test.postman_collection.json b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/foo_API_test.postman_collection.json new file mode 100644 index 0000000000..dc4acafab3 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/foo_API_test.postman_collection.json @@ -0,0 +1,180 @@ +{ + "info": { + "_postman_id": "9989b5be-13ba-4d22-8e43-d05dbf628e58", + "name": "foo API test", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "add a foo", + "event": [ + { + "listen": "test", + "script": { + "id": "a01534dc-6fc7-4c54-ba1d-6bcf311e5836", + "exec": [ + "pm.test(\"success status\", () => pm.response.to.be.success );", + "", + "pm.test(\"name is correct\", () => ", + " pm.expect(pm.response.json().name).to.equal(\"Transformers\"));", + "", + "pm.test(\"id was assigned\", () => ", + " pm.expect(pm.response.json().id).to.be.not.null );", + "", + "pm.variables.set(\"id\", pm.response.json().id);" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "name": "Content-Type", + "value": "application/json", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"Transformers\"\n}" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos" + ] + } + }, + "response": [] + }, + { + "name": "get a foo", + "event": [ + { + "listen": "test", + "script": { + "id": "03de440c-b483-4ab8-a11a-d0c99b349963", + "exec": [ + "pm.test(\"success status\", () => pm.response.to.be.success );", + "", + "pm.test(\"name is correct\", () => ", + " pm.expect(pm.response.json().name).to.equal(\"Transformers\"));", + "", + "pm.test(\"id is correct\", () => ", + " pm.expect(pm.response.json().id).to.equal(pm.variables.get(\"id\")) );" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos", + "{{id}}" + ] + } + }, + "response": [] + }, + { + "name": "delete a foo", + "event": [ + { + "listen": "test", + "script": { + "id": "74c1bb0f-c06c-48b1-a545-459233541b14", + "exec": [ + "pm.test(\"success status\", () => pm.response.to.be.success );" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "DELETE", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos", + "{{id}}" + ] + } + }, + "response": [] + }, + { + "name": "verify delete", + "event": [ + { + "listen": "test", + "script": { + "id": "03de440c-b483-4ab8-a11a-d0c99b349963", + "exec": [ + "pm.test(\"status is 500\", () => pm.response.to.have.status(500) );", + "", + "pm.test(\"no value present\", () => ", + " pm.expect(pm.response.json().cause).to.equal(\"No value present\"));" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos", + "{{id}}" + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/spring-boot-security/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/logback.xml similarity index 100% rename from spring-boot-security/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-mvc-2/src/main/resources/logback.xml diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/swagger-description.yml b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/swagger-description.yml new file mode 100644 index 0000000000..b40ddc80f0 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/swagger-description.yml @@ -0,0 +1,33 @@ +swagger: "2.0" +info: + description: "This is a sample Swagger description for an Array server" + version: "1.0.0" + title: "Swagger Array" + license: + name: "Apache 2.0" + url: "http://www.apache.org/licenses/LICENSE-2.0.html" +basePath: "/localhost:8080/" +tags: +- name: "foo-controller" + description: "Foo controller" + +paths: + /foos: + post: + tags: + - "foo-controller" + summary: "create" + description: "" + parameters: + - in: body + description: "" + required: true + name: name + schema: + type: array + items: + type: string + example: ["str1", "str2", "str3"] + responses: + default: + description: OK \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java new file mode 100644 index 0000000000..88c5ae1686 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java @@ -0,0 +1,123 @@ +package com.baeldung.etag; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.assertj.core.util.Preconditions; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ComponentScan(basePackageClasses = WebConfig.class) +@EnableAutoConfiguration +public class EtagIntegrationTest { + + @LocalServerPort + private int port; + + @Test + public void givenResourceExists_whenRetrievingResource_thenEtagIsAlsoReturned() { + // Given + final String uriOfResource = createAsUri(); + + // When + final Response findOneResponse = RestAssured.given().header("Accept", "application/json").get(uriOfResource); + + // Then + assertNotNull(findOneResponse.getHeader(HttpHeaders.ETAG)); + } + + @Test + public void givenResourceWasRetrieved_whenRetrievingAgainWithEtag_thenNotModifiedReturned() { + // Given + final String uriOfResource = createAsUri(); + final Response findOneResponse = RestAssured.given().header("Accept", "application/json").get(uriOfResource); + final String etagValue = findOneResponse.getHeader(HttpHeaders.ETAG); + + // When + final Response secondFindOneResponse = RestAssured.given().header("Accept", "application/json") + .headers("If-None-Match", etagValue).get(uriOfResource); + + // Then + assertTrue(secondFindOneResponse.getStatusCode() == 304); + } + + @Test + public void givenResourceWasRetrievedThenModified_whenRetrievingAgainWithEtag_thenResourceIsReturned() { + // Given + final String uriOfResource = createAsUri(); + final Response firstFindOneResponse = RestAssured.given().header("Accept", "application/json") + .get(uriOfResource); + final String etagValue = firstFindOneResponse.getHeader(HttpHeaders.ETAG); + final long createdId = firstFindOneResponse.jsonPath().getLong("id"); + + Foo updatedFoo = new Foo("updated value"); + updatedFoo.setId(createdId); + Response updatedResponse = RestAssured.given().contentType(ContentType.JSON).body(updatedFoo) + .put(uriOfResource); + assertThat(updatedResponse.getStatusCode() == 200); + + // When + final Response secondFindOneResponse = RestAssured.given().header("Accept", "application/json") + .headers("If-None-Match", etagValue).get(uriOfResource); + + // Then + assertTrue(secondFindOneResponse.getStatusCode() == 200); + } + + @Test + @Ignore("Not Yet Implemented By Spring - https://jira.springsource.org/browse/SPR-10164") + public void givenResourceExists_whenRetrievedWithIfMatchIncorrectEtag_then412IsReceived() { + // Given + final String uriOfResource = createAsUri(); + + // When + final Response findOneResponse = RestAssured.given().header("Accept", "application/json") + .headers("If-Match", randomAlphabetic(8)).get(uriOfResource); + + // Then + assertTrue(findOneResponse.getStatusCode() == 412); + } + + private final String createAsUri() { + final Response response = createAsResponse(new Foo(randomAlphabetic(6))); + Preconditions.checkState(response.getStatusCode() == 201, "create operation: " + response.getStatusCode()); + + return getURL() + "/" + response.getBody().as(Foo.class).getId(); + } + + private Response createAsResponse(final Foo resource) { + String resourceAsString; + try { + resourceAsString = new ObjectMapper().writeValueAsString(resource); + } catch (JsonProcessingException e) { + throw new AssertionError("Error during serialization"); + } + return RestAssured.given().contentType(MediaType.APPLICATION_JSON.toString()).body(resourceAsString) + .post(getURL()); + } + + private String getURL() { + return "http://localhost:" + port + "/foos"; + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java new file mode 100644 index 0000000000..e65b106ead --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java @@ -0,0 +1,82 @@ +package com.baeldung.mime; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +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.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.etag.Foo; +import com.baeldung.etag.WebConfig; + +import io.restassured.RestAssured; +import io.restassured.response.Response; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes= WebConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@ComponentScan({"com.baeldung.mime", "com.baeldung.etag"}) +@EnableAutoConfiguration +@ActiveProfiles("test") +public class FooLiveTest { + + @LocalServerPort + private int port; + + @Autowired + protected IMarshaller marshaller; + + // API + + public final void create() { + create(new Foo(randomAlphabetic(6))); + } + + public final String createAsUri() { + return createAsUri(new Foo(randomAlphabetic(6))); + } + + protected final void create(final Foo resource) { + createAsUri(resource); + } + + private final String createAsUri(final Foo resource) { + final Response response = createAsResponse(resource); + return getURL() + "/" + response.getBody().as(Foo.class).getId(); + } + + private final Response createAsResponse(final Foo resource) { + + final String resourceAsString = marshaller.encode(resource); + return RestAssured.given() + .contentType(marshaller.getMime()) + .body(resourceAsString) + .post(getURL()); + } + + // + + protected String getURL() { + return "http://localhost:" + port + "/foos"; + } + + @Test + public void givenResourceExists_whenRetrievingResource_thenEtagIsAlsoReturned() { + // Given + final String uriOfResource = createAsUri(); + + // When + final Response findOneResponse = RestAssured.given().header("Accept", "application/json").get(uriOfResource); + + // Then + assertEquals(findOneResponse.getStatusCode(), 200); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/IMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/IMarshaller.java new file mode 100644 index 0000000000..79c0616043 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/IMarshaller.java @@ -0,0 +1,15 @@ +package com.baeldung.mime; + +import java.util.List; + +public interface IMarshaller { + + String encode(final T entity); + + T decode(final String entityAsString, final Class clazz); + + List decodeList(final String entitiesAsString, final Class clazz); + + String getMime(); + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java new file mode 100644 index 0000000000..9dee0ef2cd --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java @@ -0,0 +1,75 @@ +package com.baeldung.mime; + +import java.io.IOException; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; + +import com.baeldung.etag.Foo; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +public final class JacksonMarshaller implements IMarshaller { + private final Logger logger = LoggerFactory.getLogger(JacksonMarshaller.class); + + private final ObjectMapper objectMapper; + + public JacksonMarshaller() { + super(); + + objectMapper = new ObjectMapper(); + } + + // API + + @Override + public final String encode(final T resource) { + String entityAsJSON = null; + try { + entityAsJSON = objectMapper.writeValueAsString(resource); + } catch (final IOException ioEx) { + logger.error("", ioEx); + } + + return entityAsJSON; + } + + @Override + public final T decode(final String resourceAsString, final Class clazz) { + T entity = null; + try { + entity = objectMapper.readValue(resourceAsString, clazz); + } catch (final IOException ioEx) { + logger.error("", ioEx); + } + + return entity; + } + + @SuppressWarnings("unchecked") + @Override + public final List decodeList(final String resourcesAsString, final Class clazz) { + List entities = null; + try { + if (clazz.equals(Foo.class)) { + entities = objectMapper.readValue(resourcesAsString, new TypeReference>() { + // ... + }); + } else { + entities = objectMapper.readValue(resourcesAsString, List.class); + } + } catch (final IOException ioEx) { + logger.error("", ioEx); + } + + return entities; + } + + @Override + public final String getMime() { + return MediaType.APPLICATION_JSON.toString(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/TestMarshallerFactory.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/TestMarshallerFactory.java new file mode 100644 index 0000000000..d7cd875ae4 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/TestMarshallerFactory.java @@ -0,0 +1,48 @@ +package com.baeldung.mime; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@Profile("test") +public class TestMarshallerFactory implements FactoryBean { + + @Autowired + private Environment env; + + public TestMarshallerFactory() { + super(); + } + + // API + + @Override + public IMarshaller getObject() { + final String testMime = env.getProperty("test.mime"); + if (testMime != null) { + switch (testMime) { + case "json": + return new JacksonMarshaller(); + case "xml": + return new XStreamMarshaller(); + default: + throw new IllegalStateException(); + } + } + + return new JacksonMarshaller(); + } + + @Override + public Class getObjectType() { + return IMarshaller.class; + } + + @Override + public boolean isSingleton() { + return true; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java new file mode 100644 index 0000000000..2c67694e83 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java @@ -0,0 +1,46 @@ +package com.baeldung.mime; + +import java.util.List; + +import org.springframework.http.MediaType; + +import com.baeldung.etag.Foo; +import com.thoughtworks.xstream.XStream; + +public final class XStreamMarshaller implements IMarshaller { + + private XStream xstream; + + public XStreamMarshaller() { + super(); + + xstream = new XStream(); + xstream.autodetectAnnotations(true); + xstream.processAnnotations(Foo.class); + } + + // API + + @Override + public final String encode(final T resource) { + return xstream.toXML(resource); + } + + @SuppressWarnings("unchecked") + @Override + public final T decode(final String resourceAsString, final Class clazz) { + return (T) xstream.fromXML(resourceAsString); + } + + @SuppressWarnings("unchecked") + @Override + public List decodeList(final String resourcesAsString, final Class clazz) { + return this.decode(resourcesAsString, List.class); + } + + @Override + public final String getMime() { + return MediaType.APPLICATION_XML.toString(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/students/StudentControllerIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/students/StudentControllerIntegrationTest.java new file mode 100644 index 0000000000..577dbb6eb1 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/students/StudentControllerIntegrationTest.java @@ -0,0 +1,73 @@ +package com.baeldung.students; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +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.request.MockMvcRequestBuilders.put; +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.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class StudentControllerIntegrationTest { + + private static final String STUDENTS_PATH = "/students/"; + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenReadAll_thenStatusIsOk() throws Exception { + this.mockMvc.perform(get(STUDENTS_PATH)) + .andExpect(status().isOk()); + } + + @Test + public void whenReadOne_thenStatusIsOk() throws Exception { + this.mockMvc.perform(get(STUDENTS_PATH + 1)) + .andExpect(status().isOk()); + } + + @Test + public void whenCreate_thenStatusIsCreated() throws Exception { + Student student = new Student(10, "Albert", "Einstein"); + this.mockMvc.perform(post(STUDENTS_PATH).content(asJsonString(student)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isCreated()); + } + + @Test + public void whenUpdate_thenStatusIsOk() throws Exception { + Student student = new Student(1, "Nikola", "Tesla"); + this.mockMvc.perform(put(STUDENTS_PATH + 1) + .content(asJsonString(student)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()); + } + + @Test + public void whenDelete_thenStatusIsNoContent() throws Exception { + this.mockMvc.perform(delete(STUDENTS_PATH + 3)) + .andExpect(status().isNoContent()); + } + + private String asJsonString(final Object obj) { + try { + return new ObjectMapper().writeValueAsString(obj); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/spring-boot-mvc-birt/README.md b/spring-boot-modules/spring-boot-mvc-birt/README.md similarity index 100% rename from spring-boot-mvc-birt/README.md rename to spring-boot-modules/spring-boot-mvc-birt/README.md diff --git a/spring-boot-modules/spring-boot-mvc-birt/pom.xml b/spring-boot-modules/spring-boot-mvc-birt/pom.xml new file mode 100644 index 0000000000..f65b851f30 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-birt/pom.xml @@ -0,0 +1,85 @@ + + + 4.0.0 + spring-boot-mvc-birt + 0.0.1-SNAPSHOT + spring-boot-mvc-birt + jar + Module For Spring Boot Integration with BIRT + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-logging + + + ch.qos.logback + logback-classic + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.innoventsolutions.birt.runtime + org.eclipse.birt.runtime_4.8.0-20180626 + ${eclipse.birt.runtime.version} + + + + log4j + log4j + ${log4j.version} + + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + 2.1.1.RELEASE + com.baeldung.birt.engine.ReportEngineApplication + 1.8 + 1.8 + 4.8.0 + + + diff --git a/spring-boot-mvc-birt/reports/csv_data_report.rptdesign b/spring-boot-modules/spring-boot-mvc-birt/reports/csv_data_report.rptdesign similarity index 100% rename from spring-boot-mvc-birt/reports/csv_data_report.rptdesign rename to spring-boot-modules/spring-boot-mvc-birt/reports/csv_data_report.rptdesign diff --git a/spring-boot-mvc-birt/reports/data.csv b/spring-boot-modules/spring-boot-mvc-birt/reports/data.csv similarity index 100% rename from spring-boot-mvc-birt/reports/data.csv rename to spring-boot-modules/spring-boot-mvc-birt/reports/data.csv diff --git a/spring-boot-mvc-birt/reports/static_report.rptdesign b/spring-boot-modules/spring-boot-mvc-birt/reports/static_report.rptdesign similarity index 100% rename from spring-boot-mvc-birt/reports/static_report.rptdesign rename to spring-boot-modules/spring-boot-mvc-birt/reports/static_report.rptdesign diff --git a/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/designer/ReportDesignApplication.java b/spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/designer/ReportDesignApplication.java similarity index 100% rename from spring-boot-mvc-birt/src/main/java/com/baeldung/birt/designer/ReportDesignApplication.java rename to spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/designer/ReportDesignApplication.java diff --git a/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/ReportEngineApplication.java b/spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/ReportEngineApplication.java similarity index 100% rename from spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/ReportEngineApplication.java rename to spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/ReportEngineApplication.java diff --git a/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/controller/BirtReportController.java b/spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/controller/BirtReportController.java similarity index 100% rename from spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/controller/BirtReportController.java rename to spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/controller/BirtReportController.java diff --git a/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/dto/OutputType.java b/spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/dto/OutputType.java similarity index 100% rename from spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/dto/OutputType.java rename to spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/dto/OutputType.java diff --git a/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/dto/Report.java b/spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/dto/Report.java similarity index 100% rename from spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/dto/Report.java rename to spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/dto/Report.java diff --git a/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/service/BirtReportService.java b/spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/service/BirtReportService.java similarity index 100% rename from spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/service/BirtReportService.java rename to spring-boot-modules/spring-boot-mvc-birt/src/main/java/com/baeldung/birt/engine/service/BirtReportService.java diff --git a/spring-boot-mvc-birt/src/main/resources/application.properties b/spring-boot-modules/spring-boot-mvc-birt/src/main/resources/application.properties similarity index 100% rename from spring-boot-mvc-birt/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-mvc-birt/src/main/resources/application.properties diff --git a/spring-boot-mvc/.gitignore b/spring-boot-modules/spring-boot-mvc/.gitignore similarity index 100% rename from spring-boot-mvc/.gitignore rename to spring-boot-modules/spring-boot-mvc/.gitignore diff --git a/spring-boot-modules/spring-boot-mvc/README.md b/spring-boot-modules/spring-boot-mvc/README.md new file mode 100644 index 0000000000..41b98063a6 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/README.md @@ -0,0 +1,12 @@ +## Spring Boot MVC + +This module contains articles about Spring Web MVC in Spring Boot projects. + +### Relevant Articles: + +- [Custom Validation MessageSource in Spring Boot](https://www.baeldung.com/spring-custom-validation-message-source) +- [Display RSS Feed with Spring MVC](https://www.baeldung.com/spring-mvc-rss-feed) +- [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) +- [Setting Up Swagger 2 with a Spring REST API](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) +- [Using Spring ResponseEntity to Manipulate the HTTP Response](https://www.baeldung.com/spring-response-entity) +- More articles: [[next -->]](/spring-boot-modules/spring-boot-mvc-2) diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml new file mode 100644 index 0000000000..6a951ace93 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -0,0 +1,156 @@ + + + 4.0.0 + spring-boot-mvc + spring-boot-mvc + jar + Module For Spring Boot MVC + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + + jcenter-snapshots + jcenter + http://oss.jfrog.org/artifactory/oss-snapshot-local/ + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.apache.tomcat.embed + tomcat-embed-jasper + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + mysql + mysql-connector-java + + + + org.hsqldb + hsqldb + runtime + + + + + org.glassfish + javax.faces + ${javax.faces.version} + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + com.rometools + rome + ${rome.version} + + + + + org.hibernate.validator + hibernate-validator + + + javax.validation + validation-api + + + org.springframework.boot + spring-boot-starter-validation + + + + + io.springfox + springfox-swagger2 + ${spring.fox.version} + + + io.springfox + springfox-swagger-ui + ${spring.fox.version} + + + + io.springfox + springfox-data-rest + ${spring.fox.version} + + + + io.springfox + springfox-bean-validators + ${spring.fox.version} + + + + + org.aspectj + aspectjrt + 1.9.1 + + + org.aspectj + aspectjweaver + 1.9.1 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.springbootmvc.SpringBootMvcApplication + JAR + + + + + + + 3.0.0-SNAPSHOT + + 1.10.0 + 2.3.7 + com.baeldung.springbootmvc.SpringBootMvcApplication + + + diff --git a/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java new file mode 100644 index 0000000000..9fc228b201 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java @@ -0,0 +1,5 @@ +package com.baeldung.nosuchbeandefinitionexception; + +public class BeanB { + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseController.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseController.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseController.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseController.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseWithBuilderController.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseWithBuilderController.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseWithBuilderController.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseWithBuilderController.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedApplication.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedApplication.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedApplication.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedApplication.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedController.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedController.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedController.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedController.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedView.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedView.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedView.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedView.java diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootannotations/MySQLAutoconfiguration.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootannotations/MySQLAutoconfiguration.java new file mode 100644 index 0000000000..62b1329a54 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootannotations/MySQLAutoconfiguration.java @@ -0,0 +1,118 @@ +package com.baeldung.springbootannotations; + +import java.util.Arrays; +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.springframework.boot.autoconfigure.condition.ConditionMessage; +import org.springframework.boot.autoconfigure.condition.ConditionMessage.Style; +import org.springframework.boot.autoconfigure.condition.ConditionOutcome; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnResource; +import org.springframework.boot.autoconfigure.condition.SpringBootCondition; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.Ordered; +import org.springframework.core.env.Environment; +import org.springframework.core.type.AnnotatedTypeMetadata; +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.util.ClassUtils; + +@Configuration +@ConditionalOnClass(DataSource.class) +@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) +@PropertySource("classpath:mysql.properties") +public class MySQLAutoconfiguration { + + @Autowired + private Environment env; + + @Bean + @ConditionalOnProperty(name = "usemysql", havingValue = "local") + @ConditionalOnMissingBean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true&&serverTimezone=UTC"); + dataSource.setUsername("mysqluser"); + dataSource.setPassword("mysqlpass"); + + return dataSource; + } + + @Bean(name = "dataSource") + @ConditionalOnProperty(name = "usemysql", havingValue = "custom") + @ConditionalOnMissingBean + public DataSource dataSource2() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl(env.getProperty("mysql.url")); + dataSource.setUsername(env.getProperty("mysql.user") != null ? env.getProperty("mysql.user") : ""); + dataSource.setPassword(env.getProperty("mysql.pass") != null ? env.getProperty("mysql.pass") : ""); + + return dataSource; + } + + @Bean + @ConditionalOnBean(name = "dataSource") + @ConditionalOnMissingBean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan("com.baeldung.autoconfiguration.example"); + em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + if (additionalProperties() != null) { + em.setJpaProperties(additionalProperties()); + } + return em; + } + + @Bean + @ConditionalOnMissingBean(type = "JpaTransactionManager") + JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory); + return transactionManager; + } + + @ConditionalOnResource(resources = "classpath:mysql.properties") + @Conditional(HibernateCondition.class) + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("mysql-hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("mysql-hibernate.dialect")); + hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("mysql-hibernate.show_sql") != null ? env.getProperty("mysql-hibernate.show_sql") : "false"); + + return hibernateProperties; + } + + static class HibernateCondition extends SpringBootCondition { + + private static final String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" }; + + @Override + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate"); + + return Arrays.stream(CLASS_NAMES).filter(className -> ClassUtils.isPresent(className, context.getClassLoader())).map(className -> ConditionOutcome.match(message.found("class").items(Style.NORMAL, className))).findAny() + .orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES)))); + } + + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoggingController.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoggingController.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoggingController.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoggingController.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoginController.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoginController.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoginController.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoginController.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/CustomMessageSourceConfiguration.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/CustomMessageSourceConfiguration.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/CustomMessageSourceConfiguration.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/CustomMessageSourceConfiguration.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/model/LoginForm.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/model/LoginForm.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/model/LoginForm.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/model/LoginForm.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/Application.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/Application.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/Application.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/Application.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/model/User.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/model/User.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/model/User.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/model/User.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/plugin/EmailAnnotationPlugin.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/plugin/EmailAnnotationPlugin.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/plugin/EmailAnnotationPlugin.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/plugin/EmailAnnotationPlugin.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/repository/UserRepository.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/repository/UserRepository.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/repository/UserRepository.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/repository/UserRepository.java diff --git a/spring-boot-mvc/src/main/resources/application.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/application.properties similarity index 100% rename from spring-boot-mvc/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-mvc/src/main/resources/application.properties diff --git a/spring-boot-vue/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-mvc/src/main/resources/logback.xml similarity index 100% rename from spring-boot-vue/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-mvc/src/main/resources/logback.xml diff --git a/spring-boot-mvc/src/main/resources/messages.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties similarity index 100% rename from spring-boot-mvc/src/main/resources/messages.properties rename to spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties diff --git a/spring-boot-mvc/src/main/resources/messages_fr.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties similarity index 100% rename from spring-boot-mvc/src/main/resources/messages_fr.properties rename to spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/mysql.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/mysql.properties new file mode 100644 index 0000000000..74f1ee1373 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/mysql.properties @@ -0,0 +1,5 @@ +usemysql=local + +mysql-hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +mysql-hibernate.show_sql=true +mysql-hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/spring-boot-mvc/src/main/resources/static/index.html b/spring-boot-modules/spring-boot-mvc/src/main/resources/static/index.html similarity index 100% rename from spring-boot-mvc/src/main/resources/static/index.html rename to spring-boot-modules/spring-boot-mvc/src/main/resources/static/index.html diff --git a/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml b/spring-boot-modules/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml similarity index 100% rename from spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml rename to spring-boot-modules/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml diff --git a/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml b/spring-boot-modules/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-boot-mvc/src/main/webapp/WEB-INF/web.xml rename to spring-boot-modules/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml diff --git a/spring-boot-mvc/src/main/webapp/index.xhtml b/spring-boot-modules/spring-boot-mvc/src/main/webapp/index.xhtml similarity index 100% rename from spring-boot-mvc/src/main/webapp/index.xhtml rename to spring-boot-modules/spring-boot-mvc/src/main/webapp/index.xhtml diff --git a/spring-boot-mvc/src/main/webapp/todo.xhtml b/spring-boot-modules/spring-boot-mvc/src/main/webapp/todo.xhtml similarity index 100% rename from spring-boot-mvc/src/main/webapp/todo.xhtml rename to spring-boot-modules/spring-boot-mvc/src/main/webapp/todo.xhtml diff --git a/spring-boot-mvc/src/test/java/com/baeldung/rss/RssFeedUnitTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/rss/RssFeedUnitTest.java similarity index 100% rename from spring-boot-mvc/src/test/java/com/baeldung/rss/RssFeedUnitTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/rss/RssFeedUnitTest.java diff --git a/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/LoginControllerUnitTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/LoginControllerUnitTest.java similarity index 95% rename from spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/LoginControllerUnitTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/LoginControllerUnitTest.java index 68229f459c..8ccf451e86 100644 --- a/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/LoginControllerUnitTest.java +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/LoginControllerUnitTest.java @@ -15,7 +15,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.baeldung.springbootmvc.config.CustomMessageSourceConfiguration; @RunWith(SpringRunner.class) -@WebMvcTest(value = LoginController.class, secure = false) +@WebMvcTest(value = LoginController.class) @ContextConfiguration(classes = { SpringBootMvcApplication.class, CustomMessageSourceConfiguration.class }) public class LoginControllerUnitTest { diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..209a93d94c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.springbootannotations.MySQLAutoconfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MySQLAutoconfiguration.class) +@WebAppConfiguration +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e73f4e79f7 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.springbootmvc.SpringBootMvcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootMvcApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-nashorn/README.md b/spring-boot-modules/spring-boot-nashorn/README.md similarity index 100% rename from spring-boot-nashorn/README.md rename to spring-boot-modules/spring-boot-nashorn/README.md diff --git a/spring-boot-modules/spring-boot-nashorn/pom.xml b/spring-boot-modules/spring-boot-nashorn/pom.xml new file mode 100644 index 0000000000..c60997005d --- /dev/null +++ b/spring-boot-modules/spring-boot-nashorn/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + com.baeldung.nashorn + spring-boot-nashorn + 1.0 + spring-boot-nashorn + jar + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/Application.java b/spring-boot-modules/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/Application.java similarity index 100% rename from spring-boot-nashorn/src/main/java/com/baeldung/nashorn/Application.java rename to spring-boot-modules/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/Application.java diff --git a/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyRestController.java b/spring-boot-modules/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyRestController.java similarity index 100% rename from spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyRestController.java rename to spring-boot-modules/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyRestController.java diff --git a/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyWebController.java b/spring-boot-modules/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyWebController.java similarity index 100% rename from spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyWebController.java rename to spring-boot-modules/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyWebController.java diff --git a/spring-boot-nashorn/src/main/resources/application.properties b/spring-boot-modules/spring-boot-nashorn/src/main/resources/application.properties similarity index 100% rename from spring-boot-nashorn/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-nashorn/src/main/resources/application.properties diff --git a/spring-boot-nashorn/src/main/resources/static/app.js b/spring-boot-modules/spring-boot-nashorn/src/main/resources/static/app.js similarity index 100% rename from spring-boot-nashorn/src/main/resources/static/app.js rename to spring-boot-modules/spring-boot-nashorn/src/main/resources/static/app.js diff --git a/spring-boot-nashorn/src/main/resources/static/js/react-dom-server.js b/spring-boot-modules/spring-boot-nashorn/src/main/resources/static/js/react-dom-server.js similarity index 100% rename from spring-boot-nashorn/src/main/resources/static/js/react-dom-server.js rename to spring-boot-modules/spring-boot-nashorn/src/main/resources/static/js/react-dom-server.js diff --git a/spring-boot-nashorn/src/main/resources/static/js/react-dom.js b/spring-boot-modules/spring-boot-nashorn/src/main/resources/static/js/react-dom.js similarity index 100% rename from spring-boot-nashorn/src/main/resources/static/js/react-dom.js rename to spring-boot-modules/spring-boot-nashorn/src/main/resources/static/js/react-dom.js diff --git a/spring-boot-nashorn/src/main/resources/static/js/react.js b/spring-boot-modules/spring-boot-nashorn/src/main/resources/static/js/react.js similarity index 100% rename from spring-boot-nashorn/src/main/resources/static/js/react.js rename to spring-boot-modules/spring-boot-nashorn/src/main/resources/static/js/react.js diff --git a/spring-boot-nashorn/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-boot-modules/spring-boot-nashorn/src/main/webapp/WEB-INF/jsp/index.jsp similarity index 100% rename from spring-boot-nashorn/src/main/webapp/WEB-INF/jsp/index.jsp rename to spring-boot-modules/spring-boot-nashorn/src/main/webapp/WEB-INF/jsp/index.jsp diff --git a/spring-boot-parent/README.md b/spring-boot-modules/spring-boot-parent/README.md similarity index 100% rename from spring-boot-parent/README.md rename to spring-boot-modules/spring-boot-parent/README.md diff --git a/spring-boot-modules/spring-boot-parent/pom.xml b/spring-boot-modules/spring-boot-parent/pom.xml new file mode 100644 index 0000000000..cf0a6702ea --- /dev/null +++ b/spring-boot-modules/spring-boot-parent/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + spring-boot-parent + 1.0.0-SNAPSHOT + spring-boot-parent + pom + spring-boot-parent + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + + + + spring-boot-with-starter-parent + spring-boot-with-custom-parent + + + diff --git a/spring-boot-modules/spring-boot-parent/spring-boot-with-custom-parent/pom.xml b/spring-boot-modules/spring-boot-parent/spring-boot-with-custom-parent/pom.xml new file mode 100644 index 0000000000..d08384e34c --- /dev/null +++ b/spring-boot-modules/spring-boot-parent/spring-boot-with-custom-parent/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + spring-boot-with-custom-parent + 1.0.0-SNAPSHOT + spring-boot-with-custom-parent + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + + 1.8 + + + diff --git a/spring-boot-parent/spring-boot-with-custom-parent/src/main/java/com/baeldung/customparent/SpringBootStarterCustomParentApplication.java b/spring-boot-modules/spring-boot-parent/spring-boot-with-custom-parent/src/main/java/com/baeldung/customparent/SpringBootStarterCustomParentApplication.java similarity index 100% rename from spring-boot-parent/spring-boot-with-custom-parent/src/main/java/com/baeldung/customparent/SpringBootStarterCustomParentApplication.java rename to spring-boot-modules/spring-boot-parent/spring-boot-with-custom-parent/src/main/java/com/baeldung/customparent/SpringBootStarterCustomParentApplication.java diff --git a/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml b/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml new file mode 100644 index 0000000000..baba410b39 --- /dev/null +++ b/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + com.baeldung + spring-boot-with-starter-parent + 1.0.0-SNAPSHOT + spring-boot-with-starter-parent + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../../parent-boot-2 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + + + + + + org.springframework.boot + spring-boot-starter-web + + + junit + junit + + + + + 1.8 + 2.1.5.RELEASE + 4.11 + + + diff --git a/spring-boot-parent/spring-boot-with-starter-parent/src/main/java/com/baeldung/starterparent/SpringBootStarterParentApplication.java b/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/src/main/java/com/baeldung/starterparent/SpringBootStarterParentApplication.java similarity index 100% rename from spring-boot-parent/spring-boot-with-starter-parent/src/main/java/com/baeldung/starterparent/SpringBootStarterParentApplication.java rename to spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/src/main/java/com/baeldung/starterparent/SpringBootStarterParentApplication.java diff --git a/spring-boot-modules/spring-boot-performance/README.md b/spring-boot-modules/spring-boot-performance/README.md new file mode 100644 index 0000000000..9443e5bb19 --- /dev/null +++ b/spring-boot-modules/spring-boot-performance/README.md @@ -0,0 +1,8 @@ +## Spring Boot Performance + +This module contains articles about Spring Boot performance. + +### Relevant Articles + +- [Lazy Initialization in Spring Boot 2](https://www.baeldung.com/spring-boot-lazy-initialization) +- [Introduction to Chaos Monkey](https://www.baeldung.com/spring-boot-chaos-monkey) diff --git a/spring-boot-modules/spring-boot-performance/pom.xml b/spring-boot-modules/spring-boot-performance/pom.xml new file mode 100644 index 0000000000..1f3eafd96c --- /dev/null +++ b/spring-boot-modules/spring-boot-performance/pom.xml @@ -0,0 +1,57 @@ + + 4.0.0 + spring-boot-performance + spring-boot-performance + war + This is a simple Spring Boot application taking advantage of the latest Spring Boot improvements/features. Current version: 2.2 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + de.codecentric + chaos-monkey-spring-boot + ${chaos.monkey.version} + + + + + spring-boot-performance + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + + + + com.baeldung.lazyinitialization.Application + 2.0.0 + + diff --git a/spring-boot/src/main/java/com/baeldung/chaosmonkey/SpringBootChaosMonkeyApp.java b/spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/chaosmonkey/SpringBootChaosMonkeyApp.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/chaosmonkey/SpringBootChaosMonkeyApp.java rename to spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/chaosmonkey/SpringBootChaosMonkeyApp.java diff --git a/spring-boot/src/main/java/com/baeldung/chaosmonkey/controller/PermissionsController.java b/spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/chaosmonkey/controller/PermissionsController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/chaosmonkey/controller/PermissionsController.java rename to spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/chaosmonkey/controller/PermissionsController.java diff --git a/spring-boot/src/main/java/com/baeldung/chaosmonkey/service/PermissionsService.java b/spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/chaosmonkey/service/PermissionsService.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/chaosmonkey/service/PermissionsService.java rename to spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/chaosmonkey/service/PermissionsService.java diff --git a/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java b/spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java similarity index 100% rename from spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java rename to spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java diff --git a/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/services/Writer.java b/spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/services/Writer.java similarity index 100% rename from spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/services/Writer.java rename to spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/services/Writer.java diff --git a/spring-boot-modules/spring-boot-performance/src/main/resources/application.properties b/spring-boot-modules/spring-boot-performance/src/main/resources/application.properties new file mode 100644 index 0000000000..3727232ea6 --- /dev/null +++ b/spring-boot-modules/spring-boot-performance/src/main/resources/application.properties @@ -0,0 +1,29 @@ +#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-performance/src/main/resources/application.yml b/spring-boot-modules/spring-boot-performance/src/main/resources/application.yml similarity index 100% rename from spring-boot-performance/src/main/resources/application.yml rename to spring-boot-modules/spring-boot-performance/src/main/resources/application.yml diff --git a/spring-boot-modules/spring-boot-properties/README.md b/spring-boot-modules/spring-boot-properties/README.md new file mode 100644 index 0000000000..f861a01d10 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/README.md @@ -0,0 +1,16 @@ +## Spring Boot Properties + +This module contains articles about Properties in Spring Boot. + +### Relevant Articles: +- [Reloading Properties Files in Spring](https://www.baeldung.com/spring-reloading-properties) +- [Guide to @ConfigurationProperties in Spring Boot](https://www.baeldung.com/configuration-properties-in-spring-boot) +- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) +- [Guide to @EnableConfigurationProperties](https://www.baeldung.com/spring-enable-config-properties) +- [Properties with Spring and Spring Boot](https://www.baeldung.com/properties-with-spring) - checkout the `com.baeldung.properties` package for all scenarios of properties injection and usage +- [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation) +- [Spring YAML Configuration](https://www.baeldung.com/spring-yaml) +- [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults) +- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class) +- [Add Build Properties to a Spring Boot Application](https://www.baeldung.com/spring-boot-build-properties) +- [IntelliJ – Cannot Resolve Spring Boot Configuration Properties Error](https://www.baeldung.com/intellij-resolve-spring-boot-configuration-properties) diff --git a/spring-boot-properties/extra.properties b/spring-boot-modules/spring-boot-properties/extra.properties similarity index 100% rename from spring-boot-properties/extra.properties rename to spring-boot-modules/spring-boot-properties/extra.properties diff --git a/spring-boot-properties/extra2.properties b/spring-boot-modules/spring-boot-properties/extra2.properties similarity index 100% rename from spring-boot-properties/extra2.properties rename to spring-boot-modules/spring-boot-properties/extra2.properties diff --git a/spring-boot-modules/spring-boot-properties/pom.xml b/spring-boot-modules/spring-boot-properties/pom.xml new file mode 100644 index 0000000000..ef9c084f4c --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/pom.xml @@ -0,0 +1,134 @@ + + + 4.0.0 + spring-boot-properties + spring-boot-properties + jar + Spring Boot Properties Module + 0.0.1-SNAPSHOT + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + commons-configuration + commons-configuration + ${commons-configuration.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.cloud + spring-cloud-starter + + + com.google.guava + guava + ${guava.version} + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + + + org.springframework.boot + spring-boot-configuration-processor + ${configuration-processor.version} + true + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + spring-boot-properties + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + @ + + false + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + json + + + + + + + + + + 1.8 + Greenwich.SR1 + 1.10 + 20.0 + 4.4.11 + @ + 2.2.4.RELEASE + com.baeldung.buildproperties.Application + + + diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/buildproperties/Application.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/buildproperties/Application.java new file mode 100644 index 0000000000..405cec3eac --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/buildproperties/Application.java @@ -0,0 +1,18 @@ +package com.baeldung.buildproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@ComponentScan(basePackages = "com.baeldung.buildproperties") +@PropertySource("classpath:build.properties") +//@PropertySource("classpath:build.yml") +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/buildproperties/BuildInfoService.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/buildproperties/BuildInfoService.java new file mode 100644 index 0000000000..2a0d27188e --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/buildproperties/BuildInfoService.java @@ -0,0 +1,21 @@ +package com.baeldung.buildproperties; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +@Service +public class BuildInfoService { + @Value("${application-description}") + private String applicationDescription; + + @Value("${application-version}") + private String applicationVersion; + + public String getApplicationDescription() { + return applicationDescription; + } + + public String getApplicationVersion() { + return applicationVersion; + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/CustomProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/CustomProperties.java new file mode 100644 index 0000000000..398b7557c4 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/CustomProperties.java @@ -0,0 +1,37 @@ +package com.baeldung.configuration.processor; + +import org.springframework.boot.context.properties.*; +import org.springframework.context.annotation.*; + +@Configuration +@ConfigurationProperties(prefix = "com.baeldung") +public class CustomProperties { + + /** + * The url to connect to. + */ + String url; + + /** + * The time to wait for the connection. + */ + private int timeoutInMilliSeconds = 1000; + + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public int getTimeoutInMilliSeconds() { + return timeoutInMilliSeconds; + } + + public void setTimeoutInMilliSeconds(int timeoutInMilliSeconds) { + this.timeoutInMilliSeconds = timeoutInMilliSeconds; + } + +} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/DemoApplication.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/DemoApplication.java new file mode 100644 index 0000000000..1a35de86da --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/DemoApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.configuration.processor; + +import org.springframework.boot.*; +import org.springframework.boot.autoconfigure.*; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/JdbcProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/JdbcProperties.java new file mode 100644 index 0000000000..bbd193acba --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/JdbcProperties.java @@ -0,0 +1,21 @@ +package com.baeldung.configuration.processor; + +import org.springframework.boot.context.properties.*; +import org.springframework.context.annotation.*; +import org.springframework.beans.factory.annotation.*; + +@Configuration +@ConfigurationProperties(prefix = "com.baeldung") +public class JdbcProperties { + + @Value("${jdbc.url:jdbc:postgresql:/localhost:5432}") + private String jdbcUrl; + + public String getJdbcUrl() { + return jdbcUrl; + } + + public void setJdbcUrl(String jdbcUrl) { + this.jdbcUrl = jdbcUrl; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/PropertyBeanInjection.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/PropertyBeanInjection.java new file mode 100644 index 0000000000..89a8f9458c --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configuration/processor/PropertyBeanInjection.java @@ -0,0 +1,29 @@ +package com.baeldung.configuration.processor; + +import org.springframework.beans.factory.annotation.*; +import org.springframework.stereotype.*; + +@Component +public class PropertyBeanInjection { + + private CustomProperties customProperties; + + private JdbcProperties jdbcProperties; + + PropertyBeanInjection(@Autowired CustomProperties customProperties, @Autowired JdbcProperties jdbcProperties) { + this.customProperties = customProperties; + this.jdbcProperties = jdbcProperties; + } + + String getUrl() { + return customProperties.getUrl(); + } + + String getJdbcUrl() { + return jdbcProperties.getJdbcUrl(); + } + + int getTimeoutInMilliseconds() { + return customProperties.getTimeoutInMilliSeconds(); + } +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ConfigProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ConfigProperties.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ConfigProperties.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ConfigProperties.java diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Database.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Database.java new file mode 100644 index 0000000000..990ede35cd --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Database.java @@ -0,0 +1,36 @@ +package com.baeldung.configurationproperties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + + +@ConfigurationProperties(prefix = "database") +public class Database { + + String url; + String username; + String password; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/DatabaseConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/DatabaseConfig.java new file mode 100644 index 0000000000..8f17c98f03 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/DatabaseConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.configurationproperties; + +import org.springframework.core.env.Environment; +import org.springframework.beans.factory.annotation.*; +import org.springframework.context.annotation.*; + +@Configuration +public class DatabaseConfig { + + @Autowired private Environment env; + + @Bean(name="dataSource") + public Database dataSource() { + + Database dataSource = new Database(); + dataSource.setUrl(env.getProperty("jdbc.url")); + dataSource.setUsername(env.getProperty("database.username")); + dataSource.setPassword(env.getProperty("database.password")); + + return dataSource; + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/DatabaseConfigPropertiesApp.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/DatabaseConfigPropertiesApp.java new file mode 100644 index 0000000000..bb1c937f60 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/DatabaseConfigPropertiesApp.java @@ -0,0 +1,13 @@ +package com.baeldung.configurationproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackageClasses = {Database.class,DatabaseConfig.class}) +public class DatabaseConfigPropertiesApp{ + + public static void main(String[]args) {SpringApplication.run(DatabaseConfigPropertiesApp.class,args);} + +} \ No newline at end of file diff --git a/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Employee.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Employee.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Employee.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Employee.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/EmployeeConverter.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/EmployeeConverter.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/configurationproperties/EmployeeConverter.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/EmployeeConverter.java diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ImmutableConfigPropertiesApp.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ImmutableConfigPropertiesApp.java new file mode 100644 index 0000000000..b9d84238c3 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ImmutableConfigPropertiesApp.java @@ -0,0 +1,14 @@ +package com.baeldung.configurationproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; + +@SpringBootApplication +@ConfigurationPropertiesScan +public class ImmutableConfigPropertiesApp { + + public static void main(String[] args) { + SpringApplication.run(ImmutableConfigPropertiesApp.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ImmutableCredentials.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ImmutableCredentials.java new file mode 100644 index 0000000000..a58e4143e5 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ImmutableCredentials.java @@ -0,0 +1,31 @@ +package com.baeldung.configurationproperties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.ConstructorBinding; + +@ConfigurationProperties(prefix = "mail.credentials") +@ConstructorBinding +public class ImmutableCredentials { + + private final String authMethod; + private final String username; + private final String password; + + public ImmutableCredentials(String authMethod, String username, String password) { + this.authMethod = authMethod; + this.username = username; + this.password = password; + } + + public String getAuthMethod() { + return authMethod; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Item.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Item.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Item.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Item.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertiesConversionApplication.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertiesConversionApplication.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertiesConversionApplication.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertiesConversionApplication.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertyConversion.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertyConversion.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertyConversion.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertyConversion.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/AdditionalConfiguration.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/AdditionalConfiguration.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/AdditionalConfiguration.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/AdditionalConfiguration.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/AdditionalProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/AdditionalProperties.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/AdditionalProperties.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/AdditionalProperties.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java similarity index 90% rename from spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java index 41f26d51f7..e54f28837d 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.configurationproperties.ConfigProperties; @SpringBootApplication -@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class }) +@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class, Database.class }) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/CustomJsonProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/CustomJsonProperties.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/CustomJsonProperties.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/CustomJsonProperties.java diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java new file mode 100644 index 0000000000..6e798672e7 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java @@ -0,0 +1,33 @@ +package com.baeldung.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "database") +public class Database { + + private String url; + private String username; + private String password; + + public String getUrl() { + return url; + } + public void setUrl(String url) { + this.url = url; + } + 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-boot-properties/src/main/java/com/baeldung/properties/JsonProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonProperties.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/JsonProperties.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonProperties.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/core/ComponentInXmlUsingProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/core/ComponentInXmlUsingProperties.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/core/ComponentInXmlUsingProperties.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/core/ComponentInXmlUsingProperties.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/core/ComponentUsingProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/core/ComponentUsingProperties.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/core/ComponentUsingProperties.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/core/ComponentUsingProperties.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java similarity index 93% rename from spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java index d43f18f6a7..5b954f8941 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java @@ -7,7 +7,7 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration -@ComponentScan("org.baeldung.properties.core") +@ComponentScan("com.baeldung.properties.core") @PropertySource("classpath:foo.properties") public class ExternalPropertiesWithJavaConfig { diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java similarity index 91% rename from spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java index 6d105428d9..9080e3d0ba 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:configForProperties.xml") -@ComponentScan("org.baeldung.core") +@ComponentScan("com.baeldung.core") public class ExternalPropertiesWithXmlConfig { public ExternalPropertiesWithXmlConfig() { diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java similarity index 91% rename from spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java index 6f1e4c8490..f45f5b6a03 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:configForPropertiesOne.xml") -@ComponentScan("org.baeldung.core") +@ComponentScan("com.baeldung.core") public class ExternalPropertiesWithXmlConfigOne { public ExternalPropertiesWithXmlConfigOne() { diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigTwo.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigTwo.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigTwo.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigTwo.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/BasicPropertiesWithJavaConfig.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfig.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfig.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfig.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfigOther.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfigOther.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfigOther.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfigOther.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertyPlaceholderConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertyPlaceholderConfig.java new file mode 100644 index 0000000000..0d1eb4ccf7 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertyPlaceholderConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.properties.spring; + +import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.*; + +@Configuration +public class PropertyPlaceholderConfig { + + public PropertyPlaceholderConfig(){ + super(); + } + + @Bean + public static PropertyPlaceholderConfigurer properties() { + PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); + Resource[] resources = new ClassPathResource[]{ new ClassPathResource("foo.properties") }; + ppc.setLocations( resources ); + ppc.setIgnoreUnresolvablePlaceholders( true ); + return ppc; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertySourcesPlaceholderConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertySourcesPlaceholderConfig.java new file mode 100644 index 0000000000..8ff464e4cf --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/spring/PropertySourcesPlaceholderConfig.java @@ -0,0 +1,24 @@ +package com.baeldung.properties.spring; + +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.*; + +@Configuration +public class PropertySourcesPlaceholderConfig{ + + public PropertySourcesPlaceholderConfig(){ + super(); + } + + @Bean + public static PropertySourcesPlaceholderConfigurer properties(){ + PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer(); + Resource[] resources = new ClassPathResource[]{ new ClassPathResource("foo.properties") }; + pspc.setLocations(resources); + pspc.setIgnoreUnresolvablePlaceholders(true); + return pspc; + } + +} \ No newline at end of file diff --git a/spring-boot-properties/src/main/java/com/baeldung/value/ClassNotManagedBySpring.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ClassNotManagedBySpring.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/value/ClassNotManagedBySpring.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ClassNotManagedBySpring.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/value/InitializerBean.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/InitializerBean.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/value/InitializerBean.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/InitializerBean.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/value/SomeBean.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/SomeBean.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/value/SomeBean.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/SomeBean.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/value/ValuesApp.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ValuesApp.java similarity index 100% rename from spring-boot-properties/src/main/java/com/baeldung/value/ValuesApp.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ValuesApp.java diff --git a/spring-boot-properties/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java similarity index 97% rename from spring-boot-properties/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java index d2cda19ae6..589f891e6b 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java @@ -1,75 +1,75 @@ -package com.baeldung.valuewithdefaults; - -import java.util.Arrays; -import java.util.List; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.util.Assert; - -import com.google.common.collect.Lists; -import com.google.common.primitives.Ints; - -/** - * Demonstrates setting defaults for @Value annotation. Note that there are no properties - * defined in the specified property source. We also assume that the user here - * does not have a system property named some.key. - * - */ -@Configuration -@PropertySource(name = "myProperties", value = "valueswithdefaults.properties") -public class ValuesWithDefaultsApp { - - @Value("${some.key:my default value}") - private String stringWithDefaultValue; - - @Value("${some.key:}") - private String stringWithBlankDefaultValue; - - @Value("${some.key:true}") - private boolean booleanWithDefaultValue; - - @Value("${some.key:42}") - private int intWithDefaultValue; - - @Value("${some.key:one,two,three}") - private String[] stringArrayWithDefaults; - - @Value("${some.key:1,2,3}") - private int[] intArrayWithDefaults; - - @Value("#{systemProperties['some.key'] ?: 'my default system property value'}") - private String spelWithDefaultValue; - - - public static void main(String[] args) { - ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesWithDefaultsApp.class); - } - - @PostConstruct - public void afterInitialize() { - // strings - Assert.isTrue(stringWithDefaultValue.equals("my default value")); - Assert.isTrue(stringWithBlankDefaultValue.equals("")); - - // other primitives - Assert.isTrue(booleanWithDefaultValue); - Assert.isTrue(intWithDefaultValue == 42); - - // arrays - List stringListValues = Lists.newArrayList("one", "two", "three"); - Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues)); - - List intListValues = Lists.newArrayList(1, 2, 3); - Assert.isTrue(Ints.asList(intArrayWithDefaults).containsAll(intListValues)); - - // SpEL - Assert.isTrue(spelWithDefaultValue.equals("my default system property value")); - - } -} +package com.baeldung.valuewithdefaults; + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.util.Assert; + +import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; + +/** + * Demonstrates setting defaults for @Value annotation. Note that there are no properties + * defined in the specified property source. We also assume that the user here + * does not have a system property named some.key. + * + */ +@Configuration +@PropertySource(name = "myProperties", value = "valueswithdefaults.properties") +public class ValuesWithDefaultsApp { + + @Value("${some.key:my default value}") + private String stringWithDefaultValue; + + @Value("${some.key:}") + private String stringWithBlankDefaultValue; + + @Value("${some.key:true}") + private boolean booleanWithDefaultValue; + + @Value("${some.key:42}") + private int intWithDefaultValue; + + @Value("${some.key:one,two,three}") + private String[] stringArrayWithDefaults; + + @Value("${some.key:1,2,3}") + private int[] intArrayWithDefaults; + + @Value("#{systemProperties['some.key'] ?: 'my default system property value'}") + private String spelWithDefaultValue; + + + public static void main(String[] args) { + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesWithDefaultsApp.class); + } + + @PostConstruct + public void afterInitialize() { + // strings + Assert.isTrue(stringWithDefaultValue.equals("my default value")); + Assert.isTrue(stringWithBlankDefaultValue.equals("")); + + // other primitives + Assert.isTrue(booleanWithDefaultValue); + Assert.isTrue(intWithDefaultValue == 42); + + // arrays + List stringListValues = Lists.newArrayList("one", "two", "three"); + Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues)); + + List intListValues = Lists.newArrayList(1, 2, 3); + Assert.isTrue(Ints.asList(intArrayWithDefaults).containsAll(intListValues)); + + // SpEL + Assert.isTrue(spelWithDefaultValue.equals("my default system property value")); + + } +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/yaml/MyApplication.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/yaml/MyApplication.java similarity index 97% rename from spring-boot-properties/src/main/java/com/baeldung/yaml/MyApplication.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/yaml/MyApplication.java index 4a585df998..d42b731213 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/yaml/MyApplication.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/yaml/MyApplication.java @@ -1,31 +1,31 @@ -/* - * 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.yaml; - -import java.util.Collections; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class MyApplication implements CommandLineRunner { - - @Autowired - private YAMLConfig myConfig; - - public static void main(String[] args) { - SpringApplication app = new SpringApplication(MyApplication.class); - app.run(); - } - - public void run(String... args) throws Exception { - System.out.println("using environment:" + myConfig.getEnvironment()); - System.out.println("name:" + myConfig.getName()); - System.out.println("servers:" + myConfig.getServers()); - } - -} +/* + * 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.yaml; + +import java.util.Collections; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MyApplication implements CommandLineRunner { + + @Autowired + private YAMLConfig myConfig; + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(MyApplication.class); + app.run(); + } + + public void run(String... args) throws Exception { + System.out.println("using environment:" + myConfig.getEnvironment()); + System.out.println("name:" + myConfig.getName()); + System.out.println("servers:" + myConfig.getServers()); + } + +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/yaml/YAMLConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/yaml/YAMLConfig.java similarity index 95% rename from spring-boot-properties/src/main/java/com/baeldung/yaml/YAMLConfig.java rename to spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/yaml/YAMLConfig.java index 313b920502..ad633c4b56 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/yaml/YAMLConfig.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/yaml/YAMLConfig.java @@ -1,41 +1,41 @@ -package com.baeldung.yaml; - -import java.util.ArrayList; -import java.util.List; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties -@ConfigurationProperties -public class YAMLConfig { - private String name; - private String environment; - private List servers = new ArrayList(); - - public List getServers() { - return servers; - } - - public void setServers(List servers) { - this.servers = servers; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEnvironment() { - return environment; - } - - public void setEnvironment(String environment) { - this.environment = environment; - } - -} +package com.baeldung.yaml; + +import java.util.ArrayList; +import java.util.List; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties +@ConfigurationProperties +public class YAMLConfig { + private String name; + private String environment; + private List servers = new ArrayList(); + + public List getServers() { + return servers; + } + + public void setServers(List servers) { + this.servers = servers; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEnvironment() { + return environment; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + +} diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/application.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/application.properties new file mode 100644 index 0000000000..af38556f81 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/application.properties @@ -0,0 +1,5 @@ +management.endpoints.web.exposure.include=refresh +spring.properties.refreshDelay=1000 +spring.config.location=file:extra.properties +spring.main.allow-bean-definition-overriding=true + diff --git a/spring-boot-properties/src/main/resources/application.yml b/spring-boot-modules/spring-boot-properties/src/main/resources/application.yml similarity index 100% rename from spring-boot-properties/src/main/resources/application.yml rename to spring-boot-modules/spring-boot-properties/src/main/resources/application.yml diff --git a/spring-boot-properties/src/main/resources/bar.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/bar.properties similarity index 100% rename from spring-boot-properties/src/main/resources/bar.properties rename to spring-boot-modules/spring-boot-properties/src/main/resources/bar.properties diff --git a/spring-boot-properties/src/main/resources/basicConfigForProperties.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/basicConfigForProperties.xml similarity index 100% rename from spring-boot-properties/src/main/resources/basicConfigForProperties.xml rename to spring-boot-modules/spring-boot-properties/src/main/resources/basicConfigForProperties.xml diff --git a/spring-boot-properties/src/main/resources/basicConfigForPropertiesOne.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/basicConfigForPropertiesOne.xml similarity index 100% rename from spring-boot-properties/src/main/resources/basicConfigForPropertiesOne.xml rename to spring-boot-modules/spring-boot-properties/src/main/resources/basicConfigForPropertiesOne.xml diff --git a/spring-boot-properties/src/main/resources/basicConfigForPropertiesTwo.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/basicConfigForPropertiesTwo.xml similarity index 100% rename from spring-boot-properties/src/main/resources/basicConfigForPropertiesTwo.xml rename to spring-boot-modules/spring-boot-properties/src/main/resources/basicConfigForPropertiesTwo.xml diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/build.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/build.properties new file mode 100644 index 0000000000..5bd0a50a17 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/build.properties @@ -0,0 +1,2 @@ +application-version=@project.version@ +application-description=@project.description@ \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/build.yml b/spring-boot-modules/spring-boot-properties/src/main/resources/build.yml new file mode 100644 index 0000000000..528d2e3440 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/build.yml @@ -0,0 +1,2 @@ +application-description: ^project.description^ +application-version: ^project.version^ \ No newline at end of file diff --git a/spring-boot-properties/src/main/resources/child.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/child.properties similarity index 100% rename from spring-boot-properties/src/main/resources/child.properties rename to spring-boot-modules/spring-boot-properties/src/main/resources/child.properties diff --git a/spring-boot-properties/src/main/resources/configForProperties.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml similarity index 80% rename from spring-boot-properties/src/main/resources/configForProperties.xml rename to spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml index d796f791cb..4468bb485f 100644 --- a/spring-boot-properties/src/main/resources/configForProperties.xml +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml @@ -7,10 +7,14 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd" > - + + + + + \ No newline at end of file diff --git a/spring-boot-properties/src/main/resources/configForPropertiesOne.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/configForPropertiesOne.xml similarity index 100% rename from spring-boot-properties/src/main/resources/configForPropertiesOne.xml rename to spring-boot-modules/spring-boot-properties/src/main/resources/configForPropertiesOne.xml diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/configForPropertyPlaceholderBeans.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/configForPropertyPlaceholderBeans.xml new file mode 100644 index 0000000000..a296cf5169 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/configForPropertyPlaceholderBeans.xml @@ -0,0 +1,23 @@ + + + + + + + classpath:foo.properties + + + + + + + + + classpath:foo.properties + + + + + \ No newline at end of file diff --git a/spring-boot-properties/src/main/resources/configprops.json b/spring-boot-modules/spring-boot-properties/src/main/resources/configprops.json similarity index 100% rename from spring-boot-properties/src/main/resources/configprops.json rename to spring-boot-modules/spring-boot-properties/src/main/resources/configprops.json diff --git a/spring-boot-properties/src/main/resources/configprops.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/configprops.properties similarity index 100% rename from spring-boot-properties/src/main/resources/configprops.properties rename to spring-boot-modules/spring-boot-properties/src/main/resources/configprops.properties diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/configuration-processor.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/configuration-processor.properties new file mode 100644 index 0000000000..b68a4fbda3 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/configuration-processor.properties @@ -0,0 +1,3 @@ +com.baeldung.url=www.abc.test.com +com.baeldung.jdbc.url= +com.baeldung.timeout-in-milli-seconds=2000 diff --git a/spring-boot-properties/src/main/resources/conversion.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/conversion.properties similarity index 100% rename from spring-boot-properties/src/main/resources/conversion.properties rename to spring-boot-modules/spring-boot-properties/src/main/resources/conversion.properties diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties new file mode 100644 index 0000000000..6524ce6109 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties @@ -0,0 +1,4 @@ +database.url=jdbc:postgresql:/localhost:5432/instance +database.username=foo +database.password=bar +jdbc.url=jdbc:postgresql:/localhost:5432 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/database.yml b/spring-boot-modules/spring-boot-properties/src/main/resources/database.yml new file mode 100644 index 0000000000..8404d9411a --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/database.yml @@ -0,0 +1,5 @@ +database: + url: jdbc:postresql:/localhost:5432/instance + username: foo + password: bar +secret: foo \ No newline at end of file diff --git a/spring-boot-properties/src/main/resources/foo.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/foo.properties similarity index 100% rename from spring-boot-properties/src/main/resources/foo.properties rename to spring-boot-modules/spring-boot-properties/src/main/resources/foo.properties diff --git a/spring-boot-properties/src/main/resources/parent.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/parent.properties similarity index 100% rename from spring-boot-properties/src/main/resources/parent.properties rename to spring-boot-modules/spring-boot-properties/src/main/resources/parent.properties diff --git a/spring-boot-properties/src/main/resources/values.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/values.properties similarity index 100% rename from spring-boot-properties/src/main/resources/values.properties rename to spring-boot-modules/spring-boot-properties/src/main/resources/values.properties diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/valueswithdefaults.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/valueswithdefaults.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java new file mode 100644 index 0000000000..2cb27e1844 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.buildproperties; + +import static org.junit.Assert.assertThat; + +import org.hamcrest.Matchers; +import org.junit.jupiter.api.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) +class BuildInfoServiceIntegrationTest { + + @Autowired + private BuildInfoService service; + + @Test + void whenGetApplicationDescription_thenSuccess() { + assertThat(service.getApplicationDescription(), Matchers.is("Spring Boot Properties Module")); + assertThat(service.getApplicationVersion(), Matchers.is("0.0.1-SNAPSHOT")); + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configuration/processor/PropertyBeanInjectionUnitTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configuration/processor/PropertyBeanInjectionUnitTest.java new file mode 100644 index 0000000000..eb6add2b94 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configuration/processor/PropertyBeanInjectionUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.configuration.processor; + +import org.junit.jupiter.api.*; +import org.junit.runner.*; +import org.springframework.beans.factory.annotation.*; +import org.springframework.boot.test.context.*; +import org.springframework.test.context.*; +import org.springframework.test.context.junit4.*; + +@RunWith(SpringRunner.class) +@TestPropertySource("/configuration-processor.properties") +@SpringBootTest(classes = DemoApplication.class) +class PropertyBeanInjectionUnitTest { + + @Autowired + private PropertyBeanInjection propertyBeanInjection; + + @Test + void checkThatJdbcPropertiesHaveTheCorrectValueFromPropertiesFile() { + Assertions.assertEquals("jdbc:postgresql:/localhost:5432", propertyBeanInjection.getJdbcUrl()); + } + + @Test + void checkThatCustomPropertiesHaveTheCorrectValueFromPropertiesFile() { + Assertions.assertEquals("www.abc.test.com", propertyBeanInjection.getUrl()); + Assertions.assertEquals(2000, propertyBeanInjection.getTimeoutInMilliseconds()); + } + +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java similarity index 77% rename from spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java index 141400b1fe..2b0833c387 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java @@ -4,6 +4,7 @@ import org.junit.Assert; 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.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; @@ -13,13 +14,17 @@ import com.baeldung.properties.AdditionalProperties; import com.baeldung.properties.ConfigPropertiesDemoApplication; @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigPropertiesDemoApplication.class) -@TestPropertySource("classpath:configprops-test.properties") +@SpringBootTest(classes = {ConfigPropertiesDemoApplication.class, DatabaseConfigPropertiesApp.class}) +@TestPropertySource(locations = {"classpath:configprops-test.properties", "classpath:database-test.properties"}) public class ConfigPropertiesIntegrationTest { @Autowired private ConfigProperties properties; + @Autowired + @Qualifier("dataSource") + private Database databaseProperties; + @Autowired private AdditionalProperties additionalProperties; @@ -53,4 +58,11 @@ public class ConfigPropertiesIntegrationTest { Assert.assertTrue(additionalProperties.getUnit().equals("km")); Assert.assertTrue(additionalProperties.getMax() == 100); } + + @Test + public void whenDatabasePropertyQueriedthenReturnsProperty() { + Assert.assertTrue(databaseProperties.getUrl().equals("jdbc:postgresql:/localhost:5432")); + Assert.assertTrue(databaseProperties.getUsername().equals("foo")); + Assert.assertTrue(databaseProperties.getPassword().equals("bar")); + } } diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java new file mode 100644 index 0000000000..0b9bd797ae --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.configurationproperties; + +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; + +import com.baeldung.properties.ConfigPropertiesDemoApplication; +import com.baeldung.properties.Database; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigPropertiesDemoApplication.class) +@TestPropertySource("classpath:application.properties") +public class DatabasePropertiesIntegrationTest { + + @Autowired + private Database database; + + @Test + public void testDatabaseProperties() { + Assert.assertNotNull(database); + Assert.assertEquals("jdbc:postgresql:/localhost:5432/instance", database.getUrl()); + Assert.assertEquals("foo", database.getUsername()); + Assert.assertEquals("bar", database.getPassword()); + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ImmutableConfigurationPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ImmutableConfigurationPropertiesIntegrationTest.java new file mode 100644 index 0000000000..a45932f7be --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ImmutableConfigurationPropertiesIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.configurationproperties; + +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; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ImmutableConfigPropertiesApp.class) +@TestPropertySource("classpath:configprops-test.properties") +public class ImmutableConfigurationPropertiesIntegrationTest { + + @Autowired + private ImmutableCredentials immutableCredentials; + + @Test + public void whenConstructorBindingUsed_thenPropertiesCorrectlyBound() { + assertThat(immutableCredentials.getAuthMethod()).isEqualTo("SHA1"); + assertThat(immutableCredentials.getUsername()).isEqualTo("john"); + assertThat(immutableCredentials.getPassword()).isEqualTo("password"); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/PropertiesConversionIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/PropertiesConversionIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/configurationproperties/PropertiesConversionIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/PropertiesConversionIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/basic/BasicPropertiesWithJavaIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/basic/BasicPropertiesWithJavaIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/basic/BasicPropertiesWithJavaIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/basic/BasicPropertiesWithJavaIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/basic/ExtendedPropertiesWithJavaIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/basic/ExtendedPropertiesWithJavaIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/basic/ExtendedPropertiesWithJavaIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/basic/ExtendedPropertiesWithJavaIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithJavaIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithJavaIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithJavaIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithJavaIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithMultipleXmlsIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithMultipleXmlsIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithMultipleXmlsIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithMultipleXmlsIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithXmlIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithXmlIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithXmlIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/basic/PropertiesWithXmlIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithJavaIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithMultipleXmlsIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePlaceholdersJavaConfigIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePlaceholdersJavaConfigIntegrationTest.java new file mode 100644 index 0000000000..8ebda90321 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePlaceholdersJavaConfigIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung.properties.multiple; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import com.baeldung.properties.spring.PropertyPlaceholderConfig; +import com.baeldung.properties.spring.PropertySourcesPlaceholderConfig; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringJUnitConfig({PropertyPlaceholderConfig.class, PropertySourcesPlaceholderConfig.class}) +public class MultiplePlaceholdersJavaConfigIntegrationTest { + + @Value("${key.something}") + private String something; + + + @Test + public void whenReadInjectedValues_thenGetCorrectValues() { + assertThat(something).isEqualTo("val"); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePlaceholdersXmlConfigIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePlaceholdersXmlConfigIntegrationTest.java new file mode 100644 index 0000000000..b863e2e080 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePlaceholdersXmlConfigIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.properties.multiple; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.assertj.core.api.Assertions.assertThat; + + +@SpringJUnitConfig(locations = "classpath:configForPropertyPlaceholderBeans.xml") +public class MultiplePlaceholdersXmlConfigIntegrationTest { + + @Value("${foo}") + private String something; + + @Value("${key.something}") + private String something2; + + + @Test + public void whenReadInjectedValues_thenGetCorrectValues() { + assertThat(something).isEqualTo("bar"); + assertThat(something2).isEqualTo("val"); + } +} \ No newline at end of file diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesJavaConfigIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesJavaConfigIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesJavaConfigIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesJavaConfigIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java similarity index 84% rename from spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java index db71e816dd..6827ee1cf1 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java @@ -13,9 +13,12 @@ public class MultiplePropertiesXmlConfigIntegrationTest { @Value("${key.something2}") private String something2; + @Value("${jdbc.url}") private String jdbcUrl; + @Test public void whenReadInjectedValues_thenGetCorrectValues() { assertThat(something).isEqualTo("val"); assertThat(something2).isEqualTo("val2"); + assertThat(jdbcUrl).isEqualTo("jdbc:postgresql:/localhost:5432"); } } diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ChildValueHolder.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ChildValueHolder.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ChildValueHolder.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ChildValueHolder.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentValueHolder.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentValueHolder.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentValueHolder.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/ParentValueHolder.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/FilePropertyInjectionUnitTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/FilePropertyInjectionUnitTest.java new file mode 100644 index 0000000000..874f632401 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/FilePropertyInjectionUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.properties.testproperty; + +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@TestPropertySource("/foo.properties") +public class FilePropertyInjectionUnitTest { + + @Value("${foo}") + private String foo; + + @Test + public void whenFilePropertyProvided_thenProperlyInjected() { + assertThat(foo).isEqualTo("bar"); + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/PropertyInjectionUnitTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/PropertyInjectionUnitTest.java new file mode 100644 index 0000000000..9492e18322 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/PropertyInjectionUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.properties.testproperty; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@TestPropertySource(properties = {"foo=bar"}) +public class PropertyInjectionUnitTest { + + @Value("${foo}") + private String foo; + + @Test + public void whenPropertyProvided_thenProperlyInjected() { + assertThat(foo).isEqualTo("bar"); + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/SpringBootPropertyInjectionIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/SpringBootPropertyInjectionIntegrationTest.java new file mode 100644 index 0000000000..fdca7e814d --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/SpringBootPropertyInjectionIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung.properties.testproperty; + +import com.baeldung.properties.reloading.SpringBootPropertiesTestApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(properties = {"foo=bar"}, classes = SpringBootPropertiesTestApplication.class) +public class SpringBootPropertyInjectionIntegrationTest { + + @Value("${foo}") + private String foo; + + @Test + public void whenSpringBootPropertyProvided_thenProperlyInjected() { + assertThat(foo).isEqualTo("bar"); + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/test/IntegrationTestSuite.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/test/IntegrationTestSuite.java new file mode 100644 index 0000000000..0e0f8f6230 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/test/IntegrationTestSuite.java @@ -0,0 +1,27 @@ +package com.baeldung.test; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +import com.baeldung.properties.basic.ExtendedPropertiesWithJavaIntegrationTest; +import com.baeldung.properties.basic.PropertiesWithMultipleXmlsIntegrationTest; +import com.baeldung.properties.basic.PropertiesWithXmlIntegrationTest; +import com.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest; +import com.baeldung.properties.external.ExternalPropertiesWithMultipleXmlsIntegrationTest; +import com.baeldung.properties.external.ExternalPropertiesWithXmlManualTest; +import com.baeldung.properties.multiple.MultiplePropertiesXmlConfigIntegrationTest; +import com.baeldung.properties.multiple.MultiplePlaceholdersXmlConfigIntegrationTest; + +@RunWith(Suite.class) +@SuiteClasses({ //@formatter:off + PropertiesWithXmlIntegrationTest.class, + ExternalPropertiesWithJavaIntegrationTest.class, + ExternalPropertiesWithMultipleXmlsIntegrationTest.class, + ExternalPropertiesWithXmlManualTest.class, + ExtendedPropertiesWithJavaIntegrationTest.class, MultiplePropertiesXmlConfigIntegrationTest.class, + PropertiesWithMultipleXmlsIntegrationTest.class, MultiplePlaceholdersXmlConfigIntegrationTest.class +})// @formatter:on +public final class IntegrationTestSuite { + // +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java similarity index 100% rename from spring-boot-properties/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java rename to spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties b/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties new file mode 100644 index 0000000000..d4d1df7abc --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties @@ -0,0 +1,8 @@ +management.endpoints.web.exposure.include=refresh +spring.properties.refreshDelay=1000 +spring.config.location=file:extra.properties +spring.main.allow-bean-definition-overriding=true + +database.url=jdbc:postgresql:/localhost:5432/instance +database.username=foo +database.password=bar \ No newline at end of file diff --git a/spring-boot-properties/src/test/resources/configprops-test.properties b/spring-boot-modules/spring-boot-properties/src/test/resources/configprops-test.properties similarity index 96% rename from spring-boot-properties/src/test/resources/configprops-test.properties rename to spring-boot-modules/spring-boot-properties/src/test/resources/configprops-test.properties index 5eed93a22b..3fc1195b98 100644 --- a/spring-boot-properties/src/test/resources/configprops-test.properties +++ b/spring-boot-modules/spring-boot-properties/src/test/resources/configprops-test.properties @@ -24,3 +24,5 @@ item.size=21 #Additional properties additional.unit=km additional.max=100 + +key.something=val \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/test/resources/configuration-processor.properties b/spring-boot-modules/spring-boot-properties/src/test/resources/configuration-processor.properties new file mode 100644 index 0000000000..b68a4fbda3 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/resources/configuration-processor.properties @@ -0,0 +1,3 @@ +com.baeldung.url=www.abc.test.com +com.baeldung.jdbc.url= +com.baeldung.timeout-in-milli-seconds=2000 diff --git a/spring-boot-properties/src/test/resources/conversion.properties b/spring-boot-modules/spring-boot-properties/src/test/resources/conversion.properties similarity index 100% rename from spring-boot-properties/src/test/resources/conversion.properties rename to spring-boot-modules/spring-boot-properties/src/test/resources/conversion.properties diff --git a/spring-boot-modules/spring-boot-properties/src/test/resources/database-test.properties b/spring-boot-modules/spring-boot-properties/src/test/resources/database-test.properties new file mode 100644 index 0000000000..384d0850ab --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/resources/database-test.properties @@ -0,0 +1,3 @@ +jdbc.url=jdbc:postgresql:/localhost:5432 +database.username=foo +database.password=bar diff --git a/spring-boot-modules/spring-boot-properties/src/test/resources/foo.properties b/spring-boot-modules/spring-boot-properties/src/test/resources/foo.properties new file mode 100644 index 0000000000..b5ae2aedd4 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/resources/foo.properties @@ -0,0 +1,2 @@ +foo=bar +key.something=val \ No newline at end of file diff --git a/spring-boot-property-exp/README.md b/spring-boot-modules/spring-boot-property-exp/README.md similarity index 100% rename from spring-boot-property-exp/README.md rename to spring-boot-modules/spring-boot-property-exp/README.md diff --git a/spring-boot-modules/spring-boot-property-exp/pom.xml b/spring-boot-modules/spring-boot-property-exp/pom.xml new file mode 100644 index 0000000000..2da25fca31 --- /dev/null +++ b/spring-boot-modules/spring-boot-property-exp/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + spring-boot-property-exp + spring-boot-property-exp + 0.0.1-SNAPSHOT + pom + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + + + + property-exp-default-config + property-exp-custom-config + + + diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/pom.xml b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/pom.xml new file mode 100644 index 0000000000..e38a2742d5 --- /dev/null +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + property-exp-custom-config + 0.0.1-SNAPSHOT + property-exp-custom-config + jar + + + com.baeldung.spring-boot-modules + spring-boot-property-exp + 0.0.1-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + ${basedir}/src/main/resources + true + + **/application*.yml + **/application*.yaml + **/application*.properties + + + + ${basedir}/src/main/resources + true + + **/application*.yml + **/application*.yaml + **/application*.properties + + + + + + org.apache.maven.plugins + maven-resources-plugin + ${apache-maven.version} + + + @ + + true + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp + + + + + + + 2.2.6.RELEASE + Custom Property Value + 2.7 + 1.6.0 + + + diff --git a/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java similarity index 100% rename from spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java rename to spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java diff --git a/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java similarity index 100% rename from spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java rename to spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java diff --git a/spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties similarity index 100% rename from spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties diff --git a/spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt similarity index 100% rename from spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt rename to spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt diff --git a/spring-mvc-simple/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/main/resources/logback.xml similarity index 100% rename from spring-mvc-simple/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/main/resources/logback.xml diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..2e1a17199d --- /dev/null +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-property-exp/property-exp-default-config/build.gradle b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/build.gradle similarity index 100% rename from spring-boot-property-exp/property-exp-default-config/build.gradle rename to spring-boot-modules/spring-boot-property-exp/property-exp-default-config/build.gradle diff --git a/spring-boot-property-exp/property-exp-default-config/gradle.properties b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/gradle.properties similarity index 100% rename from spring-boot-property-exp/property-exp-default-config/gradle.properties rename to spring-boot-modules/spring-boot-property-exp/property-exp-default-config/gradle.properties diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml new file mode 100644 index 0000000000..79e194a3b5 --- /dev/null +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + property-exp-default-config + 0.0.1-SNAPSHOT + property-exp-default-config + jar + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + + + + Custom Property Value + + + diff --git a/spring-boot-property-exp/property-exp-default-config/settings.gradle b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/settings.gradle similarity index 100% rename from spring-boot-property-exp/property-exp-default-config/settings.gradle rename to spring-boot-modules/spring-boot-property-exp/property-exp-default-config/settings.gradle diff --git a/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java similarity index 100% rename from spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java rename to spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java diff --git a/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java similarity index 100% rename from spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java rename to spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java diff --git a/spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties similarity index 100% rename from spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties diff --git a/spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt similarity index 100% rename from spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt rename to spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/main/resources/logback.xml similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/main/resources/logback.xml diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..2e1a17199d --- /dev/null +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-modules/spring-boot-runtime/README.md b/spring-boot-modules/spring-boot-runtime/README.md new file mode 100644 index 0000000000..62727ecc76 --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime/README.md @@ -0,0 +1,13 @@ +## Spring Boot Runtime + +This module contains articles about administering a Spring Boot runtime + +### Relevant Articles: + - [Shutdown a Spring Boot Application](https://www.baeldung.com/spring-boot-shutdown) + - [Programmatically Restarting a Spring Boot Application](https://www.baeldung.com/java-restart-spring-boot-app) + - [Logging HTTP Requests with Spring Boot Actuator HTTP Tracing](https://www.baeldung.com/spring-boot-actuator-http) + - [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) + - [Spring Boot Embedded Tomcat Logs](https://www.baeldung.com/spring-boot-embedded-tomcat-logs) + - [Project Configuration with Spring](https://www.baeldung.com/project-configuration-with-spring) + - [CORS with Spring](https://www.baeldung.com/spring-cors) + - [Spring – Log Incoming Requests](https://www.baeldung.com/spring-http-logging) \ No newline at end of file diff --git a/spring-boot-runtime/disabling-console-jul/.gitignore b/spring-boot-modules/spring-boot-runtime/disabling-console-jul/.gitignore similarity index 100% rename from spring-boot-runtime/disabling-console-jul/.gitignore rename to spring-boot-modules/spring-boot-runtime/disabling-console-jul/.gitignore diff --git a/spring-boot-modules/spring-boot-runtime/disabling-console-jul/pom.xml b/spring-boot-modules/spring-boot-runtime/disabling-console-jul/pom.xml new file mode 100644 index 0000000000..2f1c9c2add --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime/disabling-console-jul/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + disabling-console-jul + disabling-console-jul + + + + com.baeldung + spring-boot-runtime + 0.0.1-SNAPSHOT + + + + + 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 + + + + + \ No newline at end of file diff --git a/spring-boot-runtime/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java b/spring-boot-modules/spring-boot-runtime/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java similarity index 100% rename from spring-boot-runtime/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java rename to spring-boot-modules/spring-boot-runtime/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java diff --git a/spring-boot-runtime/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java b/spring-boot-modules/spring-boot-runtime/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java similarity index 100% rename from spring-boot-runtime/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java rename to spring-boot-modules/spring-boot-runtime/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java diff --git a/spring-boot-runtime/disabling-console-jul/src/main/resources/application.properties b/spring-boot-modules/spring-boot-runtime/disabling-console-jul/src/main/resources/application.properties similarity index 100% rename from spring-boot-runtime/disabling-console-jul/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-runtime/disabling-console-jul/src/main/resources/application.properties diff --git a/spring-boot-runtime/disabling-console-jul/src/main/resources/logging.properties b/spring-boot-modules/spring-boot-runtime/disabling-console-jul/src/main/resources/logging.properties similarity index 100% rename from spring-boot-runtime/disabling-console-jul/src/main/resources/logging.properties rename to spring-boot-modules/spring-boot-runtime/disabling-console-jul/src/main/resources/logging.properties diff --git a/spring-boot-runtime/disabling-console-log4j2/.gitignore b/spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/.gitignore similarity index 100% rename from spring-boot-runtime/disabling-console-log4j2/.gitignore rename to spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/.gitignore diff --git a/spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/pom.xml b/spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/pom.xml new file mode 100644 index 0000000000..35f54999ec --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + disabling-console-log4j2 + disabling-console-log4j2 + + + + com.baeldung + spring-boot-runtime + 0.0.1-SNAPSHOT + + + + + 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 + + + + + \ No newline at end of file diff --git a/spring-boot-runtime/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java b/spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java similarity index 100% rename from spring-boot-runtime/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java rename to spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java diff --git a/spring-boot-runtime/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java b/spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java similarity index 100% rename from spring-boot-runtime/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java rename to spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java diff --git a/spring-boot-runtime/disabling-console-log4j2/src/main/resources/log4j2.xml b/spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/src/main/resources/log4j2.xml similarity index 100% rename from spring-boot-runtime/disabling-console-log4j2/src/main/resources/log4j2.xml rename to spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/src/main/resources/log4j2.xml diff --git a/spring-boot-runtime/disabling-console-logback/.gitignore b/spring-boot-modules/spring-boot-runtime/disabling-console-logback/.gitignore similarity index 100% rename from spring-boot-runtime/disabling-console-logback/.gitignore rename to spring-boot-modules/spring-boot-runtime/disabling-console-logback/.gitignore diff --git a/spring-boot-modules/spring-boot-runtime/disabling-console-logback/pom.xml b/spring-boot-modules/spring-boot-runtime/disabling-console-logback/pom.xml new file mode 100644 index 0000000000..c96dfb6a2f --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime/disabling-console-logback/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + disabling-console-logback + disabling-console-logback + + + com.baeldung + spring-boot-runtime + 0.0.1-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + + \ No newline at end of file diff --git a/spring-boot-runtime/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java b/spring-boot-modules/spring-boot-runtime/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java similarity index 100% rename from spring-boot-runtime/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java rename to spring-boot-modules/spring-boot-runtime/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java diff --git a/spring-boot-runtime/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java b/spring-boot-modules/spring-boot-runtime/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java similarity index 100% rename from spring-boot-runtime/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java rename to spring-boot-modules/spring-boot-runtime/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java diff --git a/spring-boot-runtime/disabling-console-logback/src/main/resources/application.properties b/spring-boot-modules/spring-boot-runtime/disabling-console-logback/src/main/resources/application.properties similarity index 100% rename from spring-boot-runtime/disabling-console-logback/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-runtime/disabling-console-logback/src/main/resources/application.properties diff --git a/spring-boot-runtime/disabling-console-logback/src/main/resources/logback-spring.xml b/spring-boot-modules/spring-boot-runtime/disabling-console-logback/src/main/resources/logback-spring.xml similarity index 100% rename from spring-boot-runtime/disabling-console-logback/src/main/resources/logback-spring.xml rename to spring-boot-modules/spring-boot-runtime/disabling-console-logback/src/main/resources/logback-spring.xml diff --git a/spring-boot-runtime/docker/Dockerfile b/spring-boot-modules/spring-boot-runtime/docker/Dockerfile similarity index 100% rename from spring-boot-runtime/docker/Dockerfile rename to spring-boot-modules/spring-boot-runtime/docker/Dockerfile diff --git a/spring-boot-runtime/docker/logback.xml b/spring-boot-modules/spring-boot-runtime/docker/logback.xml similarity index 100% rename from spring-boot-runtime/docker/logback.xml rename to spring-boot-modules/spring-boot-runtime/docker/logback.xml diff --git a/spring-boot-runtime/docker/run.sh b/spring-boot-modules/spring-boot-runtime/docker/run.sh similarity index 100% rename from spring-boot-runtime/docker/run.sh rename to spring-boot-modules/spring-boot-runtime/docker/run.sh diff --git a/spring-boot-modules/spring-boot-runtime/pom.xml b/spring-boot-modules/spring-boot-runtime/pom.xml new file mode 100644 index 0000000000..df45537940 --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime/pom.xml @@ -0,0 +1,175 @@ + + + 4.0.0 + spring-boot-runtime + spring-boot-runtime + pom + Demo project for Spring Boot + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + disabling-console-jul + disabling-console-log4j2 + disabling-console-logback + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + provided + + + + org.springframework.boot + spring-boot-starter-test + test + + + + commons-io + commons-io + 2.6 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-mail + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-security + + + de.codecentric + spring-boot-admin-starter-client + ${spring-boot-admin-starter-client.version} + + + org.springframework.security + spring-security-test + + + + com.h2database + h2 + runtime + + + + javax.persistence + javax.persistence-api + ${jpa.version} + + + + com.google.guava + guava + ${guava.version} + + + + org.subethamail + subethasmtp + ${subethasmtp.version} + test + + + + org.springframework.cloud + spring-cloud-context + ${springcloud.version} + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + + + + ${project.artifactId} + + + src/main/resources + true + + **/conf.properties + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + 2.2 + 18.0 + 3.1.7 + 2.0.2.RELEASE + 4.5.8 + 2.1.6 + + + diff --git a/spring-boot-runtime/src/main/java/com/baeldung/cors/Account.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/Account.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/cors/Account.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/Account.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/cors/AccountController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/AccountController.java similarity index 91% rename from spring-boot-runtime/src/main/java/com/baeldung/cors/AccountController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/AccountController.java index c387eb2121..2a4156a392 100644 --- a/spring-boot-runtime/src/main/java/com/baeldung/cors/AccountController.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/AccountController.java @@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.RestController; public class AccountController { @CrossOrigin("http://example.com") - @RequestMapping("/{id}") + @RequestMapping(method = RequestMethod.GET, path = "/{id}") public Account retrieve(@PathVariable Long id) { return new Account(id); } diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/config/WebConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/config/WebConfig.java new file mode 100644 index 0000000000..c3179621b7 --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/config/WebConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.cors.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@EnableWebMvc +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**"); + } +} diff --git a/spring-boot-runtime/src/main/java/com/baeldung/restart/Application.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/Application.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/restart/Application.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/Application.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/restart/RestartController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/RestartController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/restart/RestartController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/RestartController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/restart/RestartService.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/RestartService.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/restart/RestartService.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/RestartService.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/MainApplication.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/MainApplication.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/MainApplication.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/MainApplication.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/WebConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/WebConfig.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/WebConfig.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/config/WebConfig.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Company.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Company.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Company.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Company.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Item.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Item.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Item.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Item.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Views.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Views.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Views.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/dto/Views.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/shutdown/Application.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/Application.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/shutdown/Application.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/Application.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/shutdown/ShutdownConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/ShutdownConfig.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/shutdown/ShutdownConfig.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/ShutdownConfig.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/LoggingApplication.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/LoggingApplication.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/LoggingApplication.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/LoggingApplication.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/LoggingController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/LoggingController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/LoggingController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/LoggingController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/App.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/App.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/App.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/App.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/EchoController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/EchoController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/EchoController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/EchoController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java new file mode 100644 index 0000000000..40f5341e29 --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java @@ -0,0 +1,22 @@ +package com.baeldung.web.log.app; + +import javax.servlet.ServletRegistration; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; + +import com.baeldung.web.log.config.CustomeRequestLoggingFilter; + +@EnableAutoConfiguration +@ComponentScan("com.baeldung.web.log") +@PropertySource("application-log.properties") +@SpringBootApplication +public class Application { + + public static void main(final String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomWebAppInitializer.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomWebAppInitializer.java new file mode 100644 index 0000000000..f51bb52990 --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomWebAppInitializer.java @@ -0,0 +1,25 @@ +package com.baeldung.web.log.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; +import org.springframework.web.WebApplicationInitializer; + +public class CustomWebAppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) throws ServletException { + + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.setConfigLocation("com.baeldung.web.log"); + container.addListener(new ContextLoaderListener(context)); + + ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(context)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/"); + + container.addFilter("customRequestLoggingFilter", CustomeRequestLoggingFilter.class).addMappingForServletNames(null, false, "dispatcher"); + } +} \ No newline at end of file diff --git a/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomeRequestLoggingFilter.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomeRequestLoggingFilter.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomeRequestLoggingFilter.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomeRequestLoggingFilter.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/web/log/data/RateCard.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/data/RateCard.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/web/log/data/RateCard.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/data/RateCard.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/web/log/data/TaxiRide.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/data/TaxiRide.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/web/log/data/TaxiRide.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/data/TaxiRide.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java diff --git a/spring-boot-runtime/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java similarity index 100% rename from spring-boot-runtime/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java diff --git a/spring-boot-runtime/src/main/resources/application-log.properties b/spring-boot-modules/spring-boot-runtime/src/main/resources/application-log.properties similarity index 100% rename from spring-boot-runtime/src/main/resources/application-log.properties rename to spring-boot-modules/spring-boot-runtime/src/main/resources/application-log.properties diff --git a/spring-boot-runtime/src/main/resources/application-logging.properties b/spring-boot-modules/spring-boot-runtime/src/main/resources/application-logging.properties similarity index 100% rename from spring-boot-runtime/src/main/resources/application-logging.properties rename to spring-boot-modules/spring-boot-runtime/src/main/resources/application-logging.properties diff --git a/spring-boot-runtime/src/main/resources/application-tomcat.properties b/spring-boot-modules/spring-boot-runtime/src/main/resources/application-tomcat.properties similarity index 100% rename from spring-boot-runtime/src/main/resources/application-tomcat.properties rename to spring-boot-modules/spring-boot-runtime/src/main/resources/application-tomcat.properties diff --git a/spring-boot-runtime/src/main/resources/application.properties b/spring-boot-modules/spring-boot-runtime/src/main/resources/application.properties similarity index 100% rename from spring-boot-runtime/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-runtime/src/main/resources/application.properties diff --git a/spring-security-modules/spring-security-openid/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-runtime/src/main/resources/logback.xml similarity index 100% rename from spring-security-modules/spring-security-openid/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-runtime/src/main/resources/logback.xml diff --git a/spring-boot-runtime/src/main/webapp/WEB-INF/api-servlet.xml b/spring-boot-modules/spring-boot-runtime/src/main/webapp/WEB-INF/api-servlet.xml similarity index 100% rename from spring-boot-runtime/src/main/webapp/WEB-INF/api-servlet.xml rename to spring-boot-modules/spring-boot-runtime/src/main/webapp/WEB-INF/api-servlet.xml diff --git a/spring-boot-runtime/src/main/webapp/WEB-INF/company.html b/spring-boot-modules/spring-boot-runtime/src/main/webapp/WEB-INF/company.html similarity index 100% rename from spring-boot-runtime/src/main/webapp/WEB-INF/company.html rename to spring-boot-modules/spring-boot-runtime/src/main/webapp/WEB-INF/company.html diff --git a/spring-boot-runtime/src/main/webapp/WEB-INF/spring-views.xml b/spring-boot-modules/spring-boot-runtime/src/main/webapp/WEB-INF/spring-views.xml similarity index 100% rename from spring-boot-runtime/src/main/webapp/WEB-INF/spring-views.xml rename to spring-boot-modules/spring-boot-runtime/src/main/webapp/WEB-INF/spring-views.xml diff --git a/spring-boot-runtime/src/main/webapp/WEB-INF/web.xml b/spring-boot-modules/spring-boot-runtime/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-boot-runtime/src/main/webapp/WEB-INF/web.xml rename to spring-boot-modules/spring-boot-runtime/src/main/webapp/WEB-INF/web.xml diff --git a/spring-boot-runtime/src/test/java/com/baeldung/restart/RestartApplicationManualTest.java b/spring-boot-modules/spring-boot-runtime/src/test/java/com/baeldung/restart/RestartApplicationManualTest.java similarity index 100% rename from spring-boot-runtime/src/test/java/com/baeldung/restart/RestartApplicationManualTest.java rename to spring-boot-modules/spring-boot-runtime/src/test/java/com/baeldung/restart/RestartApplicationManualTest.java diff --git a/spring-boot-runtime/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-runtime/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java similarity index 100% rename from spring-boot-runtime/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-runtime/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java diff --git a/spring-boot-runtime/src/test/java/com/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java b/spring-boot-modules/spring-boot-runtime/src/test/java/com/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java similarity index 100% rename from spring-boot-runtime/src/test/java/com/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-runtime/src/test/java/com/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java diff --git a/spring-boot-runtime/src/test/java/com/baeldung/web/controller/TaxiFareControllerIntegrationTest.java b/spring-boot-modules/spring-boot-runtime/src/test/java/com/baeldung/web/controller/TaxiFareControllerIntegrationTest.java similarity index 100% rename from spring-boot-runtime/src/test/java/com/baeldung/web/controller/TaxiFareControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-runtime/src/test/java/com/baeldung/web/controller/TaxiFareControllerIntegrationTest.java diff --git a/spring-boot-runtime/src/test/resources/application-integrationtest.properties b/spring-boot-modules/spring-boot-runtime/src/test/resources/application-integrationtest.properties similarity index 100% rename from spring-boot-runtime/src/test/resources/application-integrationtest.properties rename to spring-boot-modules/spring-boot-runtime/src/test/resources/application-integrationtest.properties diff --git a/spring-boot-runtime/src/test/resources/application.properties b/spring-boot-modules/spring-boot-runtime/src/test/resources/application.properties similarity index 100% rename from spring-boot-runtime/src/test/resources/application.properties rename to spring-boot-modules/spring-boot-runtime/src/test/resources/application.properties diff --git a/spring-boot-modules/spring-boot-security/README.md b/spring-boot-modules/spring-boot-security/README.md new file mode 100644 index 0000000000..7229ba0f4a --- /dev/null +++ b/spring-boot-modules/spring-boot-security/README.md @@ -0,0 +1,20 @@ +## Spring Boot Security + +This module contains articles about Spring Boot Security + +### Relevant Articles: + +- [Spring Boot Security Auto-Configuration](https://www.baeldung.com/spring-boot-security-autoconfiguration) +- [Spring Security for Spring Boot Integration Tests](https://www.baeldung.com/spring-security-integration-tests) +- [Introduction to Spring Security Taglibs](https://www.baeldung.com/spring-security-taglibs) +- [Guide to @CurrentSecurityContext in Spring Security](https://www.baeldung.com/spring-currentsecuritycontext) + +### Spring Boot Security Auto-Configuration + +- mvn clean install +- uncomment actuator dependency simultaneously with the line from basic auth main class +- uncomment security properties for easy testing. If not random will be generated. + +### CURL commands + +- curl -X POST -u baeldung-admin:baeldung -d grant_type=client_credentials -d username=baeldung-admin -d password=baeldung http://localhost:8080/oauth/token diff --git a/spring-boot-modules/spring-boot-security/pom.xml b/spring-boot-modules/spring-boot-security/pom.xml new file mode 100644 index 0000000000..98eceaff96 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/pom.xml @@ -0,0 +1,89 @@ + + + 4.0.0 + spring-boot-security + spring-boot-security + Spring Boot Security Auto-Configuration + jar + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.security.oauth + spring-security-oauth2 + 2.4.0.RELEASE + + + commons-io + commons-io + 2.6 + + + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure + 2.2.2.RELEASE + + + 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 + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + org.springframework.boot + spring-boot-autoconfigure + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + com.baeldung.springbootsecurity.basic_auth.SpringBootSecurityApplication + + + diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/SpringBootSecurityApplication.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/SpringBootSecurityApplication.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/SpringBootSecurityApplication.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/SpringBootSecurityApplication.java diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfiguration.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfiguration.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfiguration.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfiguration.java diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2resource/SpringBootOAuth2ResourceApplication.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2resource/SpringBootOAuth2ResourceApplication.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2resource/SpringBootOAuth2ResourceApplication.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2resource/SpringBootOAuth2ResourceApplication.java diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/SpringBootAuthorizationServerApplication.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/SpringBootAuthorizationServerApplication.java new file mode 100644 index 0000000000..04f046ff78 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/SpringBootAuthorizationServerApplication.java @@ -0,0 +1,47 @@ +package com.baeldung.springbootsecurity.oauth2server; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.annotation.CurrentSecurityContext; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.security.Principal; + +@EnableResourceServer +@EnableAuthorizationServer +@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurity.oauth2server") +public class SpringBootAuthorizationServerApplication { + + private static final Logger logger = LoggerFactory.getLogger(SpringBootAuthorizationServerApplication.class); + + public static void main(String[] args) { + SpringApplication.run(SpringBootAuthorizationServerApplication.class, args); + } + + @RestController + class UserController { + + @GetMapping("/user") + public Principal user(Principal user) { + return user; + } + + @GetMapping("/authentication") + public Object getAuthentication(@CurrentSecurityContext(expression = "authentication") Authentication authentication) { + logger.info("authentication -> {}", authentication); + return authentication.getDetails(); + } + + @GetMapping("/principal") + public String getPrincipal(@CurrentSecurityContext(expression = "authentication.principal") Principal principal) { + logger.info("principal -> {}", principal); + return principal.getName(); + } + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthenticationMananagerConfig.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthenticationMananagerConfig.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthenticationMananagerConfig.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthenticationMananagerConfig.java diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/WebSecurityConfiguration.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/WebSecurityConfiguration.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/WebSecurityConfiguration.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/WebSecurityConfiguration.java diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2sso/SpringBootOAuth2SsoApplication.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2sso/SpringBootOAuth2SsoApplication.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2sso/SpringBootOAuth2SsoApplication.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2sso/SpringBootOAuth2SsoApplication.java diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java similarity index 100% rename from spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java rename to spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java diff --git a/spring-boot-security/src/main/resources/application-authz.properties b/spring-boot-modules/spring-boot-security/src/main/resources/application-authz.properties similarity index 100% rename from spring-boot-security/src/main/resources/application-authz.properties rename to spring-boot-modules/spring-boot-security/src/main/resources/application-authz.properties diff --git a/spring-boot-security/src/main/resources/application-resource.properties b/spring-boot-modules/spring-boot-security/src/main/resources/application-resource.properties similarity index 100% rename from spring-boot-security/src/main/resources/application-resource.properties rename to spring-boot-modules/spring-boot-security/src/main/resources/application-resource.properties diff --git a/spring-boot-security/src/main/resources/application-sso.properties b/spring-boot-modules/spring-boot-security/src/main/resources/application-sso.properties similarity index 100% rename from spring-boot-security/src/main/resources/application-sso.properties rename to spring-boot-modules/spring-boot-security/src/main/resources/application-sso.properties diff --git a/spring-boot-security/src/main/resources/application-taglibs.properties b/spring-boot-modules/spring-boot-security/src/main/resources/application-taglibs.properties similarity index 100% rename from spring-boot-security/src/main/resources/application-taglibs.properties rename to spring-boot-modules/spring-boot-security/src/main/resources/application-taglibs.properties diff --git a/spring-boot-security/src/main/resources/application.properties b/spring-boot-modules/spring-boot-security/src/main/resources/application.properties similarity index 100% rename from spring-boot-security/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-security/src/main/resources/application.properties diff --git a/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-modules/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/resources/static/index.html b/spring-boot-modules/spring-boot-security/src/main/resources/static/index.html similarity index 100% rename from spring-boot-security/src/main/resources/static/index.html rename to spring-boot-modules/spring-boot-security/src/main/resources/static/index.html diff --git a/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-modules/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp similarity index 100% rename from spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp rename to spring-boot-modules/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java similarity index 100% rename from spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java rename to spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java similarity index 100% rename from spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java rename to spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java similarity index 100% rename from spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java rename to spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java similarity index 100% rename from spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java rename to spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfigurationIntegrationTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfigurationIntegrationTest.java similarity index 100% rename from spring-boot-security/src/test/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfigurationIntegrationTest.java rename to spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfigurationIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/CustomConfigAuthorizationServerIntegrationTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/CustomConfigAuthorizationServerIntegrationTest.java new file mode 100644 index 0000000000..104e115b18 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/CustomConfigAuthorizationServerIntegrationTest.java @@ -0,0 +1,89 @@ +package com.baeldung.springbootsecurity.oauth2server; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.security.oauth2.client.OAuth2RestTemplate; +import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException; +import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import java.net.URL; +import java.util.regex.Pattern; + +import static java.util.Collections.singletonList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootAuthorizationServerApplication.class) +@ActiveProfiles("authz") +public class CustomConfigAuthorizationServerIntegrationTest extends OAuth2IntegrationTestSupport { + + @LocalServerPort + private int port; + + @Before + public void setUp() throws Exception { + base = new URL("http://localhost:" + port); + } + + @Test + public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() { + ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read")); + OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); + + OAuth2AccessToken accessToken = restTemplate.getAccessToken(); + + assertNotNull(accessToken); + } + + @Test + public void givenOAuth2Context_whenAccessingAuthentication_ThenRespondTokenDetails() { + ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read")); + OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); + + String authentication = executeGetRequest(restTemplate, "/authentication"); + + Pattern pattern = Pattern.compile("\\{\"remoteAddress\":\".*" + + "\",\"sessionId\":null,\"tokenValue\":\".*" + + "\",\"tokenType\":\"Bearer\",\"decodedDetails\":null}"); + assertTrue("authentication", pattern.matcher(authentication).matches()); + } + + @Test + public void givenOAuth2Context_whenAccessingPrincipal_ThenRespondBaeldung() { + ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read")); + OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); + + String principal = executeGetRequest(restTemplate, "/principal"); + + assertEquals("baeldung", principal); + } + + @Test(expected = OAuth2AccessDeniedException.class) + public void givenOAuth2Context_whenAccessTokenIsRequestedWithInvalidException_ThenExceptionIsThrown() { + ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("write")); + OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); + + restTemplate.getAccessToken(); + } + + @Test + public void givenOAuth2Context_whenAccessTokenIsRequestedByClientWithWriteScope_ThenAccessTokenIsNotNull() { + ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung-admin", singletonList("write")); + OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); + + OAuth2AccessToken accessToken = restTemplate.getAccessToken(); + + assertNotNull(accessToken); + } + +} + diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/DefaultConfigAuthorizationServerIntegrationTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/DefaultConfigAuthorizationServerIntegrationTest.java similarity index 100% rename from spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/DefaultConfigAuthorizationServerIntegrationTest.java rename to spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/DefaultConfigAuthorizationServerIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/OAuth2IntegrationTestSupport.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/OAuth2IntegrationTestSupport.java new file mode 100644 index 0000000000..a005965998 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/OAuth2IntegrationTestSupport.java @@ -0,0 +1,53 @@ +package com.baeldung.springbootsecurity.oauth2server; + +import org.apache.commons.io.IOUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; +import org.springframework.security.oauth2.client.OAuth2RestTemplate; +import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; +import org.springframework.web.client.RequestCallback; +import org.springframework.web.client.ResponseExtractor; + +import java.net.URL; +import java.nio.charset.Charset; +import java.util.List; + +import static java.lang.String.format; +import static java.util.Collections.singletonList; +import static org.springframework.http.HttpMethod.GET; + +public class OAuth2IntegrationTestSupport { + + public static final ResponseExtractor EXTRACT_BODY_AS_STRING = clientHttpResponse -> + IOUtils.toString(clientHttpResponse.getBody(), Charset.defaultCharset()); + private static final RequestCallback DO_NOTHING_CALLBACK = request -> { + }; + + @Value("${local.server.port}") + protected int port; + + protected URL base; + + protected ClientCredentialsResourceDetails getClientCredentialsResourceDetails(final String clientId, final List scopes) { + ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); + resourceDetails.setAccessTokenUri(format("http://localhost:%d/oauth/token", port)); + resourceDetails.setClientId(clientId); + resourceDetails.setClientSecret("baeldung"); + resourceDetails.setScope(scopes); + resourceDetails.setGrantType("client_credentials"); + return resourceDetails; + } + + protected OAuth2RestTemplate getOAuth2RestTemplate(final ClientCredentialsResourceDetails resourceDetails) { + DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext(); + OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails, clientContext); + restTemplate.setMessageConverters(singletonList(new MappingJackson2HttpMessageConverter())); + return restTemplate; + } + + protected String executeGetRequest(OAuth2RestTemplate restTemplate, String path) { + return restTemplate.execute(base.toString() + path, GET, DO_NOTHING_CALLBACK, EXTRACT_BODY_AS_STRING); + } + +} diff --git a/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java similarity index 100% rename from spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java rename to spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java diff --git a/spring-boot-springdoc/README.md b/spring-boot-modules/spring-boot-springdoc/README.md similarity index 100% rename from spring-boot-springdoc/README.md rename to spring-boot-modules/spring-boot-springdoc/README.md diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml new file mode 100644 index 0000000000..375cf06c2c --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/pom.xml @@ -0,0 +1,121 @@ + + + 4.0.0 + spring-boot-springdoc + 0.0.1-SNAPSHOT + spring-boot-springdoc + jar + Project for Springdoc integration + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + + + org.springdoc + springdoc-openapi-ui + ${springdoc.version} + + + org.springdoc + springdoc-openapi-data-rest + ${springdoc.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + 1.8 + 5.2.10.Final + 1.2.32 + + + + + integration + + + + org.springframework.boot + spring-boot-maven-plugin + 2.2.2.RELEASE + + + pre-integration-test + + start + + + + post-integration-test + + stop + + + + + + org.springdoc + springdoc-openapi-maven-plugin + 0.2 + + + integration-test + + generate + + + + + http://localhost:8080/api-docs + openapi.json + ${project.build.directory} + + + + + + + + \ No newline at end of file diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/SpringdocApplication.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/SpringdocApplication.java similarity index 100% rename from spring-boot-springdoc/src/main/java/com/baeldung/springdoc/SpringdocApplication.java rename to spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/SpringdocApplication.java diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java new file mode 100644 index 0000000000..05f8c5a946 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java @@ -0,0 +1,80 @@ +package com.baeldung.springdoc.controller; + +import java.util.Collection; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +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.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.springdoc.exception.BookNotFoundException; +import com.baeldung.springdoc.model.Book; +import com.baeldung.springdoc.repository.BookRepository; + +@RestController +@RequestMapping("/api/book") +public class BookController { + + @Autowired + private BookRepository repository; + + @GetMapping("/{id}") + public Book findById(@PathVariable long id) { + return repository.findById(id) + .orElseThrow(() -> new BookNotFoundException()); + } + + @GetMapping("/") + public Collection findBooks() { + return repository.getBooks(); + } + + @GetMapping("/filter") + public Page filterBooks(Pageable pageable) { + return repository.getBooks(pageable); + } + + @PutMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public Book updateBook(@PathVariable("id") final String id, @RequestBody final Book book) { + return book; + } + + @PatchMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public Book patchBook(@PathVariable("id") final String id, @RequestBody final Book book) { + return book; + } + + @PostMapping("/") + @ResponseStatus(HttpStatus.CREATED) + public Book postBook(@NotNull @Valid @RequestBody final Book book) { + return book; + } + + @RequestMapping(method = RequestMethod.HEAD, value = "/") + @ResponseStatus(HttpStatus.OK) + public Book headBook() { + return new Book(); + } + + @DeleteMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public long deleteBook(@PathVariable final long id) { + return id; + } +} diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/BookNotFoundException.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/BookNotFoundException.java similarity index 100% rename from spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/BookNotFoundException.java rename to spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/BookNotFoundException.java diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/GlobalControllerExceptionHandler.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/GlobalControllerExceptionHandler.java similarity index 100% rename from spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/GlobalControllerExceptionHandler.java rename to spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/GlobalControllerExceptionHandler.java diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java similarity index 100% rename from spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java rename to spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/repository/BookRepository.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/repository/BookRepository.java new file mode 100644 index 0000000000..0e3636d084 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/repository/BookRepository.java @@ -0,0 +1,36 @@ +package com.baeldung.springdoc.repository; + +import com.baeldung.springdoc.model.Book; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Repository; + +import java.util.*; + +import static java.util.stream.Collectors.toList; + +@Repository +public class BookRepository { + + private Map books = new HashMap<>(); + + public Optional findById(long id) { + return Optional.ofNullable(books.get(id)); + } + + public void add(Book book) { + books.put(book.getId(), book); + } + + public Collection getBooks() { + return books.values(); + } + + public Page getBooks(Pageable pageable) { + int toSkip = pageable.getPageSize() * pageable.getPageNumber(); + List result = books.values().stream().skip(toSkip).limit(pageable.getPageSize()).collect(toList()); + + return new PageImpl<>(result, pageable, books.size()); + } +} diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties new file mode 100644 index 0000000000..45378e610b --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties @@ -0,0 +1,8 @@ +# custom path for swagger-ui +springdoc.swagger-ui.path=/swagger-ui-custom.html + +# custom path for api docs +springdoc.api-docs.path=/api-docs + +# H2 Related Configurations +spring.datasource.url=jdbc:h2:mem:springdoc \ No newline at end of file diff --git a/spring-boot-springdoc/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-springdoc/src/main/resources/logback.xml similarity index 100% rename from spring-boot-springdoc/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-springdoc/src/main/resources/logback.xml diff --git a/spring-boot-springdoc/src/test/java/com/baeldung/springdoc/SpringContextTest.java b/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/springdoc/SpringContextTest.java similarity index 100% rename from spring-boot-springdoc/src/test/java/com/baeldung/springdoc/SpringContextTest.java rename to spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/springdoc/SpringContextTest.java diff --git a/spring-boot-testing/.gitignore b/spring-boot-modules/spring-boot-testing/.gitignore similarity index 100% rename from spring-boot-testing/.gitignore rename to spring-boot-modules/spring-boot-testing/.gitignore diff --git a/spring-boot-testing/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot-testing/.mvn/wrapper/maven-wrapper.properties similarity index 100% rename from spring-boot-testing/.mvn/wrapper/maven-wrapper.properties rename to spring-boot-modules/spring-boot-testing/.mvn/wrapper/maven-wrapper.properties diff --git a/spring-boot-modules/spring-boot-testing/README.md b/spring-boot-modules/spring-boot-testing/README.md new file mode 100644 index 0000000000..192f5cee99 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/README.md @@ -0,0 +1,16 @@ +## Spring Boot Testing + +This module contains articles about Spring Boot testing + +### The Course + +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Testing with Spring and Spock](https://www.baeldung.com/spring-spock-testing) +- [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test) +- [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level) +- [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis) +- [Testing Spring Boot @ConfigurationProperties](https://www.baeldung.com/spring-boot-testing-configurationproperties) +- [Prevent ApplicationRunner or CommandLineRunner Beans From Executing During Junit Testing](https://www.baeldung.com/spring-junit-prevent-runner-beans-testing-execution) diff --git a/spring-boot-testing/mvnw b/spring-boot-modules/spring-boot-testing/mvnw similarity index 100% rename from spring-boot-testing/mvnw rename to spring-boot-modules/spring-boot-testing/mvnw diff --git a/spring-boot-testing/mvnw.cmd b/spring-boot-modules/spring-boot-testing/mvnw.cmd similarity index 100% rename from spring-boot-testing/mvnw.cmd rename to spring-boot-modules/spring-boot-testing/mvnw.cmd diff --git a/spring-boot-modules/spring-boot-testing/pom.xml b/spring-boot-modules/spring-boot-testing/pom.xml new file mode 100644 index 0000000000..8353f9de61 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/pom.xml @@ -0,0 +1,137 @@ + + + 4.0.0 + spring-boot-testing + spring-boot-testing + war + This is simple boot application for demonstrating testing features. + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-test + test + + + + + it.ozimov + embedded-redis + ${redis.version} + test + + + + org.spockframework + spock-core + ${spock.version} + test + + + + org.spockframework + spock-spring + ${spock.version} + test + + + + io.rest-assured + rest-assured + test + + + + + + spring-boot-testing + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + pl.project13.maven + git-commit-id-plugin + ${git-commit-id-plugin.version} + + + get-the-git-infos + + revision + + initialize + + + validate-the-git-infos + + validateRevision + + package + + + + true + ${project.build.outputDirectory}/git.properties + + + + + org.codehaus.gmavenplus + gmavenplus-plugin + ${gmavenplus-plugin.version} + + + + compileTests + + + + + + + + + + com.baeldung.boot.Application + 2.2.4 + 1.2-groovy-2.4 + 1.6 + 0.7.2 + + + diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/Application.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/Application.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/boot/Application.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/Application.java diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/Credentials.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/Credentials.java new file mode 100644 index 0000000000..e51937cf57 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/Credentials.java @@ -0,0 +1,28 @@ +package com.baeldung.boot.configurationproperties; + +public class Credentials { + + private String username; + private String password; + + public Credentials(String username, String password) { + this.username = username; + this.password = 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-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/CustomCredentialsConverter.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/CustomCredentialsConverter.java new file mode 100644 index 0000000000..ef160c8c9a --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/CustomCredentialsConverter.java @@ -0,0 +1,16 @@ +package com.baeldung.boot.configurationproperties; + +import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationPropertiesBinding +public class CustomCredentialsConverter implements Converter { + + @Override + public Credentials convert(String source) { + String[] data = source.split(","); + return new Credentials(data[0], data[1]); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/MailServer.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/MailServer.java new file mode 100644 index 0000000000..e23b30759b --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/MailServer.java @@ -0,0 +1,59 @@ +package com.baeldung.boot.configurationproperties; + +import java.util.Map; + +import javax.validation.Valid; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +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 +@ConfigurationProperties(prefix = "validate") +@PropertySource("classpath:property-validation.properties") +@Validated +public class MailServer { + + @NotNull + @NotEmpty + private Map propertiesMap; + + @Valid + private MailConfig mailConfig = new MailConfig(); + + public static class MailConfig { + + @NotBlank + @Email + private String address; + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + } + + public Map getPropertiesMap() { + return propertiesMap; + } + + public void setPropertiesMap(Map propertiesMap) { + this.propertiesMap = propertiesMap; + } + + public MailConfig getMailConfig() { + return mailConfig; + } + + public void setMailConfig(MailConfig mailConfig) { + this.mailConfig = mailConfig; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/PropertyConversion.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/PropertyConversion.java new file mode 100644 index 0000000000..9b2ea39299 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/PropertyConversion.java @@ -0,0 +1,67 @@ +package com.baeldung.boot.configurationproperties; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.convert.DataSizeUnit; +import org.springframework.boot.convert.DurationUnit; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.unit.DataSize; +import org.springframework.util.unit.DataUnit; + +@Configuration +@ConfigurationProperties(prefix = "server") +public class PropertyConversion { + + private DataSize uploadSpeed; + + @DataSizeUnit(DataUnit.GIGABYTES) + private DataSize downloadSpeed; + + private Duration backupDay; + + @DurationUnit(ChronoUnit.HOURS) + private Duration backupHour; + + private Credentials credentials; + + public Duration getBackupDay() { + return backupDay; + } + + public void setBackupDay(Duration backupDay) { + this.backupDay = backupDay; + } + + public Duration getBackupHour() { + return backupHour; + } + + public void setBackupHour(Duration backupHour) { + this.backupHour = backupHour; + } + + public DataSize getUploadSpeed() { + return uploadSpeed; + } + + public void setUploadSpeed(DataSize uploadSpeed) { + this.uploadSpeed = uploadSpeed; + } + + public DataSize getDownloadSpeed() { + return downloadSpeed; + } + + public void setDownloadSpeed(DataSize downloadSpeed) { + this.downloadSpeed = downloadSpeed; + } + + public Credentials getCredentials() { + return credentials; + } + + public void setCredentials(Credentials credentials) { + this.credentials = credentials; + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfig.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfig.java new file mode 100644 index 0000000000..0c9e62445a --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfig.java @@ -0,0 +1,43 @@ +package com.baeldung.boot.configurationproperties; + +import java.util.Map; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "server") +public class ServerConfig { + + private Address address; + private Map resourcesPath; + + public static class Address { + + private String ip; + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public Map getResourcesPath() { + return resourcesPath; + } + + public void setResourcesPath(Map resourcesPath) { + this.resourcesPath = resourcesPath; + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfigFactory.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfigFactory.java new file mode 100644 index 0000000000..ca85d59112 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfigFactory.java @@ -0,0 +1,15 @@ +package com.baeldung.boot.configurationproperties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ServerConfigFactory { + + @Bean(name = "default_bean") + @ConfigurationProperties(prefix = "server.default") + public ServerConfig getDefaultConfigs() { + return new ServerConfig(); + } +} \ No newline at end of file diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/HomeController.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/HomeController.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/HomeController.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/HomeController.java diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/WebController.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/WebController.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/WebController.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/WebController.java diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java diff --git a/spring-boot-testing/src/main/java/com/baeldung/component/OtherComponent.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/component/OtherComponent.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/component/OtherComponent.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/component/OtherComponent.java diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationCommandLineRunnerApp.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationCommandLineRunnerApp.java new file mode 100644 index 0000000000..76e18dfd2f --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationCommandLineRunnerApp.java @@ -0,0 +1,11 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationCommandLineRunnerApp { + public static void main(String[] args) { + SpringApplication.run(ApplicationCommandLineRunnerApp.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java new file mode 100644 index 0000000000..3bf08491bf --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java @@ -0,0 +1,27 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Profile("!test") +@ConditionalOnProperty( + prefix = "application.runner", + value = "enabled", + havingValue = "true", + matchIfMissing = true) +@Component +public class ApplicationRunnerTaskExecutor implements ApplicationRunner { + private TaskService taskService; + + public ApplicationRunnerTaskExecutor(TaskService taskService) { + this.taskService = taskService; + } + + @Override + public void run(ApplicationArguments args) throws Exception { + taskService.execute("application runner task"); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java new file mode 100644 index 0000000000..38fd3b9c0a --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java @@ -0,0 +1,26 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Profile("!test") +@ConditionalOnProperty( + prefix = "command.line.runner", + value = "enabled", + havingValue = "true", + matchIfMissing = true) +@Component +public class CommandLineTaskExecutor implements CommandLineRunner { + private TaskService taskService; + + public CommandLineTaskExecutor(TaskService taskService) { + this.taskService = taskService; + } + + @Override + public void run(String... args) throws Exception { + taskService.execute("command line runner task"); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java new file mode 100644 index 0000000000..dac437e72d --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java @@ -0,0 +1,14 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +@Service +public class TaskService { + private static Logger logger = LoggerFactory.getLogger(TaskService.class); + + public void execute(String task) { + logger.info("do " + task); + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java diff --git a/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelController.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelController.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelController.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelController.java diff --git a/spring-boot-testing/src/main/resources/application-test.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/application-test.properties similarity index 100% rename from spring-boot-testing/src/main/resources/application-test.properties rename to spring-boot-modules/spring-boot-testing/src/main/resources/application-test.properties diff --git a/spring-boot-testing/src/main/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties similarity index 100% rename from spring-boot-testing/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-testing/src/main/resources/application.properties diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/property-validation.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/property-validation.properties new file mode 100644 index 0000000000..6b4c881dc0 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/resources/property-validation.properties @@ -0,0 +1,4 @@ +validate.propertiesMap.first=prop1 +validate.propertiesMap.second=prop2 + +validate.mail_config.address=user1@test \ No newline at end of file diff --git a/spring-boot-testing/src/test/groovy/com/baeldung/boot/LoadContextTest.groovy b/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/LoadContextTest.groovy similarity index 100% rename from spring-boot-testing/src/test/groovy/com/baeldung/boot/LoadContextTest.groovy rename to spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/LoadContextTest.groovy diff --git a/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy b/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy similarity index 85% rename from spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy rename to spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy index d8b4e03adc..fe53abd241 100644 --- a/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy +++ b/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy @@ -1,8 +1,10 @@ package com.baeldung.boot import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest +import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultMatchers @@ -12,8 +14,9 @@ import spock.lang.Title @Title("WebController Specification") @Narrative("The Specification of the behaviour of the WebController. It can greet a person, change the name and reset it to 'world'") -@AutoConfigureMockMvc(secure=false) -@WebMvcTest() +@SpringBootTest +@AutoConfigureMockMvc +@EnableAutoConfiguration(exclude= SecurityAutoConfiguration.class) class WebControllerTest extends Specification { @Autowired diff --git a/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy alias b/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy alias similarity index 100% rename from spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy alias rename to spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy alias diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java similarity index 76% rename from spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java index a4a29cddf3..2ca0c74901 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java @@ -1,26 +1,32 @@ package com.baeldung.autoconfig.exclude; -import static org.junit.Assert.assertEquals; +import com.baeldung.boot.Application; import io.restassured.RestAssured; - 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.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.boot.Application; +import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) @TestPropertySource(properties = "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration") public class ExcludeAutoConfig1IntegrationTest { + /** + * Encapsulates the random port the test server is listening on. + */ + @LocalServerPort + private int port; + @Test public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); assertEquals(HttpStatus.OK.value(), statusCode); } } diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java new file mode 100644 index 0000000000..c0bd6570a1 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.autoconfig.exclude; + +import com.baeldung.boot.Application; +import io.restassured.RestAssured; +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.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +public class ExcludeAutoConfig2IntegrationTest { + + /** + * Encapsulates the random port the test server is listening on. + */ + @LocalServerPort + private int port; + + @Test + public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { + int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); + assertEquals(HttpStatus.OK.value(), statusCode); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java similarity index 77% rename from spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java index 0e45d1e9e5..1642d4b932 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java @@ -1,27 +1,33 @@ package com.baeldung.autoconfig.exclude; -import static org.junit.Assert.assertEquals; +import com.baeldung.boot.Application; import io.restassured.RestAssured; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.boot.Application; +import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) @EnableAutoConfiguration(exclude=SecurityAutoConfiguration.class) public class ExcludeAutoConfig3IntegrationTest { + /** + * Encapsulates the random port the test server is listening on. + */ + @LocalServerPort + private int port; + @Test public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); assertEquals(HttpStatus.OK.value(), statusCode); } } diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java new file mode 100644 index 0000000000..1aa453348b --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java @@ -0,0 +1,29 @@ +package com.baeldung.autoconfig.exclude; + +import io.restassured.RestAssured; +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.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class ExcludeAutoConfig4IntegrationTest { + + /** + * Encapsulates the random port the test server is listening on. + */ + @LocalServerPort + private int port; + + @Test + public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { + int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); + assertEquals(HttpStatus.OK.value(), statusCode); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/TestApplication.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/TestApplication.java similarity index 100% rename from spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/TestApplication.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/TestApplication.java diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java similarity index 100% rename from spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java new file mode 100644 index 0000000000..44a02c0c80 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.boot.autoconfig; + +import com.baeldung.boot.Application; +import io.restassured.RestAssured; +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.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class AutoConfigIntegrationTest { + + /** + * Encapsulates the random port the test server is listening on. + */ + @LocalServerPort + private int port; + + @Test + public void givenNoAuthentication_whenAccessHome_thenUnauthorized() { + int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); + assertEquals(HttpStatus.UNAUTHORIZED.value(), statusCode); + } + + @Test + public void givenAuthentication_whenAccessHome_thenOK() { + int statusCode = RestAssured.given().auth().basic("john", "123").get("http://localhost:" + port).statusCode(); + assertEquals(HttpStatus.OK.value(), statusCode); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToBeanMethodsUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToBeanMethodsUnitTest.java new file mode 100644 index 0000000000..82c2a55c32 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToBeanMethodsUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.boot.configurationproperties; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@EnableConfigurationProperties(value = ServerConfig.class) +@ContextConfiguration(classes = ServerConfigFactory.class) +@TestPropertySource("classpath:server-config-test.properties") +public class BindingPropertiesToBeanMethodsUnitTest { + + @Autowired + @Qualifier("default_bean") + private ServerConfig serverConfig; + + @Test + void givenBeanAnnotatedMethod_whenBindingProperties_thenAllFieldsAreSet() { + assertEquals("192.168.0.2", serverConfig.getAddress() + .getIp()); + + Map expectedResourcesPath = new HashMap<>(); + expectedResourcesPath.put("imgs", "/root/def/imgs"); + assertEquals(expectedResourcesPath, serverConfig.getResourcesPath()); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToUserDefinedPOJOUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToUserDefinedPOJOUnitTest.java new file mode 100644 index 0000000000..9db906fa04 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToUserDefinedPOJOUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.boot.configurationproperties; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@EnableConfigurationProperties(value = ServerConfig.class) +@TestPropertySource("classpath:server-config-test.properties") +public class BindingPropertiesToUserDefinedPOJOUnitTest { + + @Autowired + private ServerConfig serverConfig; + + @Test + void givenUserDefinedPOJO_whenBindingPropertiesFile_thenAllFieldsAreSet() { + assertEquals("192.168.0.1", serverConfig.getAddress() + .getIp()); + + Map expectedResourcesPath = new HashMap<>(); + expectedResourcesPath.put("imgs", "/root/imgs"); + assertEquals(expectedResourcesPath, serverConfig.getResourcesPath()); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingYMLPropertiesUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingYMLPropertiesUnitTest.java new file mode 100644 index 0000000000..5543f5e9e8 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingYMLPropertiesUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.boot.configurationproperties; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class) +@EnableConfigurationProperties(value = ServerConfig.class) +@ActiveProfiles("test") +public class BindingYMLPropertiesUnitTest { + + @Autowired + private ServerConfig serverConfig; + + @Test + void whenBindingYMLConfigFile_thenAllFieldsAreSet() { + assertEquals("192.168.0.4", serverConfig.getAddress() + .getIp()); + + Map expectedResourcesPath = new HashMap<>(); + expectedResourcesPath.put("imgs", "/etc/test/imgs"); + assertEquals(expectedResourcesPath, serverConfig.getResourcesPath()); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/OverridingConfigurationPropertiesUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/OverridingConfigurationPropertiesUnitTest.java new file mode 100644 index 0000000000..2779b0a313 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/OverridingConfigurationPropertiesUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.boot.configurationproperties; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@EnableConfigurationProperties(value = MailServer.class) +@TestPropertySource(properties = { "validate.mail_config.address=new_user@test" }) +public class OverridingConfigurationPropertiesUnitTest { + + @Autowired + private MailServer mailServer; + + @Test + void givenUsingPropertiesAttribute_whenAssiginingNewValueToProprty_thenSpringUsesNewValue() { + assertEquals("new_user@test", mailServer.getMailConfig() + .getAddress()); + + Map expectedMap = new HashMap<>(); + expectedMap.put("first", "prop1"); + expectedMap.put("second", "prop2"); + assertEquals(expectedMap, mailServer.getPropertiesMap()); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/PropertyValidationUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/PropertyValidationUnitTest.java new file mode 100644 index 0000000000..939471dd67 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/PropertyValidationUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.boot.configurationproperties; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import javax.validation.Validation; +import javax.validation.Validator; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@EnableConfigurationProperties(value = MailServer.class) +@TestPropertySource("classpath:property-validation-test.properties") +public class PropertyValidationUnitTest { + + @Autowired + private MailServer mailServer; + + private static Validator propertyValidator; + + @BeforeAll + public static void setup() { + propertyValidator = Validation.buildDefaultValidatorFactory() + .getValidator(); + } + + @Test + void whenBindingPropertiesToValidatedBeans_thenConstrainsAreChecked() { + assertEquals(0, propertyValidator.validate(mailServer.getPropertiesMap()) + .size()); + assertEquals(0, propertyValidator.validate(mailServer.getMailConfig()) + .size()); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/SpringPropertiesConversionUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/SpringPropertiesConversionUnitTest.java new file mode 100644 index 0000000000..3f2da2a669 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/SpringPropertiesConversionUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.boot.configurationproperties; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.util.unit.DataSize; + +@ExtendWith(SpringExtension.class) +@EnableConfigurationProperties(value = PropertyConversion.class) +@ContextConfiguration(classes = CustomCredentialsConverter.class) +@TestPropertySource("classpath:spring-conversion-test.properties") +public class SpringPropertiesConversionUnitTest { + + @Autowired + private PropertyConversion propertyConversion; + + @Test + void whenUsingSpringDefaultSizeConversion_thenDataSizeObjectIsSet() { + assertEquals(DataSize.ofMegabytes(500), propertyConversion.getUploadSpeed()); + assertEquals(DataSize.ofGigabytes(10), propertyConversion.getDownloadSpeed()); + } + + @Test + void whenUsingSpringDefaultDurationConversion_thenDurationObjectIsSet() { + assertEquals(Duration.ofDays(1), propertyConversion.getBackupDay()); + assertEquals(Duration.ofHours(8), propertyConversion.getBackupHour()); + } + + @Test + void whenRegisteringCustomCredentialsConverter_thenCredentialsAreParsed() { + assertEquals("user", propertyConversion.getCredentials() + .getUsername()); + assertEquals("123", propertyConversion.getCredentials() + .getPassword()); + } +} \ No newline at end of file diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java similarity index 100% rename from spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java similarity index 100% rename from spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/LoadSpringContextIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/LoadSpringContextIntegrationTest.java new file mode 100644 index 0000000000..6698094550 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/LoadSpringContextIntegrationTest.java @@ -0,0 +1,43 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.prevent.commandline.application.runner.execution.ApplicationCommandLineRunnerApp; +import com.baeldung.prevent.commandline.application.runner.execution.TaskService; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { ApplicationCommandLineRunnerApp.class }, + initializers = ConfigFileApplicationContextInitializer.class) +public class LoadSpringContextIntegrationTest { + @SpyBean + TaskService taskService; + + @SpyBean + CommandLineRunner commandLineRunner; + + @SpyBean + ApplicationRunner applicationRunner; + + @Test + void whenContextLoads_thenRunnersDoNotRun() throws Exception { + assertNotNull(taskService); + assertNotNull(commandLineRunner); + assertNotNull(applicationRunner); + + verify(taskService, times(0)).execute(any()); + verify(commandLineRunner, times(0)).run(any()); + verify(applicationRunner, times(0)).run(any()); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java new file mode 100644 index 0000000000..26a7339f1d --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.SpyBean; + +import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor; +import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@SpringBootTest +class RunApplicationIntegrationTest { + @SpyBean + ApplicationRunnerTaskExecutor applicationRunnerTaskExecutor; + @SpyBean + CommandLineTaskExecutor commandLineTaskExecutor; + + @Test + void whenContextLoads_thenRunnersRun() throws Exception { + verify(applicationRunnerTaskExecutor, times(1)).run(any()); + verify(commandLineTaskExecutor, times(1)).run(any()); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestProfileIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestProfileIntegrationTest.java new file mode 100644 index 0000000000..333cd2ab91 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestProfileIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ActiveProfiles; + +import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor; +import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor; +import com.baeldung.prevent.commandline.application.runner.execution.TaskService; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@ActiveProfiles("test") +@SpringBootTest +class RunApplicationWithTestProfileIntegrationTest { + @Autowired + private ApplicationContext context; + + @Test + void whenContextLoads_thenRunnersAreNotLoaded() { + assertNotNull(context.getBean(TaskService.class)); + assertThrows(NoSuchBeanDefinitionException.class, + () -> context.getBean(CommandLineTaskExecutor.class), + "CommandLineRunner should not be loaded during this integration test"); + assertThrows(NoSuchBeanDefinitionException.class, + () -> context.getBean(ApplicationRunnerTaskExecutor.class), + "ApplicationRunner should not be loaded during this integration test"); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestPropertiesIntegrationTest.java new file mode 100644 index 0000000000..264a06a41e --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestPropertiesIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; + +import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor; +import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor; +import com.baeldung.prevent.commandline.application.runner.execution.TaskService; + +@SpringBootTest(properties = { + "command.line.runner.enabled=false", + "application.runner.enabled=false" }) +class RunApplicationWithTestPropertiesIntegrationTest { + @Autowired + private ApplicationContext context; + + @Test + void whenContextLoads_thenRunnersAreNotLoaded() { + assertNotNull(context.getBean(TaskService.class)); + assertThrows(NoSuchBeanDefinitionException.class, + () -> context.getBean(CommandLineTaskExecutor.class), + "CommandLineRunner should not be loaded during this integration test"); + assertThrows(NoSuchBeanDefinitionException.class, + () -> context.getBean(ApplicationRunnerTaskExecutor.class), + "ApplicationRunner should not be loaded during this integration test"); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java similarity index 94% rename from spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java index 7a1eb4adbe..f8bd61e5c7 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java @@ -1,7 +1,5 @@ package com.baeldung.testloglevel; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -13,9 +11,14 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; + +@DirtiesContext(classMode = AFTER_CLASS) @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class) @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) diff --git a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java similarity index 94% rename from spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java index af3bafdc2e..ffe9d400ed 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java @@ -1,7 +1,5 @@ package com.baeldung.testloglevel; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -13,9 +11,14 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; + +@DirtiesContext(classMode = AFTER_CLASS) @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class) @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) diff --git a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java similarity index 94% rename from spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java index 5609ce6c01..6e80f50c00 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java @@ -11,12 +11,15 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; @RunWith(SpringRunner.class) +@DirtiesContext(classMode = AFTER_CLASS) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class) @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) @ActiveProfiles("logging-test") diff --git a/spring-boot-testing/src/test/resources/application-logback-test.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application-logback-test.properties similarity index 100% rename from spring-boot-testing/src/test/resources/application-logback-test.properties rename to spring-boot-modules/spring-boot-testing/src/test/resources/application-logback-test.properties diff --git a/spring-boot-testing/src/test/resources/application-logback-test2.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application-logback-test2.properties similarity index 100% rename from spring-boot-testing/src/test/resources/application-logback-test2.properties rename to spring-boot-modules/spring-boot-testing/src/test/resources/application-logback-test2.properties diff --git a/spring-boot-testing/src/test/resources/application-logging-test.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application-logging-test.properties similarity index 100% rename from spring-boot-testing/src/test/resources/application-logging-test.properties rename to spring-boot-modules/spring-boot-testing/src/test/resources/application-logging-test.properties diff --git a/spring-boot-testing/src/test/resources/application-test.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application-test.properties similarity index 100% rename from spring-boot-testing/src/test/resources/application-test.properties rename to spring-boot-modules/spring-boot-testing/src/test/resources/application-test.properties diff --git a/spring-boot-testing/src/test/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties similarity index 100% rename from spring-boot-testing/src/test/resources/application.properties rename to spring-boot-modules/spring-boot-testing/src/test/resources/application.properties diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application.yml b/spring-boot-modules/spring-boot-testing/src/test/resources/application.yml new file mode 100644 index 0000000000..1b46b0f1ff --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/resources/application.yml @@ -0,0 +1,15 @@ +spring: + profiles: test +server: + address: + ip: 192.168.0.4 + resources_path: + imgs: /etc/test/imgs +--- +spring: + profiles: dev +server: + address: + ip: 192.168.0.5 + resources_path: + imgs: /etc/dev/imgs \ No newline at end of file diff --git a/spring-boot-testing/src/test/resources/logback-multiprofile.xml b/spring-boot-modules/spring-boot-testing/src/test/resources/logback-multiprofile.xml similarity index 100% rename from spring-boot-testing/src/test/resources/logback-multiprofile.xml rename to spring-boot-modules/spring-boot-testing/src/test/resources/logback-multiprofile.xml diff --git a/spring-boot-testing/src/test/resources/logback-test.xml b/spring-boot-modules/spring-boot-testing/src/test/resources/logback-test.xml similarity index 100% rename from spring-boot-testing/src/test/resources/logback-test.xml rename to spring-boot-modules/spring-boot-testing/src/test/resources/logback-test.xml diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/property-validation-test.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/property-validation-test.properties new file mode 100644 index 0000000000..6b4c881dc0 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/resources/property-validation-test.properties @@ -0,0 +1,4 @@ +validate.propertiesMap.first=prop1 +validate.propertiesMap.second=prop2 + +validate.mail_config.address=user1@test \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/server-config-test.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/server-config-test.properties new file mode 100644 index 0000000000..62b23ed1d6 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/resources/server-config-test.properties @@ -0,0 +1,6 @@ +server.address.ip=192.168.0.1 +server.resources_path.imgs=/root/imgs + +# default config +server.default.address.ip=192.168.0.2 +server.default.resources_path.imgs=/root/def/imgs \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/spring-conversion-test.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/spring-conversion-test.properties new file mode 100644 index 0000000000..87444cee10 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/resources/spring-conversion-test.properties @@ -0,0 +1,10 @@ +# bandwidth +server.upload_speed=500MB +server.download_speed=10 + +# backup date +server.backup_day=1d +server.backup_hour=8 + +# custom converter +server.credentials=user,123 \ No newline at end of file diff --git a/spring-boot-vue/.gitignore b/spring-boot-modules/spring-boot-vue/.gitignore similarity index 100% rename from spring-boot-vue/.gitignore rename to spring-boot-modules/spring-boot-vue/.gitignore diff --git a/spring-boot-vue/README.md b/spring-boot-modules/spring-boot-vue/README.md similarity index 100% rename from spring-boot-vue/README.md rename to spring-boot-modules/spring-boot-vue/README.md diff --git a/spring-boot-modules/spring-boot-vue/pom.xml b/spring-boot-modules/spring-boot-vue/pom.xml new file mode 100644 index 0000000000..0a6307e46b --- /dev/null +++ b/spring-boot-modules/spring-boot-vue/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + spring-boot-vue + 0.0.1-SNAPSHOT + spring-boot-vue + jar + Demo project for Spring Boot Vue project + + + com.baeldung + parent-boot-2 + 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-thymeleaf + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + UTF-8 + + + diff --git a/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java b/spring-boot-modules/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java similarity index 100% rename from spring-boot-vue/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java rename to spring-boot-modules/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java diff --git a/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/controllers/MainController.java b/spring-boot-modules/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/controllers/MainController.java similarity index 100% rename from spring-boot-vue/src/main/java/com/baeldung/springbootmvc/controllers/MainController.java rename to spring-boot-modules/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/controllers/MainController.java diff --git a/spring-boot-modules/spring-boot-vue/src/main/resources/application.properties b/spring-boot-modules/spring-boot-vue/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-modules/spring-boot-vue/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-vue/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-modules/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-modules/spring-boot-vue/src/main/resources/static/favicon.ico similarity index 100% rename from spring-boot-vue/src/main/resources/static/favicon.ico rename to spring-boot-modules/spring-boot-vue/src/main/resources/static/favicon.ico diff --git a/spring-boot-vue/src/main/resources/templates/index.html b/spring-boot-modules/spring-boot-vue/src/main/resources/templates/index.html similarity index 100% rename from spring-boot-vue/src/main/resources/templates/index.html rename to spring-boot-modules/spring-boot-vue/src/main/resources/templates/index.html diff --git a/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationIntegrationTest.java similarity index 100% rename from spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e73f4e79f7 --- /dev/null +++ b/spring-boot-modules/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.springbootmvc.SpringBootMvcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootMvcApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-modules/spring-boot/.gitignore b/spring-boot-modules/spring-boot/.gitignore new file mode 100644 index 0000000000..da7c2c5c0a --- /dev/null +++ b/spring-boot-modules/spring-boot/.gitignore @@ -0,0 +1,5 @@ +/target/ +.settings/ +.classpath +.project + diff --git a/spring-boot/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot/.mvn/wrapper/maven-wrapper.properties similarity index 100% rename from spring-boot/.mvn/wrapper/maven-wrapper.properties rename to spring-boot-modules/spring-boot/.mvn/wrapper/maven-wrapper.properties diff --git a/spring-boot-modules/spring-boot/README.MD b/spring-boot-modules/spring-boot/README.MD new file mode 100644 index 0000000000..fb1c20e988 --- /dev/null +++ b/spring-boot-modules/spring-boot/README.MD @@ -0,0 +1,28 @@ +## Spring Boot + +This module contains articles about Spring Boot + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring) +- [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) +- [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) +- [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) +- [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) +- [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) +- [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom) +- [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) +- [How to Get All Spring-Managed Beans?](https://www.baeldung.com/spring-show-all-beans) +- [Spring Boot and Togglz Aspect](https://www.baeldung.com/spring-togglz) +- [Getting Started with GraphQL and Spring Boot](https://www.baeldung.com/spring-graphql) +- [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) +- [An Introduction to Kong](https://www.baeldung.com/kong) +- [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) +- [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) +- [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) +- [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) +- [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) +- [Running Setup Data on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) diff --git a/spring-boot/mvnw b/spring-boot-modules/spring-boot/mvnw similarity index 100% rename from spring-boot/mvnw rename to spring-boot-modules/spring-boot/mvnw diff --git a/spring-boot/mvnw.cmd b/spring-boot-modules/spring-boot/mvnw.cmd similarity index 97% rename from spring-boot/mvnw.cmd rename to spring-boot-modules/spring-boot/mvnw.cmd index 4f0b068a03..6a6eec39ba 100755 --- a/spring-boot/mvnw.cmd +++ b/spring-boot-modules/spring-boot/mvnw.cmd @@ -1,145 +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% +@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-modules/spring-boot/pom.xml b/spring-boot-modules/spring-boot/pom.xml new file mode 100644 index 0000000000..e0ff9ae2f9 --- /dev/null +++ b/spring-boot-modules/spring-boot/pom.xml @@ -0,0 +1,234 @@ + + + 4.0.0 + spring-boot + spring-boot + war + This is simple boot application for Spring boot actuator test + 0.0.1-SNAPSHOT + + + 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-thymeleaf + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.ehcache + ehcache + + + org.hibernate + hibernate-ehcache + + + org.springframework.boot + spring-boot-starter-actuator + + + + com.graphql-java + graphql-spring-boot-starter + ${graphql-spring-boot-starter.version} + + + com.graphql-java + graphql-java-tools + ${graphql-java-tools.version} + + + com.graphql-java + graphiql-spring-boot-starter + ${graphiql-spring-boot-starter.version} + + + + org.springframework.boot + spring-boot-starter-tomcat + + + + org.springframework.boot + spring-boot-starter-test + test + + + + io.dropwizard.metrics + metrics-core + + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter + + + com.jayway.jsonpath + json-path + test + + + + com.google.guava + guava + ${guava.version} + + + + org.apache.tomcat + tomcat-servlet-api + ${tomee-servlet-api.version} + provided + + + + org.togglz + togglz-spring-boot-starter + ${togglz.version} + + + + org.togglz + togglz-spring-security + ${togglz.version} + + + + org.apache.activemq + artemis-server + + + + com.rometools + rome + ${rome.version} + + + + javax.validation + validation-api + + + + + spring-boot + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.apache.maven.plugins + maven-resources-plugin + + + @ + + false + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + + com.baeldung.intro.App + 8.5.11 + 2.4.1.Final + 1.9.0 + 5.0.2 + 5.0.2 + 5.2.4 + 18.0 + @ + + + diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/Application.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/Application.java new file mode 100644 index 0000000000..e2b933a67e --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/Application.java @@ -0,0 +1,28 @@ +package com.baeldung.beanvalidation.application; + +import com.baeldung.beanvalidation.application.entities.User; +import com.baeldung.beanvalidation.application.repositories.UserRepository; + +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 { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public CommandLineRunner run(UserRepository userRepository) throws Exception { + return (String[] args) -> { + User user1 = new User("Bob", "bob@domain.com"); + User user2 = new User("Jenny", "jenny@domain.com"); + userRepository.save(user1); + userRepository.save(user2); + userRepository.findAll().forEach(System.out::println); + }; + } +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java new file mode 100644 index 0000000000..abda9a9449 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java @@ -0,0 +1,53 @@ +package com.baeldung.beanvalidation.application.controllers; + +import com.baeldung.beanvalidation.application.entities.User; +import com.baeldung.beanvalidation.application.repositories.UserRepository; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.Valid; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserController { + + private final UserRepository userRepository; + + @Autowired + public UserController(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @GetMapping("/users") + public List getUsers() { + return (List) userRepository.findAll(); + } + + @PostMapping("/users") + ResponseEntity addUser(@Valid @RequestBody User user) { + return ResponseEntity.ok("User is valid"); + } + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(MethodArgumentNotValidException.class) + public Map handleValidationExceptions(MethodArgumentNotValidException ex) { + Map errors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach((error) -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + return errors; + } +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/entities/User.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/entities/User.java new file mode 100644 index 0000000000..511ce47775 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/entities/User.java @@ -0,0 +1,50 @@ +package com.baeldung.beanvalidation.application.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.NotBlank; + +@Entity +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @NotBlank(message = "Name is mandatory") + private String name; + + @NotBlank(message = "Email is mandatory") + private String email; + + public User(){} + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; + } +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java new file mode 100644 index 0000000000..7b55d15a01 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.beanvalidation.application.repositories; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.beanvalidation.application.entities.User; + +@Repository +public interface UserRepository extends CrudRepository {} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java new file mode 100644 index 0000000000..cb0d0c1532 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java @@ -0,0 +1,14 @@ +package com.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/config/H2JpaConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java similarity index 89% rename from spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java index 92a6ed7ab0..928928c9a5 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.config; +package com.baeldung.boot.config; import java.util.Properties; @@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.boot.boottest", "org.baeldung.repository" }) +@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.boot.boottest", "com.baeldung.repository" }) @PropertySource("classpath:persistence-generic-entity.properties") @EnableTransactionManagement public class H2JpaConfig { @@ -41,7 +41,7 @@ public class H2JpaConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.boot.domain", "org.baeldung.boot.model", "org.baeldung.boot.boottest", "org.baeldung.model" }); + em.setPackagesToScan(new String[] { "com.baeldung.boot.domain", "com.baeldung.boot.model", "com.baeldung.boot.boottest", "com.baeldung.model" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java new file mode 100644 index 0000000000..b23c910a04 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.boot.config; + +import com.baeldung.boot.converter.StringToEmployeeConverter; +import com.baeldung.boot.converter.StringToEnumConverterFactory; +import com.baeldung.boot.converter.GenericBigDecimalConverter; +import org.springframework.context.annotation.Configuration; +import org.springframework.format.FormatterRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @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/servlet/HelloWorldServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java similarity index 96% rename from spring-boot/src/main/java/org/baeldung/boot/controller/servlet/HelloWorldServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java index 34ad11254c..80c75aa8b5 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/HelloWorldServlet.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.controller.servlet; +package com.baeldung.boot.controller.servlet; import java.io.IOException; import java.io.PrintWriter; diff --git a/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java similarity index 96% rename from spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java index 91547683c6..f276f94b7c 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.controller.servlet; +package com.baeldung.boot.controller.servlet; import java.io.IOException; import java.io.PrintWriter; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java new file mode 100644 index 0000000000..fc73cfee5f --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java @@ -0,0 +1,31 @@ +package com.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-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java new file mode 100644 index 0000000000..ac635532ea --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java @@ -0,0 +1,14 @@ +package com.baeldung.boot.converter; + +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])); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java similarity index 95% rename from spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java index ddb2cd2b08..a2dce11a6a 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.converter; +package com.baeldung.boot.converter; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java new file mode 100644 index 0000000000..260b1c734b --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java @@ -0,0 +1,17 @@ +package com.baeldung.boot.converter.controller; + +import org.springframework.http.ResponseEntity; +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 +public class StringToEmployeeConverterController { + + @GetMapping("/string-to-employee") + public ResponseEntity getStringToEmployee(@RequestParam("employee") Employee employee) { + return ResponseEntity.ok(employee); + } +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java new file mode 100644 index 0000000000..7717294996 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java @@ -0,0 +1,6 @@ +package com.baeldung.boot.domain; + +public enum Modes { + + ALPHA, BETA; +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java new file mode 100644 index 0000000000..405cec3eac --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java @@ -0,0 +1,18 @@ +package com.baeldung.buildproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@ComponentScan(basePackages = "com.baeldung.buildproperties") +@PropertySource("classpath:build.properties") +//@PropertySource("classpath:build.yml") +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java new file mode 100644 index 0000000000..2a0d27188e --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java @@ -0,0 +1,21 @@ +package com.baeldung.buildproperties; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +@Service +public class BuildInfoService { + @Value("${application-description}") + private String applicationDescription; + + @Value("${application-version}") + private String applicationVersion; + + public String getApplicationDescription() { + return applicationDescription; + } + + public String getApplicationVersion() { + return applicationVersion; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java similarity index 89% rename from spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java index 6b342a1bfb..373ae8f745 100644 --- a/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java @@ -1,24 +1,24 @@ -package org.baeldung.common.error; - -import org.springframework.boot.web.servlet.error.ErrorController; -import org.springframework.web.bind.annotation.GetMapping; - -public class MyCustomErrorController implements ErrorController { - - private static final String PATH = "/error"; - - public MyCustomErrorController() { - // TODO Auto-generated constructor stub - } - - @GetMapping(value = PATH) - public String error() { - return "Error haven"; - } - - @Override - public String getErrorPath() { - return PATH; - } - -} +package com.baeldung.common.error; + +import org.springframework.boot.web.servlet.error.ErrorController; +import org.springframework.web.bind.annotation.GetMapping; + +public class MyCustomErrorController implements ErrorController { + + private static final String PATH = "/error"; + + public MyCustomErrorController() { + // TODO Auto-generated constructor stub + } + + @GetMapping(value = PATH) + public String error() { + return "Error haven"; + } + + @Override + public String getErrorPath() { + return PATH; + } + +} diff --git a/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java similarity index 88% rename from spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java index 723afddd06..3f51a4ab69 100644 --- a/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java @@ -1,15 +1,15 @@ -package org.baeldung.common.error; - -import org.springframework.boot.web.servlet.ServletRegistrationBean; - -import javax.servlet.Servlet; - -public class SpringHelloServletRegistrationBean extends ServletRegistrationBean { - - public SpringHelloServletRegistrationBean() { - } - - public SpringHelloServletRegistrationBean(Servlet servlet, String... urlMappings) { - super(servlet, urlMappings); - } -} +package com.baeldung.common.error; + +import org.springframework.boot.web.servlet.ServletRegistrationBean; + +import javax.servlet.Servlet; + +public class SpringHelloServletRegistrationBean extends ServletRegistrationBean { + + public SpringHelloServletRegistrationBean() { + } + + public SpringHelloServletRegistrationBean(Servlet servlet, String... urlMappings) { + super(servlet, urlMappings); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java similarity index 86% rename from spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java index 3e26f8c9d8..1e5fbf3ac4 100644 --- a/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java @@ -1,22 +1,22 @@ -package org.baeldung.common.error.controller; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class ErrorController { - - public ErrorController() { - } - - @GetMapping("/400") - String error400() { - return "Error Code: 400 occured."; - } - - @GetMapping("/errorHaven") - String errorHeaven() { - return "You have reached the haven of errors!!!"; - } - -} +package com.baeldung.common.error.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ErrorController { + + public ErrorController() { + } + + @GetMapping("/400") + String error400() { + return "Error Code: 400 occured."; + } + + @GetMapping("/errorHaven") + String errorHeaven() { + 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-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java similarity index 92% rename from spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java index f6ab017298..be503b1b6c 100644 --- a/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java @@ -1,25 +1,25 @@ -package org.baeldung.common.properties; - -import org.springframework.boot.web.server.ErrorPage; -import org.springframework.boot.web.server.WebServerFactoryCustomizer; -import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; - -@Component -public class MyServletContainerCustomizationBean implements WebServerFactoryCustomizer { - - public MyServletContainerCustomizationBean() { - - } - - @Override - public void customize(ConfigurableServletWebServerFactory container) { - container.setPort(8084); - container.setContextPath("/springbootapp"); - - container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); - container.addErrorPages(new ErrorPage("/errorHaven")); - } - -} +package com.baeldung.common.properties; + +import org.springframework.boot.web.server.ErrorPage; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; + +@Component +public class MyServletContainerCustomizationBean implements WebServerFactoryCustomizer { + + public MyServletContainerCustomizationBean() { + + } + + @Override + public void customize(ConfigurableServletWebServerFactory container) { + container.setPort(8084); + container.setContextPath("/springbootapp"); + + container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); + container.addErrorPages(new ErrorPage("/errorHaven")); + } + +} diff --git a/spring-boot/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java similarity index 90% rename from spring-boot/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java index be33d64c5d..1db7054f85 100644 --- a/spring-boot/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java @@ -1,28 +1,28 @@ -package org.baeldung.common.resources; - -import org.springframework.boot.ExitCodeGenerator; - -import java.util.Objects; -import java.util.concurrent.ExecutorService; - -public class ExecutorServiceExitCodeGenerator implements ExitCodeGenerator { - - private ExecutorService executorService; - - public ExecutorServiceExitCodeGenerator(ExecutorService executorService) { - } - - @Override - public int getExitCode() { - try { - if (!Objects.isNull(executorService)) { - executorService.shutdownNow(); - return 1; - } - - return 0; - } catch (SecurityException ex) { - return 0; - } - } -} +package com.baeldung.common.resources; + +import org.springframework.boot.ExitCodeGenerator; + +import java.util.Objects; +import java.util.concurrent.ExecutorService; + +public class ExecutorServiceExitCodeGenerator implements ExitCodeGenerator { + + private ExecutorService executorService; + + public ExecutorServiceExitCodeGenerator(ExecutorService executorService) { + } + + @Override + public int getExitCode() { + try { + if (!Objects.isNull(executorService)) { + executorService.shutdownNow(); + return 1; + } + + return 0; + } catch (SecurityException ex) { + return 0; + } + } +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java new file mode 100644 index 0000000000..eb091b4695 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java @@ -0,0 +1,18 @@ +package com.baeldung.demo; + +import com.baeldung.graphql.GraphqlConfiguration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import org.springframework.context.annotation.Import; + +@SpringBootApplication +@Import(GraphqlConfiguration.class) +public class DemoApplication { + + public static void main(String[] args) { + System.setProperty("spring.config.name", "demo"); + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java new file mode 100644 index 0000000000..fa3c1dc809 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java @@ -0,0 +1,46 @@ +package com.baeldung.demo.boottest; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.Size; +import java.util.Date; + +@Entity +@Table(name = "person") +public class Employee { + + public Employee() { + } + + public Employee(String name) { + this.name = name; + } + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Size(min = 3, max = 20) + private String name; + + private Date birthday; + + 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; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java new file mode 100644 index 0000000000..b6850d587e --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.demo.boottest; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +@Repository +@Transactional +public interface EmployeeRepository extends JpaRepository { + + public Employee findByName(String name); + + public List findAll(); + +} diff --git a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java similarity index 96% rename from spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java index 516bff0e8c..7d2e06d4a0 100644 --- a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java new file mode 100644 index 0000000000..ff1976cad1 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java @@ -0,0 +1,16 @@ +package com.baeldung.demo.boottest; + +import java.util.List; + +public interface EmployeeService { + + public Employee getEmployeeById(Long id); + + public Employee getEmployeeByName(String name); + + public List getAllEmployees(); + + public boolean exists(String email); + + public Employee save(Employee employee); +} diff --git a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java similarity index 96% rename from spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java index a1639b29cc..156fc571f3 100644 --- a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java new file mode 100644 index 0000000000..98a0db67ef --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java @@ -0,0 +1,21 @@ +package com.baeldung.demo.components; + +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.repository.FooRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class FooService { + + @Autowired + private FooRepository fooRepository; + + public Foo getFooWithId(Integer id) throws Exception { + return fooRepository.findById(id).orElse(null); + } + + public Foo getFooWithName(String name) { + return fooRepository.findByName(name); + } +} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java similarity index 85% rename from spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java index 51dd7bbd44..276802d0b9 100644 --- a/spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.exceptions; +package com.baeldung.demo.exceptions; public class CommonException extends RuntimeException { diff --git a/spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java similarity index 86% rename from spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java index 59796c58f0..8c425d078e 100644 --- a/spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.exceptions; +package com.baeldung.demo.exceptions; public class FooNotFoundException extends RuntimeException { diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java new file mode 100644 index 0000000000..796bcca11b --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java @@ -0,0 +1,45 @@ +package com.baeldung.demo.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Foo implements Serializable { + private static final long serialVersionUID = 1L; + @Id + @GeneratedValue + private Integer id; + private String name; + + public Foo() { + } + + public Foo(String name) { + this.name = name; + } + + public Foo(Integer id, String name) { + super(); + this.id = id; + this.name = 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-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java new file mode 100644 index 0000000000..ed27ac23bc --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.demo.repository; + +import com.baeldung.demo.model.Foo; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface FooRepository extends JpaRepository { + public Foo findByName(String name); +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java new file mode 100644 index 0000000000..c72c52fa3e --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java @@ -0,0 +1,26 @@ +package com.baeldung.demo.service; + +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.components.FooService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class FooController { + + @Autowired + private FooService fooService; + + @GetMapping("/{id}") + public Foo getFooWithId(@PathVariable Integer id) throws Exception { + return fooService.getFooWithId(id); + } + + @GetMapping("/") + public Foo getFooWithName(@RequestParam String name) throws Exception { + return fooService.getFooWithName(name); + } +} \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java new file mode 100644 index 0000000000..5b5b4ae834 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java @@ -0,0 +1,23 @@ +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; + +import com.baeldung.displayallbeans.service.FooService; + +@Controller +public class FooController { + @Autowired + private FooService fooService; + + @GetMapping(value = "/displayallbeans") + public ResponseEntity getHeaderAndBody(Map model) { + model.put("header", fooService.getHeader()); + model.put("message", fooService.getBody()); + return ResponseEntity.ok("displayallbeans"); + } +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java new file mode 100644 index 0000000000..d3f1ea294e --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java @@ -0,0 +1,16 @@ +package com.baeldung.displayallbeans.service; + +import org.springframework.stereotype.Service; + +@Service +public class FooService { + + public String getHeader() { + return "Display All Beans"; + } + + public String getBody() { + return "This is a sample application that displays all beans " + "in Spring IoC container using ListableBeanFactory interface " + "and Spring Boot Actuators."; + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java diff --git a/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java similarity index 89% rename from spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java index 34b50a2c0a..c316cabda5 100644 --- a/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java @@ -1,9 +1,9 @@ -package org.baeldung.endpoints.info; +package com.baeldung.endpoints.info; import java.util.HashMap; import java.util.Map; -import org.baeldung.repository.UserRepository; +import com.baeldung.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Author.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Author.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/graphql/Author.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Author.java diff --git a/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java diff --git a/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java diff --git a/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/graphql/Mutation.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Post.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Post.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/graphql/Post.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Post.java diff --git a/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/graphql/PostDao.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java diff --git a/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Query.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Query.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/graphql/Query.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Query.java diff --git a/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java diff --git a/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java diff --git a/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/App.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/App.java new file mode 100644 index 0000000000..77cdf4ddb9 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/App.java @@ -0,0 +1,11 @@ +package com.baeldung.intro; + +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, args); + } +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java new file mode 100644 index 0000000000..4797d6e593 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java @@ -0,0 +1,18 @@ +package com.baeldung.intro.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HomeController { + + @GetMapping("/") + public String root() { + return "Index Page"; + } + + @GetMapping("/local") + public String local() { + return "/local"; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java diff --git a/spring-boot/src/main/java/com/baeldung/kong/QueryController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/QueryController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/kong/QueryController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/QueryController.java diff --git a/spring-boot/src/main/java/com/baeldung/kong/StockApp.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/StockApp.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/kong/StockApp.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/StockApp.java diff --git a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java similarity index 76% rename from spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java index 30ac94221b..383932524f 100644 --- a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java @@ -1,63 +1,63 @@ -package org.baeldung.main; - -import org.baeldung.boot.controller.servlet.HelloWorldServlet; -import org.baeldung.boot.controller.servlet.SpringHelloWorldServlet; -import org.baeldung.common.error.SpringHelloServletRegistrationBean; -import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -@RestController -@EnableAutoConfiguration -@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config" }) -public class SpringBootApplication { - - private static ApplicationContext applicationContext; - - @GetMapping("/") - String home() { - return "TADA!!! You are in Spring Boot Actuator test application."; - } - - public static void main(String[] args) { - applicationContext = SpringApplication.run(SpringBootApplication.class, args); - } - - @Bean - public ExecutorService executorService() { - return Executors.newFixedThreadPool(10); - } - - @Bean - public HelloWorldServlet helloWorldServlet() { - return new HelloWorldServlet(); - } - - @Bean - public SpringHelloServletRegistrationBean servletRegistrationBean() { - SpringHelloServletRegistrationBean bean = new SpringHelloServletRegistrationBean(new SpringHelloWorldServlet(), "/springHelloWorld/*"); - bean.setLoadOnStartup(1); - bean.addInitParameter("message", "SpringHelloWorldServlet special message"); - return bean; - } - - @Bean - @Autowired - public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) { - return new ExecutorServiceExitCodeGenerator(executorService); - } - - public void shutDown(ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator) { - SpringApplication.exit(applicationContext, executorServiceExitCodeGenerator); - } - -} +package com.baeldung.main; + +import com.baeldung.boot.controller.servlet.HelloWorldServlet; +import com.baeldung.boot.controller.servlet.SpringHelloWorldServlet; +import com.baeldung.common.error.SpringHelloServletRegistrationBean; +import com.baeldung.common.resources.ExecutorServiceExitCodeGenerator; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +@RestController +@EnableAutoConfiguration +@ComponentScan({ "com.baeldung.common.error", "com.baeldung.common.error.controller", "com.baeldung.common.properties", "com.baeldung.common.resources", "com.baeldung.endpoints", "com.baeldung.service", "com.baeldung.monitor.jmx", "com.baeldung.boot.config" }) +public class SpringBootApplication { + + private static ApplicationContext applicationContext; + + @GetMapping("/") + String home() { + return "TADA!!! You are in Spring Boot Actuator test application."; + } + + public static void main(String[] args) { + applicationContext = SpringApplication.run(SpringBootApplication.class, args); + } + + @Bean + public ExecutorService executorService() { + return Executors.newFixedThreadPool(10); + } + + @Bean + public HelloWorldServlet helloWorldServlet() { + return new HelloWorldServlet(); + } + + @Bean + public SpringHelloServletRegistrationBean servletRegistrationBean() { + SpringHelloServletRegistrationBean bean = new SpringHelloServletRegistrationBean(new SpringHelloWorldServlet(), "/springHelloWorld/*"); + bean.setLoadOnStartup(1); + bean.addInitParameter("message", "SpringHelloWorldServlet special message"); + return bean; + } + + @Bean + @Autowired + public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) { + return new ExecutorServiceExitCodeGenerator(executorService); + } + + public void shutDown(ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator) { + SpringApplication.exit(applicationContext, executorServiceExitCodeGenerator); + } + +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java new file mode 100644 index 0000000000..cc5f27f38c --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java @@ -0,0 +1,49 @@ +package com.baeldung.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/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java new file mode 100644 index 0000000000..4dd863fb17 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java @@ -0,0 +1,79 @@ +package com.baeldung.repository; + +import com.baeldung.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.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; + +@Repository("userRepository") +public interface UserRepository extends JpaRepository { + + int countByStatus(int status); + + Optional findOneByName(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/src/main/java/com/baeldung/rss/ArticleFeedView.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleFeedView.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/rss/ArticleFeedView.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleFeedView.java diff --git a/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java diff --git a/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java diff --git a/spring-boot/src/main/java/com/baeldung/rss/RssApp.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/RssApp.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/rss/RssApp.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/RssApp.java diff --git a/spring-boot/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java diff --git a/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java diff --git a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java diff --git a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java diff --git a/spring-boot/src/main/java/com/baeldung/servlets/props/Constants.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/Constants.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servlets/props/Constants.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/Constants.java diff --git a/spring-boot/src/main/java/com/baeldung/servlets/props/PropertyLoader.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertyLoader.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servlets/props/PropertyLoader.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertyLoader.java diff --git a/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java diff --git a/spring-boot/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java diff --git a/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java diff --git a/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java diff --git a/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java diff --git a/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java new file mode 100644 index 0000000000..de4ca5998e --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java @@ -0,0 +1,16 @@ +package com.baeldung.session.exception; + +import com.baeldung.demo.model.Foo; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; + +@EntityScan(basePackageClasses = Foo.class) +@SpringBootApplication +public class Application { + public static void main(String[] args) { + System.setProperty("spring.config.name", "exception"); + System.setProperty("spring.profiles.active", "exception"); + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java new file mode 100644 index 0000000000..5e748973ed --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.session.exception.repository; + +import com.baeldung.demo.model.Foo; + +public interface FooRepository { + + void save(Foo foo); + + Foo get(Integer id); +} diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java similarity index 88% rename from spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java index 607bae83ba..a304373d6c 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java @@ -1,8 +1,8 @@ -package org.baeldung.session.exception.repository; +package com.baeldung.session.exception.repository; import javax.persistence.EntityManagerFactory; -import org.baeldung.demo.model.Foo; +import com.baeldung.demo.model.Foo; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java similarity index 96% rename from spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java index 7cce34a06c..44ec9e25ab 100644 --- a/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java @@ -1,14 +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); - } -} +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-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java similarity index 95% rename from spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java index e85b9395d3..545599ce25 100644 --- a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java @@ -1,14 +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."); - } -} +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-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java similarity index 96% rename from spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java index e85d12e791..b586c1430a 100644 --- a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java @@ -1,14 +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."); - } - -} +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-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java similarity index 95% rename from spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java index bed1d50ee7..25a56e2859 100644 --- a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java @@ -1,8 +1,8 @@ -package com.baeldung.shutdownhooks.beans; - -public class Bean3 { - - public void destroy() { - System.out.println("Shutdown triggered using bean destroy method."); - } -} +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-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java similarity index 96% rename from spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java index 07d729cb83..03ad5524b6 100644 --- a/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java @@ -1,18 +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 - } - -} +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-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java similarity index 96% rename from spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java index 2d0712e19b..7d487dfc21 100644 --- a/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java @@ -1,25 +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; - } -} +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/startup/AppStartupRunner.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java similarity index 95% rename from spring-boot/src/main/java/org/baeldung/startup/AppStartupRunner.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java index d491bdb42c..0495473704 100644 --- a/spring-boot/src/main/java/org/baeldung/startup/AppStartupRunner.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-boot/src/main/java/org/baeldung/startup/CommandLineAppStartupRunner.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java similarity index 94% rename from spring-boot/src/main/java/org/baeldung/startup/CommandLineAppStartupRunner.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java index 6a7be59c21..48c5225cf1 100644 --- a/spring-boot/src/main/java/org/baeldung/startup/CommandLineAppStartupRunner.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-boot/src/main/java/com/baeldung/toggle/Employee.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/Employee.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/toggle/Employee.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/Employee.java diff --git a/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java diff --git a/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java diff --git a/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java diff --git a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java diff --git a/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java diff --git a/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java diff --git a/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java diff --git a/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java diff --git a/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java diff --git a/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java diff --git a/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties b/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties new file mode 100644 index 0000000000..270e86d443 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties @@ -0,0 +1,4 @@ +#server +server.port=9000 +server.servlet-path=/ +server.context-path=/ \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/application.properties b/spring-boot-modules/spring-boot/src/main/resources/application.properties new file mode 100644 index 0000000000..44649fc1c0 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/resources/application.properties @@ -0,0 +1,36 @@ +server.port=9090 +server.servlet.contextPath=/springbootapp +management.server.port=8081 +management.server.address=127.0.0.1 +#debug=true +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto = update + +management.endpoints.jmx.domain=Spring Sample Application +spring.jmx.unique-names=true + +management.endpoints.web.exposure.include=* +management.endpoint.shutdown.enabled=true + +##jolokia.config.debug=true +##endpoints.jolokia.enabled=true +##endpoints.jolokia.path=jolokia + +spring.jmx.enabled=true + +## for pretty printing of json when endpoints accessed over HTTP +http.mappers.jsonPrettyPrint=true + +## Configuring info endpoint +info.app.name=Spring Sample Application +info.app.description=This is my first spring boot application G1 +info.app.version=1.0.0 +info.java-vendor = ${java.specification.vendor} + +logging.level.org.springframework=INFO + +#Servlet Configuration +servlet.name=dispatcherExample +servlet.mapping=/dispatcherExampleURL + +contactInfoType=email \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/build.properties b/spring-boot-modules/spring-boot/src/main/resources/build.properties new file mode 100644 index 0000000000..1612b8086d --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/resources/build.properties @@ -0,0 +1,2 @@ +application-description=@project.description@ +application-version=@project.version@ \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/build.yml b/spring-boot-modules/spring-boot/src/main/resources/build.yml new file mode 100644 index 0000000000..528d2e3440 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/resources/build.yml @@ -0,0 +1,2 @@ +application-description: ^project.description^ +application-version: ^project.version^ \ No newline at end of file diff --git a/spring-boot/src/main/resources/custom.properties b/spring-boot-modules/spring-boot/src/main/resources/custom.properties similarity index 100% rename from spring-boot/src/main/resources/custom.properties rename to spring-boot-modules/spring-boot/src/main/resources/custom.properties diff --git a/spring-boot/src/main/resources/data-expressions.sql b/spring-boot-modules/spring-boot/src/main/resources/data-expressions.sql similarity index 100% rename from spring-boot/src/main/resources/data-expressions.sql rename to spring-boot-modules/spring-boot/src/main/resources/data-expressions.sql diff --git a/spring-boot/src/main/resources/data.sql b/spring-boot-modules/spring-boot/src/main/resources/data.sql similarity index 100% rename from spring-boot/src/main/resources/data.sql rename to spring-boot-modules/spring-boot/src/main/resources/data.sql diff --git a/spring-boot/src/main/resources/demo.properties b/spring-boot-modules/spring-boot/src/main/resources/demo.properties similarity index 100% rename from spring-boot/src/main/resources/demo.properties rename to spring-boot-modules/spring-boot/src/main/resources/demo.properties diff --git a/spring-boot/src/main/resources/graphql/blog.graphqls b/spring-boot-modules/spring-boot/src/main/resources/graphql/blog.graphqls similarity index 100% rename from spring-boot/src/main/resources/graphql/blog.graphqls rename to spring-boot-modules/spring-boot/src/main/resources/graphql/blog.graphqls diff --git a/spring-boot-client/src/main/resources/logback.xml b/spring-boot-modules/spring-boot/src/main/resources/logback.xml similarity index 100% rename from spring-boot-client/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot/src/main/resources/logback.xml diff --git a/spring-boot/src/main/resources/messages.properties b/spring-boot-modules/spring-boot/src/main/resources/messages.properties similarity index 100% rename from spring-boot/src/main/resources/messages.properties rename to spring-boot-modules/spring-boot/src/main/resources/messages.properties diff --git a/spring-boot/src/main/resources/messages_fr.properties b/spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties similarity index 100% rename from spring-boot/src/main/resources/messages_fr.properties rename to spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties diff --git a/spring-boot/src/main/resources/persistence-generic-entity.properties b/spring-boot-modules/spring-boot/src/main/resources/persistence-generic-entity.properties similarity index 100% rename from spring-boot/src/main/resources/persistence-generic-entity.properties rename to spring-boot-modules/spring-boot/src/main/resources/persistence-generic-entity.properties diff --git a/spring-boot-modules/spring-boot/src/main/resources/public/error/404.html b/spring-boot-modules/spring-boot/src/main/resources/public/error/404.html new file mode 100644 index 0000000000..df83ce219b --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/resources/public/error/404.html @@ -0,0 +1,8 @@ + + + RESOURCE NOT FOUND + + +

404 RESOURCE NOT FOUND

+ + \ No newline at end of file diff --git a/spring-boot/src/main/resources/schema-expressions.sql b/spring-boot-modules/spring-boot/src/main/resources/schema-expressions.sql similarity index 100% rename from spring-boot/src/main/resources/schema-expressions.sql rename to spring-boot-modules/spring-boot/src/main/resources/schema-expressions.sql diff --git a/spring-boot/src/main/resources/schema.sql b/spring-boot-modules/spring-boot/src/main/resources/schema.sql similarity index 100% rename from spring-boot/src/main/resources/schema.sql rename to spring-boot-modules/spring-boot/src/main/resources/schema.sql diff --git a/spring-boot/src/main/resources/shutdown/shutdown.bat b/spring-boot-modules/spring-boot/src/main/resources/shutdown/shutdown.bat similarity index 100% rename from spring-boot/src/main/resources/shutdown/shutdown.bat rename to spring-boot-modules/spring-boot/src/main/resources/shutdown/shutdown.bat diff --git a/spring-boot/src/main/resources/static/internationalization.js b/spring-boot-modules/spring-boot/src/main/resources/static/internationalization.js similarity index 100% rename from spring-boot/src/main/resources/static/internationalization.js rename to spring-boot-modules/spring-boot/src/main/resources/static/internationalization.js diff --git a/spring-boot/src/main/resources/templates/customer.html b/spring-boot-modules/spring-boot/src/main/resources/templates/customer.html similarity index 100% rename from spring-boot/src/main/resources/templates/customer.html rename to spring-boot-modules/spring-boot/src/main/resources/templates/customer.html diff --git a/spring-boot/src/main/resources/templates/customers.html b/spring-boot-modules/spring-boot/src/main/resources/templates/customers.html similarity index 100% rename from spring-boot/src/main/resources/templates/customers.html rename to spring-boot-modules/spring-boot/src/main/resources/templates/customers.html diff --git a/spring-boot/src/main/resources/templates/displayallbeans.html b/spring-boot-modules/spring-boot/src/main/resources/templates/displayallbeans.html similarity index 100% rename from spring-boot/src/main/resources/templates/displayallbeans.html rename to spring-boot-modules/spring-boot/src/main/resources/templates/displayallbeans.html diff --git a/spring-boot/src/main/resources/templates/error.html b/spring-boot-modules/spring-boot/src/main/resources/templates/error.html similarity index 100% rename from spring-boot/src/main/resources/templates/error.html rename to spring-boot-modules/spring-boot/src/main/resources/templates/error.html diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/error/404.html b/spring-boot-modules/spring-boot/src/main/resources/templates/error/404.html new file mode 100644 index 0000000000..df83ce219b --- /dev/null +++ b/spring-boot-modules/spring-boot/src/main/resources/templates/error/404.html @@ -0,0 +1,8 @@ + + + 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-modules/spring-boot/src/main/resources/templates/external.html similarity index 100% rename from spring-boot/src/main/resources/templates/external.html rename to spring-boot-modules/spring-boot/src/main/resources/templates/external.html diff --git a/spring-boot/src/main/resources/templates/index.html b/spring-boot-modules/spring-boot/src/main/resources/templates/index.html similarity index 100% rename from spring-boot/src/main/resources/templates/index.html rename to spring-boot-modules/spring-boot/src/main/resources/templates/index.html diff --git a/spring-boot/src/main/resources/templates/international.html b/spring-boot-modules/spring-boot/src/main/resources/templates/international.html similarity index 100% rename from spring-boot/src/main/resources/templates/international.html rename to spring-boot-modules/spring-boot/src/main/resources/templates/international.html diff --git a/spring-boot/src/main/resources/templates/layout.html b/spring-boot-modules/spring-boot/src/main/resources/templates/layout.html similarity index 100% rename from spring-boot/src/main/resources/templates/layout.html rename to spring-boot-modules/spring-boot/src/main/resources/templates/layout.html diff --git a/spring-boot/src/main/resources/templates/other.html b/spring-boot-modules/spring-boot/src/main/resources/templates/other.html similarity index 100% rename from spring-boot/src/main/resources/templates/other.html rename to spring-boot-modules/spring-boot/src/main/resources/templates/other.html diff --git a/spring-boot/src/main/resources/templates/utils.html b/spring-boot-modules/spring-boot/src/main/resources/templates/utils.html similarity index 100% rename from spring-boot/src/main/resources/templates/utils.html rename to spring-boot-modules/spring-boot/src/main/resources/templates/utils.html diff --git a/spring-boot/src/main/webapp/WEB-INF/context.xml b/spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/context.xml similarity index 100% rename from spring-boot/src/main/webapp/WEB-INF/context.xml rename to spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/context.xml diff --git a/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml b/spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml similarity index 100% rename from spring-boot/src/main/webapp/WEB-INF/dispatcher.xml rename to spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml diff --git a/spring-boot/src/main/webapp/WEB-INF/web.xml b/spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-boot/src/main/webapp/WEB-INF/web.xml rename to spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/web.xml diff --git a/spring-boot/src/main/webapp/annotationservlet.jsp b/spring-boot-modules/spring-boot/src/main/webapp/annotationservlet.jsp similarity index 100% rename from spring-boot/src/main/webapp/annotationservlet.jsp rename to spring-boot-modules/spring-boot/src/main/webapp/annotationservlet.jsp diff --git a/spring-boot/src/main/webapp/index.jsp b/spring-boot-modules/spring-boot/src/main/webapp/index.jsp similarity index 100% rename from spring-boot/src/main/webapp/index.jsp rename to spring-boot-modules/spring-boot/src/main/webapp/index.jsp diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java diff --git a/spring-boot/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java similarity index 88% rename from spring-boot/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java index 07d9b0807e..21fcaf922c 100644 --- a/spring-boot/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java @@ -1,70 +1,71 @@ -package com.baeldung.beanvalidation.application; - -import com.baeldung.beanvalidation.application.controllers.UserController; -import com.baeldung.beanvalidation.application.repositories.UserRepository; - -import java.nio.charset.Charset; -import static org.assertj.core.api.Assertions.assertThat; -import org.hamcrest.core.Is; -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.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -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) -@WebMvcTest -@AutoConfigureMockMvc -public class UserControllerIntegrationTest { - - @MockBean - private UserRepository userRepository; - - @Autowired - UserController userController; - - @Autowired - private MockMvc mockMvc; - - @Test - public void whenUserControllerInjected_thenNotNull() throws Exception { - assertThat(userController).isNotNull(); - } - - @Test - public void whenGetRequestToUsers_thenCorrectResponse() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/users") - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8)); - - } - - @Test - public void whenPostRequestToUsersAndValidUser_thenCorrectResponse() throws Exception { - MediaType textPlainUtf8 = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8")); - String user = "{\"name\": \"bob\", \"email\" : \"bob@domain.com\"}"; - mockMvc.perform(MockMvcRequestBuilders.post("/users") - .content(user) - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType(textPlainUtf8)); - } - - @Test - public void whenPostRequestToUsersAndInValidUser_thenCorrectReponse() throws Exception { - String user = "{\"name\": \"\", \"email\" : \"bob@domain.com\"}"; - mockMvc.perform(MockMvcRequestBuilders.post("/users") - .content(user) - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(MockMvcResultMatchers.status().isBadRequest()) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Is.is("Name is mandatory"))) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8)); - } -} +package com.baeldung.beanvalidation.application; + +import com.baeldung.beanvalidation.application.controllers.UserController; +import com.baeldung.beanvalidation.application.repositories.UserRepository; +import org.hamcrest.core.Is; +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.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +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; + +import java.nio.charset.Charset; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@WebMvcTest +@AutoConfigureMockMvc +public class UserControllerIntegrationTest { + + @MockBean + private UserRepository userRepository; + + @Autowired + UserController userController; + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenUserControllerInjected_thenNotNull() throws Exception { + assertThat(userController).isNotNull(); + } + + @Test + public void whenGetRequestToUsers_thenCorrectResponse() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/users") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)); + + } + + @Test + public void whenPostRequestToUsersAndValidUser_thenCorrectResponse() throws Exception { + MediaType textPlainUtf8 = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8")); + String user = "{\"name\": \"bob\", \"email\" : \"bob@domain.com\"}"; + mockMvc.perform(MockMvcRequestBuilders.post("/users") + .content(user) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType(textPlainUtf8)); + } + + @Test + public void whenPostRequestToUsersAndInValidUser_thenCorrectReponse() throws Exception { + String user = "{\"name\": \"\", \"email\" : \"bob@domain.com\"}"; + mockMvc.perform(MockMvcRequestBuilders.post("/users") + .content(user) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isBadRequest()) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Is.is("Name is mandatory"))) + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)); + } +} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..462291e0ac --- /dev/null +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung.boot; + +import com.baeldung.session.exception.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +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 = Application.class) +@TestPropertySource("classpath:exception.properties") +public class ApplicationIntegrationTest { + @Test + public void contextLoads() { + } +} diff --git a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java similarity index 87% rename from spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java index 0541da3199..aaf4f1f780 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.boot; +package com.baeldung.boot; -import org.baeldung.demo.DemoApplication; +import com.baeldung.demo.DemoApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java new file mode 100644 index 0000000000..1772739d20 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.boot.repository; + +import com.baeldung.boot.DemoApplicationIntegrationTest; +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.repository.FooRepository; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + +@Transactional +public class FooRepositoryIntegrationTest extends DemoApplicationIntegrationTest { + @Autowired + private FooRepository fooRepository; + + @Before + public void setUp() { + fooRepository.save(new Foo("Foo")); + fooRepository.save(new Foo("Bar")); + } + + @Test + public void testFindByName() { + Foo foo = fooRepository.findByName("Bar"); + + assertThat(foo, notNullValue()); + assertThat(foo.getId(), notNullValue()); + assertThat(foo.getName(), is("Bar")); + } + +} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java new file mode 100644 index 0000000000..2fe072bb67 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java @@ -0,0 +1,29 @@ +package com.baeldung.boot.repository; + +import com.baeldung.boot.DemoApplicationIntegrationTest; +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.repository.FooRepository; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; + +@Transactional +public class HibernateSessionIntegrationTest extends DemoApplicationIntegrationTest { + @Autowired + private FooRepository fooRepository; + + @Test + public void whenSavingWithCurrentSession_thenThrowNoException() { + fooRepository.save(new Foo("Exception Solved")); + + Foo foo = fooRepository.findByName("Exception Solved"); + + assertThat(foo, notNullValue()); + assertThat(foo.getId(), notNullValue()); + assertThat(foo.getName(), is("Exception Solved")); + } +} diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java similarity index 78% rename from spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java index 5c8d10223b..2e3326e6b1 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.repository; +package com.baeldung.boot.repository; -import org.baeldung.boot.ApplicationIntegrationTest; -import org.baeldung.demo.model.Foo; -import org.baeldung.session.exception.repository.FooRepository; +import com.baeldung.boot.ApplicationIntegrationTest; +import com.baeldung.demo.model.Foo; +import com.baeldung.session.exception.repository.FooRepository; import org.hibernate.HibernateException; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java new file mode 100644 index 0000000000..cb056fe56d --- /dev/null +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.buildproperties; + +import static org.junit.Assert.assertThat; + +import org.hamcrest.Matchers; +import org.junit.jupiter.api.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) +class BuildInfoServiceIntegrationTest { + + @Autowired + private BuildInfoService service; + + @Test + void whenGetApplicationDescription_thenSuccess() { + assertThat(service.getApplicationDescription(), Matchers.is("This is simple boot application for Spring boot actuator test")); + assertThat(service.getApplicationVersion(), Matchers.is("0.0.1-SNAPSHOT")); + } +} diff --git a/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java similarity index 94% rename from spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java index bd1ae2c8fa..4619964783 100644 --- a/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java @@ -1,9 +1,9 @@ -package org.baeldung.converter; +package com.baeldung.converter; import com.baeldung.toggle.Employee; -import org.baeldung.boot.Application; -import org.baeldung.boot.domain.Modes; +import com.baeldung.boot.Application; +import com.baeldung.boot.domain.Modes; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java similarity index 94% rename from spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java index 2afda7565a..52dc542ebf 100644 --- a/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.converter.controller; +package com.baeldung.converter.controller; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,7 +14,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.boot.Application; +import com.baeldung.boot.Application; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = Application.class) diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java similarity index 93% rename from spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java index 2d70583a54..962abf0fa3 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java @@ -1,8 +1,5 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; -import org.baeldung.demo.boottest.Employee; -import org.baeldung.demo.boottest.EmployeeRestController; -import org.baeldung.demo.boottest.EmployeeService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java similarity index 94% rename from spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java index 3042f95a46..164887886b 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java @@ -1,7 +1,7 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; -import org.baeldung.demo.boottest.Employee; -import org.baeldung.demo.boottest.EmployeeRepository; +import com.baeldung.demo.boottest.Employee; +import com.baeldung.demo.boottest.EmployeeRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java similarity index 97% rename from spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java index a4b35889d6..327e9f9d56 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; @@ -14,7 +14,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.io.IOException; import java.util.List; -import org.baeldung.demo.DemoApplication; +import com.baeldung.demo.DemoApplication; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java similarity index 94% rename from spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java index df28111a57..88f2830a2b 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import static org.assertj.core.api.Assertions.assertThat; @@ -6,6 +6,10 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; +import com.baeldung.demo.boottest.Employee; +import com.baeldung.demo.boottest.EmployeeRepository; +import com.baeldung.demo.boottest.EmployeeService; +import com.baeldung.demo.boottest.EmployeeServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java similarity index 91% rename from spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java index 7e04f47696..3fcd709f7c 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java similarity index 97% rename from spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java index e933920a96..f08a755fc7 100644 --- a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java @@ -1,101 +1,101 @@ -package com.baeldung.displayallbeans; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.BDDAssertions.then; - -import java.net.URI; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.actuate.beans.BeansEndpoint.ContextBeans; -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.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.context.WebApplicationContext; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@TestPropertySource(properties = { "management.port=0", "management.endpoints.web.exposure.include=*" }) -public class DisplayBeanIntegrationTest { - - @LocalServerPort - private int port; - - @Value("${local.management.port}") - private int mgt; - - @Autowired - private TestRestTemplate testRestTemplate; - - @Autowired - private WebApplicationContext context; - - private static final String ACTUATOR_PATH = "/actuator"; - - @Test - public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception { - ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/displayallbeans", String.class); - - then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - } - - @Test - public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception { - ParameterizedTypeReference> responseType = new ParameterizedTypeReference>() { - }; - RequestEntity requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans")) - .accept(MediaType.APPLICATION_JSON) - .build(); - ResponseEntity> entity = this.testRestTemplate.exchange(requestEntity, responseType); - - then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - } - - @Test - public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throws Exception { - RequestEntity requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans")) - .accept(MediaType.APPLICATION_JSON) - .build(); - ResponseEntity entity = this.testRestTemplate.exchange(requestEntity, BeanActuatorResponse.class); - - Collection beanNamesList = entity.getBody() - .getBeans(); - - assertThat(beanNamesList).contains("fooController", "fooService"); - } - - @Test - public void givenWebApplicationContext_whenAccessGetBeanDefinitionNames_thenReturnsBeanNames() throws Exception { - String[] beanNames = context.getBeanDefinitionNames(); - - List beanNamesList = Arrays.asList(beanNames); - assertThat(beanNamesList).contains("fooController", "fooService"); - } - - private static class BeanActuatorResponse { - private Map>>> contexts; - - public Collection getBeans() { - return this.contexts.get("application") - .get("beans") - .keySet(); - } - - public Map>>> getContexts() { - return contexts; - } - } -} +package com.baeldung.displayallbeans; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.BDDAssertions.then; + +import java.net.URI; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.actuate.beans.BeansEndpoint.ContextBeans; +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.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@TestPropertySource(properties = { "management.port=0", "management.endpoints.web.exposure.include=*" }) +public class DisplayBeanIntegrationTest { + + @LocalServerPort + private int port; + + @Value("${local.management.port}") + private int mgt; + + @Autowired + private TestRestTemplate testRestTemplate; + + @Autowired + private WebApplicationContext context; + + private static final String ACTUATOR_PATH = "/actuator"; + + @Test + public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception { + ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/displayallbeans", String.class); + + then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + } + + @Test + public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception { + ParameterizedTypeReference> responseType = new ParameterizedTypeReference>() { + }; + RequestEntity requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans")) + .accept(MediaType.APPLICATION_JSON) + .build(); + ResponseEntity> entity = this.testRestTemplate.exchange(requestEntity, responseType); + + then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + } + + @Test + public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throws Exception { + RequestEntity requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans")) + .accept(MediaType.APPLICATION_JSON) + .build(); + ResponseEntity entity = this.testRestTemplate.exchange(requestEntity, BeanActuatorResponse.class); + + Collection beanNamesList = entity.getBody() + .getBeans(); + + assertThat(beanNamesList).contains("fooController", "fooService"); + } + + @Test + public void givenWebApplicationContext_whenAccessGetBeanDefinitionNames_thenReturnsBeanNames() throws Exception { + String[] beanNames = context.getBeanDefinitionNames(); + + List beanNamesList = Arrays.asList(beanNames); + assertThat(beanNamesList).contains("fooController", "fooService"); + } + + private static class BeanActuatorResponse { + private Map>>> contexts; + + public Collection getBeans() { + return this.contexts.get("application") + .get("beans") + .keySet(); + } + + public Map>>> getContexts() { + return contexts; + } + } +} diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java diff --git a/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppUnitTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppUnitTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppUnitTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppUnitTest.java diff --git a/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerUnitTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerUnitTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerUnitTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerUnitTest.java diff --git a/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java diff --git a/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..a1318949f3 --- /dev/null +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java @@ -0,0 +1,73 @@ +package com.baeldung.repository; + +import com.baeldung.boot.config.H2JpaConfig; +import com.baeldung.model.User; +import com.baeldung.repository.UserRepository; +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.test.context.junit4.SpringRunner; + +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Created by adam. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = H2JpaConfig.class) +public class UserRepositoryIntegrationTest { + + private final String USER_NAME_ADAM = "Adam"; + private final Integer ACTIVE_STATUS = 1; + + @Autowired + private UserRepository userRepository; + + @Test + public void givenEmptyDBWhenFindOneByNameThenReturnEmptyOptional() { + Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); + + assertThat(foundUser.isPresent()).isEqualTo(false); + } + + @Test + public void givenUserInDBWhenFindOneByNameThenReturnOptionalWithUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + userRepository.save(user); + + Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); + + assertThat(foundUser.isPresent()).isEqualTo(true); + + assertThat(foundUser + .get() + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + CompletableFuture userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS); + + assertThat(userByStatus + .get() + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @After + public void cleanUp() { + userRepository.deleteAll(); + } + +} diff --git a/spring-boot/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java diff --git a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java diff --git a/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json b/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json new file mode 100644 index 0000000000..f19bc1febb --- /dev/null +++ b/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json @@ -0,0 +1,169 @@ +{ + "info": { + "_postman_id": "910d9690-f629-4491-bbbd-adb30982a386", + "name": "GraphQL collection", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "mutations", + "item": [ + { + "name": "writePost", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "mutation writePost ($title: String!, $text: String!, $category: String) {\n writePost (title: $title, text: $text, category: $category) {\n id\n title\n text\n category\n }\n}", + "variables": "{\n \"title\": \"\",\n \"text\": \"\",\n \"category\": \"\"\n}" + }, + "options": { + "graphql": {} + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + } + ], + "protocolProfileBehavior": {} + }, + { + "name": "queries", + "item": [ + { + "name": "get recent posts", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "{\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n text\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}", + "variables": "" + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + }, + { + "name": "recentPosts - variables", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "query recentPosts ($count: Int, $offset: Int) {\n recentPosts (count: $count, offset: $offset) {\n id\n title\n text\n category\n }\n}", + "variables": "{\n \"count\": 1,\n \"offset\": 0\n}" + }, + "options": { + "graphql": {} + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + }, + { + "name": "get recent posts - raw", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/graphql", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "query {\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}" + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + } + ], + "protocolProfileBehavior": {} + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "id": "b54f267b-c450-4f2d-8105-2f23bab4c922", + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "id": "00b575be-03d4-4b29-b137-733ead139638", + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ], + "variable": [ + { + "id": "20a274e5-6d51-40d6-81cb-af9eb115b21b", + "key": "url", + "value": "", + "type": "string" + } + ], + "protocolProfileBehavior": {} +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/test/resources/README.md b/spring-boot-modules/spring-boot/src/test/resources/README.md new file mode 100644 index 0000000000..51c95afd9d --- /dev/null +++ b/spring-boot-modules/spring-boot/src/test/resources/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [How to Test GraphQL Using Postman](https://www.baeldung.com/graphql-postman) diff --git a/spring-boot/src/test/resources/application-integrationtest.properties b/spring-boot-modules/spring-boot/src/test/resources/application-integrationtest.properties similarity index 100% rename from spring-boot/src/test/resources/application-integrationtest.properties rename to spring-boot-modules/spring-boot/src/test/resources/application-integrationtest.properties diff --git a/spring-boot/src/test/resources/application.properties b/spring-boot-modules/spring-boot/src/test/resources/application.properties similarity index 100% rename from spring-boot/src/test/resources/application.properties rename to spring-boot-modules/spring-boot/src/test/resources/application.properties diff --git a/spring-boot/src/test/resources/conversion.properties b/spring-boot-modules/spring-boot/src/test/resources/conversion.properties similarity index 100% rename from spring-boot/src/test/resources/conversion.properties rename to spring-boot-modules/spring-boot/src/test/resources/conversion.properties diff --git a/spring-boot/src/test/resources/exception-hibernate.properties b/spring-boot-modules/spring-boot/src/test/resources/exception-hibernate.properties similarity index 100% rename from spring-boot/src/test/resources/exception-hibernate.properties rename to spring-boot-modules/spring-boot/src/test/resources/exception-hibernate.properties diff --git a/spring-boot/src/test/resources/exception.properties b/spring-boot-modules/spring-boot/src/test/resources/exception.properties similarity index 100% rename from spring-boot/src/test/resources/exception.properties rename to spring-boot-modules/spring-boot/src/test/resources/exception.properties diff --git a/spring-boot/src/test/resources/import.sql b/spring-boot-modules/spring-boot/src/test/resources/import.sql similarity index 100% rename from spring-boot/src/test/resources/import.sql rename to spring-boot-modules/spring-boot/src/test/resources/import.sql diff --git a/spring-boot/src/test/resources/org/baeldung/boot/expected.json b/spring-boot-modules/spring-boot/src/test/resources/org/baeldung/boot/expected.json similarity index 100% rename from spring-boot/src/test/resources/org/baeldung/boot/expected.json rename to spring-boot-modules/spring-boot/src/test/resources/org/baeldung/boot/expected.json diff --git a/spring-boot-mvc-2/README.md b/spring-boot-mvc-2/README.md deleted file mode 100644 index 0ff0f1f156..0000000000 --- a/spring-boot-mvc-2/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Spring Boot MVC - -This module contains articles about Spring Web MVC in Spring Boot projects. - -### Relevant Articles: - -- [Functional Controllers in Spring MVC](https://www.baeldung.com/spring-mvc-functional-controllers) -- More articles: [[prev -->]](/spring-boot-mvc) diff --git a/spring-boot-mvc-2/pom.xml b/spring-boot-mvc-2/pom.xml deleted file mode 100644 index e6538c4418..0000000000 --- a/spring-boot-mvc-2/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - 4.0.0 - spring-boot-mvc-2 - spring-boot-mvc-2 - jar - Module For Spring Boot MVC Web Fn - - - org.springframework.boot - spring-boot-starter-parent - 2.2.0.BUILD-SNAPSHOT - - - - - - org.springframework.boot - spring-boot-starter-web - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.springbootmvc.SpringBootMvcFnApplication - JAR - - - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - - \ No newline at end of file diff --git a/spring-boot-mvc-birt/pom.xml b/spring-boot-mvc-birt/pom.xml deleted file mode 100644 index 76760e661b..0000000000 --- a/spring-boot-mvc-birt/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - 4.0.0 - spring-boot-mvc-birt - 0.0.1-SNAPSHOT - spring-boot-mvc-birt - jar - Module For Spring Boot Integration with BIRT - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-logging - - - ch.qos.logback - logback-classic - - - - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.innoventsolutions.birt.runtime - org.eclipse.birt.runtime_4.8.0-20180626 - ${eclipse.birt.runtime.version} - - - - log4j - log4j - ${log4j.version} - - - - org.projectlombok - lombok - ${lombok.version} - provided - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - 2.1.1.RELEASE - com.baeldung.birt.engine.ReportEngineApplication - 1.8 - 1.8 - 4.8.0 - - - diff --git a/spring-boot-mvc/README.md b/spring-boot-mvc/README.md deleted file mode 100644 index a83ea3ee25..0000000000 --- a/spring-boot-mvc/README.md +++ /dev/null @@ -1,21 +0,0 @@ -## Spring Boot MVC - -This module contains articles about Spring Web MVC in Spring Boot projects. - -### Relevant Articles: - -- [Guide to the Favicon in Spring Boot](https://www.baeldung.com/spring-boot-favicon) -- [Custom Validation MessageSource in Spring Boot](https://www.baeldung.com/spring-custom-validation-message-source) -- [Spring Boot Annotations](https://www.baeldung.com/spring-boot-annotations) -- [Spring Scheduling Annotations](https://www.baeldung.com/spring-scheduling-annotations) -- [Spring Web Annotations](https://www.baeldung.com/spring-mvc-annotations) -- [Spring Core Annotations](https://www.baeldung.com/spring-core-annotations) -- [Display RSS Feed with Spring MVC](https://www.baeldung.com/spring-mvc-rss-feed) -- [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) -- [Cache Eviction in Spring Boot](https://www.baeldung.com/spring-boot-evict-cache) -- [Setting Up Swagger 2 with a Spring REST API](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) -- [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) -- [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js) -- [Using Spring ResponseEntity to Manipulate the HTTP Response](https://www.baeldung.com/spring-response-entity) -- [Spring Bean Annotations](https://www.baeldung.com/spring-bean-annotations) -- More articles: [[next -->]](/spring-boot-mvc-2) diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml deleted file mode 100644 index 1c79a423bf..0000000000 --- a/spring-boot-mvc/pom.xml +++ /dev/null @@ -1,155 +0,0 @@ - - - 4.0.0 - spring-boot-mvc - spring-boot-mvc - jar - Module For Spring Boot MVC - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - jcenter-snapshots - jcenter - http://oss.jfrog.org/artifactory/oss-snapshot-local/ - - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.apache.tomcat.embed - tomcat-embed-jasper - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - - - - - org.glassfish - javax.faces - ${javax.faces.version} - - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - com.rometools - rome - ${rome.version} - - - - - org.hibernate.validator - hibernate-validator - - - javax.validation - validation-api - - - org.springframework.boot - spring-boot-starter-validation - - - - - io.springfox - springfox-swagger2 - ${spring.fox.version} - - - io.springfox - springfox-swagger-ui - ${spring.fox.version} - - - - io.springfox - springfox-data-rest - ${spring.fox.version} - - - - io.springfox - springfox-bean-validators - ${spring.fox.version} - - - - org.apache.tomcat.embed - tomcat-embed-jasper - provided - - - - - org.aspectj - aspectjrt - 1.9.1 - - - org.aspectj - aspectjweaver - 1.9.1 - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.springbootmvc.SpringBootMvcApplication - JAR - - - - - - - 3.0.0-SNAPSHOT - - 1.10.0 - 2.3.7 - com.baeldung.springbootmvc.SpringBootMvcApplication - - - diff --git a/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java deleted file mode 100644 index 8759f1bcd6..0000000000 --- a/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.accessparamsjs; - -import java.util.Map; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.ModelAndView; - -/** - * Sample rest controller for the tutorial article - * "Access Spring MVC Model object in JavaScript". - * - * @author Andrew Shcherbakov - * - */ -@RestController -public class Controller { - - /** - * Define two model objects (one integer and one string) and pass them to the view. - * - * @param model - * @return - */ - @RequestMapping("/index") - public ModelAndView thymeleafView(Map model) { - model.put("number", 1234); - model.put("message", "Hello from Spring MVC"); - return new ModelAndView("thymeleaf/index"); - } - -} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java deleted file mode 100644 index f0cc263504..0000000000 --- a/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.nosuchbeandefinitionexception; - -public class BeanB { - -} diff --git a/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 16e0708fc9..0000000000 --- a/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.springbootmvc.SpringBootMvcApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringBootMvcApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-nashorn/pom.xml b/spring-boot-nashorn/pom.xml deleted file mode 100644 index af11f14fdc..0000000000 --- a/spring-boot-nashorn/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - 4.0.0 - com.baeldung.nashorn - spring-boot-nashorn - 1.0 - spring-boot-nashorn - jar - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.apache.tomcat.embed - tomcat-embed-jasper - provided - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - - - - - - \ No newline at end of file diff --git a/spring-boot-parent/pom.xml b/spring-boot-parent/pom.xml deleted file mode 100644 index 7ce5bdc428..0000000000 --- a/spring-boot-parent/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - 4.0.0 - spring-boot-parent - 1.0.0-SNAPSHOT - spring-boot-parent - pom - spring-boot-parent - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. - - - - spring-boot-with-starter-parent - spring-boot-with-custom-parent - - - diff --git a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml deleted file mode 100644 index 8a55f252d6..0000000000 --- a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - 4.0.0 - spring-boot-with-custom-parent - 1.0.0-SNAPSHOT - spring-boot-with-custom-parent - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - - - 1.8 - - - diff --git a/spring-boot-parent/spring-boot-with-starter-parent/pom.xml b/spring-boot-parent/spring-boot-with-starter-parent/pom.xml deleted file mode 100644 index 9ea26e49fe..0000000000 --- a/spring-boot-parent/spring-boot-with-starter-parent/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-boot-with-starter-parent - 1.0.0-SNAPSHOT - spring-boot-with-starter-parent - - - org.springframework.boot - spring-boot-starter-parent - 2.1.5.RELEASE - - - - - - - org.springframework.boot - spring-boot-starter-data-jpa - 2.1.1.RELEASE - - - - - - - org.springframework.boot - spring-boot-starter-web - - - junit - junit - - - - - 1.8 - 4.11 - - - diff --git a/spring-boot-performance/README.md b/spring-boot-performance/README.md deleted file mode 100644 index f6a11720de..0000000000 --- a/spring-boot-performance/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Spring Boot Performance - -This module contains articles about Spring Boot performance. - -### Relevant Articles - -- [Lazy Initialization in Spring Boot 2](https://www.baeldung.com/spring-boot-lazy-initialization) diff --git a/spring-boot-performance/pom.xml b/spring-boot-performance/pom.xml deleted file mode 100644 index 7bf3885618..0000000000 --- a/spring-boot-performance/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - 4.0.0 - spring-boot-performance - spring-boot-performance - war - This is a simple Spring Boot application taking advantage of the latest Spring Boot improvements/features. Current version: 2.2 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter - - - - - spring-boot-performance - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-war-plugin - - - - - - - com.baeldung.lazyinitialization.Application - - diff --git a/spring-boot-properties/README.md b/spring-boot-properties/README.md deleted file mode 100644 index daf7c55ab3..0000000000 --- a/spring-boot-properties/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Spring Boot Properties - -This module contains articles about Properties in Spring Boot. - -### Relevant Articles: -- [Reloading Properties Files in Spring](https://www.baeldung.com/spring-reloading-properties) -- [Guide to @ConfigurationProperties in Spring Boot](https://www.baeldung.com/configuration-properties-in-spring-boot) -- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) -- [Guide to @EnableConfigurationProperties](https://www.baeldung.com/spring-enable-config-properties) -- [Properties with Spring and Spring Boot](https://www.baeldung.com/properties-with-spring) - checkout the `com.baeldung.properties` package for all scenarios of properties injection and usage -- [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation) -- [Spring YAML Configuration](https://www.baeldung.com/spring-yaml) -- [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults) -- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class) diff --git a/spring-boot-properties/pom.xml b/spring-boot-properties/pom.xml deleted file mode 100644 index 705a0eb786..0000000000 --- a/spring-boot-properties/pom.xml +++ /dev/null @@ -1,111 +0,0 @@ - - - 4.0.0 - spring-boot-properties - spring-boot-properties - jar - Spring Boot Properties Module - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - commons-configuration - commons-configuration - ${commons-configuration.version} - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.cloud - spring-cloud-starter - - - com.google.guava - guava - ${guava.version} - - - org.apache.httpcomponents - httpcore - ${httpcore.version} - - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - spring-boot-properties - - - src/main/resources - true - - - - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - json - - - - - - - - - - 1.8 - Greenwich.SR1 - 1.10 - 20.0 - 4.4.11 - - - diff --git a/spring-boot-properties/src/main/resources/application.properties b/spring-boot-properties/src/main/resources/application.properties deleted file mode 100644 index 2e06fad574..0000000000 --- a/spring-boot-properties/src/main/resources/application.properties +++ /dev/null @@ -1,4 +0,0 @@ -management.endpoints.web.exposure.include=refresh -spring.properties.refreshDelay=1000 -spring.config.location=file:extra.properties -spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-properties/src/test/java/com/baeldung/test/IntegrationTestSuite.java b/spring-boot-properties/src/test/java/com/baeldung/test/IntegrationTestSuite.java deleted file mode 100644 index 722c4fd1c4..0000000000 --- a/spring-boot-properties/src/test/java/com/baeldung/test/IntegrationTestSuite.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.test; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -import com.baeldung.properties.basic.ExtendedPropertiesWithJavaIntegrationTest; -import com.baeldung.properties.basic.PropertiesWithMultipleXmlsIntegrationTest; -import com.baeldung.properties.basic.PropertiesWithXmlIntegrationTest; -import com.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest; -import com.baeldung.properties.external.ExternalPropertiesWithMultipleXmlsIntegrationTest; -import com.baeldung.properties.external.ExternalPropertiesWithXmlManualTest; - -@RunWith(Suite.class) -@SuiteClasses({ //@formatter:off - PropertiesWithXmlIntegrationTest.class, - ExternalPropertiesWithJavaIntegrationTest.class, - ExternalPropertiesWithMultipleXmlsIntegrationTest.class, - ExternalPropertiesWithXmlManualTest.class, - ExtendedPropertiesWithJavaIntegrationTest.class, - PropertiesWithMultipleXmlsIntegrationTest.class, -})// @formatter:on -public final class IntegrationTestSuite { - // -} diff --git a/spring-boot-properties/src/test/resources/application.properties b/spring-boot-properties/src/test/resources/application.properties deleted file mode 100644 index 2e06fad574..0000000000 --- a/spring-boot-properties/src/test/resources/application.properties +++ /dev/null @@ -1,4 +0,0 @@ -management.endpoints.web.exposure.include=refresh -spring.properties.refreshDelay=1000 -spring.config.location=file:extra.properties -spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-property-exp/pom.xml b/spring-boot-property-exp/pom.xml deleted file mode 100644 index b16fcd1c22..0000000000 --- a/spring-boot-property-exp/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - spring-boot-property-exp - spring-boot-property-exp - 0.0.1-SNAPSHOT - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - property-exp-default-config - property-exp-custom-config - - - diff --git a/spring-boot-property-exp/property-exp-custom-config/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml deleted file mode 100644 index f9c3d6ef62..0000000000 --- a/spring-boot-property-exp/property-exp-custom-config/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - 4.0.0 - property-exp-custom-config - 0.0.1-SNAPSHOT - property-exp-custom-config - jar - - - com.baeldung - spring-boot-property-exp - 0.0.1-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot.version} - test - - - - - - - ${basedir}/src/main/resources - true - - **/application*.yml - **/application*.yaml - **/application*.properties - - - - ${basedir}/src/main/resources - true - - **/application*.yml - **/application*.yaml - **/application*.properties - - - - - - org.apache.maven.plugins - maven-resources-plugin - 2.7 - - - @ - - true - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp - - - - - - - 1.5.10.RELEASE - Custom Property Value - - - diff --git a/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 874c4f582f..0000000000 --- a/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml deleted file mode 100644 index 9cb1de33f6..0000000000 --- a/spring-boot-property-exp/property-exp-default-config/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - 4.0.0 - property-exp-default-config - 0.0.1-SNAPSHOT - property-exp-default-config - jar - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - - - - Custom Property Value - - - diff --git a/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 874c4f582f..0000000000 --- a/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md index 3909a99c65..861181c53e 100644 --- a/spring-boot-rest/README.md +++ b/spring-boot-rest/README.md @@ -4,13 +4,7 @@ This module contains articles about Spring Boot RESTful APIs. ### Relevant Articles -- [HATEOAS for a Spring REST Service](https://www.baeldung.com/rest-api-discoverability-with-spring) - [Versioning a REST API](https://www.baeldung.com/rest-versioning) -- [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) -- [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) -- [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) -- [Spring Boot Consuming and Producing JSON](https://www.baeldung.com/spring-boot-json) -- [Error Handling for REST with Spring](https://www.baeldung.com/exception-handling-for-rest-with-spring) ### E-book @@ -26,3 +20,7 @@ These articles are part of the Spring REST E-book: 8. [An Intro to Spring HATEOAS](https://www.baeldung.com/spring-hateoas-tutorial) 9. [REST Pagination in Spring](https://www.baeldung.com/rest-api-pagination-in-spring) 10. [Test a REST API with Java](https://www.baeldung.com/integration-testing-a-rest-api) +11. [HATEOAS for a Spring REST Service](https://www.baeldung.com/rest-api-discoverability-with-spring) + +NOTE: +Since this is a module tied to an e-book, it should not be moved or used to store the code for any further article. diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml index 3787e21493..a8500d50f2 100644 --- a/spring-boot-rest/pom.xml +++ b/spring-boot-rest/pom.xml @@ -45,6 +45,11 @@ spring-boot-starter-data-jpa + + org.springframework.boot + spring-boot-starter-data-rest + + org.springframework.boot @@ -74,6 +79,11 @@ modelmapper ${modelmapper.version} + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + diff --git a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/model/Post.java b/spring-boot-rest/src/main/java/com/baeldung/modelmapper/model/Post.java deleted file mode 100644 index be65ce34a2..0000000000 --- a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/model/Post.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.baeldung.modelmapper.model; - -import java.util.Date; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Post { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String title; - - private String url; - - private String date; - - private String redditID; - - private Date submissionDate; - - private boolean sent; - - private String userName; - - public Post() { - - } - - public boolean isSent() { - return sent; - } - - public void setSent(boolean sent) { - this.sent = sent; - } - - public String getRedditID() { - return redditID; - } - - public void setRedditID(String redditID) { - this.redditID = redditID; - } - - 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 getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getDate() { - return date; - } - - public void setDate(String date) { - this.date = date; - } - - public Date getSubmissionDate() { - return submissionDate; - } - - public void setSubmissionDate(Date submissionDate) { - this.submissionDate = submissionDate; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } -} diff --git a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/model/User.java b/spring-boot-rest/src/main/java/com/baeldung/modelmapper/model/User.java deleted file mode 100644 index a458b26f4a..0000000000 --- a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/model/User.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.modelmapper.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToOne; - -@Entity -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String name; - - @OneToOne - Preference preference; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Preference getPreference() { - return preference; - } - - public void setPreference(Preference preference) { - this.preference = preference; - } -} diff --git a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/IPostService.java b/spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/IPostService.java deleted file mode 100644 index 0182a0da41..0000000000 --- a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/IPostService.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.modelmapper.service; - -import java.util.List; - -import com.baeldung.modelmapper.model.Post; - -public interface IPostService { - - List getPostsList(int page, int size, String sortDir, String sort); - - void updatePost(Post post); - - Post createPost(Post post); - - Post getPostById(Long id); - -} diff --git a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/IUserService.java b/spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/IUserService.java deleted file mode 100644 index 79934114c1..0000000000 --- a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/IUserService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.modelmapper.service; - -import com.baeldung.modelmapper.model.User; - -public interface IUserService { - - User getCurrentUser(); - -} diff --git a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/UserService.java b/spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/UserService.java deleted file mode 100644 index e445f836a4..0000000000 --- a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/UserService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.modelmapper.service; - -import org.springframework.stereotype.Service; - -import com.baeldung.modelmapper.model.Preference; -import com.baeldung.modelmapper.model.User; - -@Service -public class UserService implements IUserService { - - @Override - public User getCurrentUser() { - - Preference preference = new Preference(); - preference.setId(1L); - preference.setTimezone("Asia/Calcutta"); - - User user = new User(); - user.setId(1L); - user.setName("Micheal"); - user.setPreference(preference); - - return user; - } -} \ No newline at end of file diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/config/CustomH2Dialect.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/config/CustomH2Dialect.java new file mode 100644 index 0000000000..0108f92b2c --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/config/CustomH2Dialect.java @@ -0,0 +1,26 @@ +package com.baeldung.persistence.config; + +import org.hibernate.dialect.H2Dialect; + +/** + * Since H2 1.4.200. the behavior of the drop table commands has changed. + * Tables are not dropped in a correct order. + * Until this is properly fixed directly in Hibernate project, + * let's use this custom H2Dialect class to solve this issue. + * + * @see https://hibernate.atlassian.net/browse/HHH-13711 + * @see https://github.com/hibernate/hibernate-orm/pull/3093 + */ +public class CustomH2Dialect extends H2Dialect { + + @Override + public boolean dropConstraints() { + return true; + } + + @Override + public boolean supportsIfExistsAfterAlterTable() { + return true; + } + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/model/Customer.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/model/Customer.java index 10da2e10f0..06b2485c7b 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/model/Customer.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/model/Customer.java @@ -1,14 +1,13 @@ package com.baeldung.persistence.model; -import java.util.Map; - -import org.springframework.hateoas.ResourceSupport; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; +import org.springframework.hateoas.RepresentationModel; + +import java.util.Map; @JsonInclude(Include.NON_NULL) -public class Customer extends ResourceSupport { +public class Customer extends RepresentationModel { private String customerId; private String customerName; private String companyName; diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/model/Order.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/model/Order.java index 7aea9bce5c..b5e1a2cee2 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/model/Order.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/model/Order.java @@ -1,8 +1,8 @@ package com.baeldung.persistence.model; -import org.springframework.hateoas.ResourceSupport; +import org.springframework.hateoas.RepresentationModel; -public class Order extends ResourceSupport { +public class Order extends RepresentationModel { private String orderId; private double price; private int quantity; diff --git a/spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/ExamplePostController.java b/spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/ExamplePostController.java index 90211b11a3..ac1d28bb72 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/ExamplePostController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/ExamplePostController.java @@ -1,11 +1,11 @@ package com.baeldung.requestresponsebody; import com.baeldung.services.ExampleService; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; 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.PostMapping; @@ -34,4 +34,18 @@ public class ExamplePostController { log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername()); return new ResponseTransfer("Thanks For Posting!!!"); } + + @PostMapping(value = "/content", produces = MediaType.APPLICATION_JSON_VALUE) + @ResponseBody + public ResponseTransfer postResponseJsonContent(@RequestBody LoginForm loginForm) { + log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername()); + return new ResponseTransfer("JSON Content!"); + } + + @PostMapping(value = "/content", produces = MediaType.APPLICATION_XML_VALUE) + @ResponseBody + public ResponseTransfer postResponseXmlContent(@RequestBody LoginForm loginForm) { + log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername()); + return new ResponseTransfer("XML Content!"); + } } \ No newline at end of file diff --git a/spring-boot-rest/src/main/java/com/baeldung/spring/PersistenceConfig.java b/spring-boot-rest/src/main/java/com/baeldung/spring/PersistenceConfig.java index 2e967751ad..8887510eca 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/spring/PersistenceConfig.java +++ b/spring-boot-rest/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -24,8 +24,8 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) -@ComponentScan(basePackages = { "com.baeldung.persistence", "com.baeldung.modelmapper" }) -@EnableJpaRepositories(basePackages = {"com.baeldung.persistence.dao", "com.baeldung.modelmapper.repository"}) +@ComponentScan(basePackages = { "com.baeldung.persistence", "com.baeldung.springpagination" }) +@EnableJpaRepositories(basePackages = {"com.baeldung.persistence.dao", "com.baeldung.springpagination.repository"}) public class PersistenceConfig { @Autowired @@ -39,7 +39,7 @@ public class PersistenceConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.persistence.model", "com.baeldung.modelmapper.model" }); + em.setPackagesToScan(new String[] { "com.baeldung.persistence.model", "com.baeldung.springpagination.model" }); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); // vendorAdapter.set diff --git a/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java b/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java index ab16b61e1d..13a9933fa6 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java +++ b/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java @@ -14,8 +14,6 @@ import org.springframework.web.filter.ShallowEtagHeaderFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration -// If we want to enable xml configurations for message-converter: -// @ImportResource("classpath:WEB-INF/api-servlet.xml") public class WebConfig implements WebMvcConfigurer { // @Override diff --git a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/controller/PostRestController.java similarity index 91% rename from spring-boot-rest/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java rename to spring-boot-rest/src/main/java/com/baeldung/springpagination/controller/PostRestController.java index e2def62466..c52960b365 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/controller/PostRestController.java @@ -1,9 +1,9 @@ -package com.baeldung.modelmapper.controller; +package com.baeldung.springpagination.controller; -import com.baeldung.modelmapper.dto.PostDto; -import com.baeldung.modelmapper.model.Post; -import com.baeldung.modelmapper.service.IPostService; -import com.baeldung.modelmapper.service.IUserService; +import com.baeldung.springpagination.dto.PostDto; +import com.baeldung.springpagination.model.Post; +import com.baeldung.springpagination.service.IPostService; +import com.baeldung.springpagination.service.IUserService; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; diff --git a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/dto/PostDto.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/dto/PostDto.java similarity index 96% rename from spring-boot-rest/src/main/java/com/baeldung/modelmapper/dto/PostDto.java rename to spring-boot-rest/src/main/java/com/baeldung/springpagination/dto/PostDto.java index 6fe2b23888..81cec5ed8c 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/dto/PostDto.java +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/dto/PostDto.java @@ -1,4 +1,4 @@ -package com.baeldung.modelmapper.dto; +package com.baeldung.springpagination.dto; import java.text.ParseException; import java.text.SimpleDateFormat; diff --git a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/dto/UserDto.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/dto/UserDto.java similarity index 80% rename from spring-boot-rest/src/main/java/com/baeldung/modelmapper/dto/UserDto.java rename to spring-boot-rest/src/main/java/com/baeldung/springpagination/dto/UserDto.java index 23110ecbaa..2e4f667b30 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/dto/UserDto.java +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/dto/UserDto.java @@ -1,4 +1,4 @@ -package com.baeldung.modelmapper.dto; +package com.baeldung.springpagination.dto; public class UserDto { diff --git a/spring-boot-rest/src/main/java/com/baeldung/springpagination/model/Post.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/model/Post.java new file mode 100644 index 0000000000..88e9ef67bb --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/model/Post.java @@ -0,0 +1,98 @@ +package com.baeldung.springpagination.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Post { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String title; + + private String url; + + private String date; + + private String redditID; + + private Date submissionDate; + + private boolean sent; + + private String userName; + + public Post() { + + } + + public boolean isSent() { + return sent; + } + + public void setSent(boolean sent) { + this.sent = sent; + } + + public String getRedditID() { + return redditID; + } + + public void setRedditID(String redditID) { + this.redditID = redditID; + } + + 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 getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public Date getSubmissionDate() { + return submissionDate; + } + + public void setSubmissionDate(Date submissionDate) { + this.submissionDate = submissionDate; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/model/Preference.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/model/Preference.java similarity index 92% rename from spring-boot-rest/src/main/java/com/baeldung/modelmapper/model/Preference.java rename to spring-boot-rest/src/main/java/com/baeldung/springpagination/model/Preference.java index 0ab5b1eddf..44f8f41aff 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/model/Preference.java +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/model/Preference.java @@ -1,4 +1,4 @@ -package com.baeldung.modelmapper.model; +package com.baeldung.springpagination.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot-rest/src/main/java/com/baeldung/springpagination/model/Subject.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/model/Subject.java new file mode 100644 index 0000000000..80598ae07d --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/model/Subject.java @@ -0,0 +1,37 @@ +package com.baeldung.springpagination.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Subject { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @Column(nullable = false) + private String name; + + public Subject() { + } + + 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; + } +} \ No newline at end of file diff --git a/spring-boot-rest/src/main/java/com/baeldung/springpagination/model/User.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/model/User.java new file mode 100644 index 0000000000..4d33834b28 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/model/User.java @@ -0,0 +1,44 @@ +package com.baeldung.springpagination.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String name; + + @OneToOne + Preference preference; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Preference getPreference() { + return preference; + } + + public void setPreference(Preference preference) { + this.preference = preference; + } +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/repository/PostRepository.java similarity index 82% rename from spring-boot-rest/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java rename to spring-boot-rest/src/main/java/com/baeldung/springpagination/repository/PostRepository.java index fc3f5733c3..acdc01df94 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/repository/PostRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.modelmapper.repository; +package com.baeldung.springpagination.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -7,8 +7,8 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; -import com.baeldung.modelmapper.model.Post; -import com.baeldung.modelmapper.model.User; +import com.baeldung.springpagination.model.Post; +import com.baeldung.springpagination.model.User; public interface PostRepository extends JpaRepository, PagingAndSortingRepository { diff --git a/spring-boot-rest/src/main/java/com/baeldung/springpagination/repository/SubjectRepository.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/repository/SubjectRepository.java new file mode 100644 index 0000000000..03c66f8d72 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/repository/SubjectRepository.java @@ -0,0 +1,16 @@ +package com.baeldung.springpagination.repository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RestResource; + +import com.baeldung.springpagination.model.Subject; + +public interface SubjectRepository extends PagingAndSortingRepository { + + @RestResource(path = "nameContains") + public Page findByNameContaining(@Param("name") String name, Pageable p); + +} \ No newline at end of file diff --git a/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/IPostService.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/IPostService.java new file mode 100644 index 0000000000..d1d9bee2c6 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/IPostService.java @@ -0,0 +1,17 @@ +package com.baeldung.springpagination.service; + +import java.util.List; + +import com.baeldung.springpagination.model.Post; + +public interface IPostService { + + List getPostsList(int page, int size, String sortDir, String sort); + + void updatePost(Post post); + + Post createPost(Post post); + + Post getPostById(Long id); + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/IUserService.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/IUserService.java new file mode 100644 index 0000000000..92dce3ed78 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/IUserService.java @@ -0,0 +1,9 @@ +package com.baeldung.springpagination.service; + +import com.baeldung.springpagination.model.User; + +public interface IUserService { + + User getCurrentUser(); + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/PostService.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/PostService.java similarity index 87% rename from spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/PostService.java rename to spring-boot-rest/src/main/java/com/baeldung/springpagination/service/PostService.java index 5980c30837..bb4869dd33 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/modelmapper/service/PostService.java +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/PostService.java @@ -1,4 +1,4 @@ -package com.baeldung.modelmapper.service; +package com.baeldung.springpagination.service; import java.util.List; @@ -8,8 +8,8 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; -import com.baeldung.modelmapper.model.Post; -import com.baeldung.modelmapper.repository.PostRepository; +import com.baeldung.springpagination.model.Post; +import com.baeldung.springpagination.repository.PostRepository; @Service public class PostService implements IPostService { diff --git a/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/UserService.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/UserService.java new file mode 100644 index 0000000000..0694450f44 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/UserService.java @@ -0,0 +1,25 @@ +package com.baeldung.springpagination.service; + +import org.springframework.stereotype.Service; + +import com.baeldung.springpagination.model.Preference; +import com.baeldung.springpagination.model.User; + +@Service +public class UserService implements IUserService { + + @Override + public User getCurrentUser() { + + Preference preference = new Preference(); + preference.setId(1L); + preference.setTimezone("Asia/Calcutta"); + + User user = new User(); + user.setId(1L); + user.setName("Micheal"); + user.setPreference(preference); + + return user; + } +} \ No newline at end of file diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/CustomerController.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/CustomerController.java index 91aa9f2144..2b7dc1eee1 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/controller/CustomerController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/CustomerController.java @@ -1,13 +1,13 @@ package com.baeldung.web.controller; -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resources; +import org.springframework.hateoas.CollectionModel; import org.springframework.hateoas.config.EnableHypermediaSupport; import org.springframework.hateoas.config.EnableHypermediaSupport.HypermediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -41,7 +41,7 @@ public class CustomerController { } @GetMapping(value = "/{customerId}/orders", produces = { "application/hal+json" }) - public Resources getOrdersForCustomer(@PathVariable final String customerId) { + public CollectionModel getOrdersForCustomer(@PathVariable final String customerId) { final List orders = orderService.getAllOrdersForCustomer(customerId); for (final Order order : orders) { final Link selfLink = linkTo( @@ -50,12 +50,12 @@ public class CustomerController { } Link link = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId)).withSelfRel(); - Resources result = new Resources<>(orders, link); + CollectionModel result = new CollectionModel<>(orders, link); return result; } @GetMapping(produces = { "application/hal+json" }) - public Resources getAllCustomers() { + public CollectionModel getAllCustomers() { final List allCustomers = customerService.allCustomers(); for (final Customer customer : allCustomers) { @@ -72,7 +72,7 @@ public class CustomerController { } Link link = linkTo(CustomerController.class).withSelfRel(); - Resources result = new Resources<>(allCustomers, link); + CollectionModel result = new CollectionModel<>(allCustomers, link); return result; } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java index 8174480078..a09878fb84 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java @@ -4,6 +4,8 @@ import java.util.List; import javax.servlet.http.HttpServletResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.Page; @@ -11,6 +13,7 @@ import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -25,6 +28,8 @@ import org.springframework.web.util.UriComponentsBuilder; import com.baeldung.persistence.model.Foo; import com.baeldung.persistence.service.IFooService; +import com.baeldung.web.exception.CustomException1; +import com.baeldung.web.exception.CustomException2; import com.baeldung.web.exception.MyResourceNotFoundException; import com.baeldung.web.hateoas.event.PaginatedResultsRetrievedEvent; import com.baeldung.web.hateoas.event.ResourceCreatedEvent; @@ -36,6 +41,8 @@ import com.google.common.base.Preconditions; @RequestMapping(value = "/foos") public class FooController { + private static final Logger logger = LoggerFactory.getLogger(FooController.class); + @Autowired private ApplicationEventPublisher eventPublisher; @@ -137,4 +144,10 @@ public class FooController { public void delete(@PathVariable("id") final Long id) { service.deleteById(id); } + + @ExceptionHandler({ CustomException1.class, CustomException2.class }) + public void handleException(final Exception ex) { + final String error = "Application specific error handling"; + logger.error(error, ex); + } } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/error/RestResponseStatusExceptionResolver.java b/spring-boot-rest/src/main/java/com/baeldung/web/error/RestResponseStatusExceptionResolver.java new file mode 100644 index 0000000000..6753ab35cf --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/error/RestResponseStatusExceptionResolver.java @@ -0,0 +1,73 @@ +package com.baeldung.web.error; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; + +@Component +public class RestResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver { + + private static final Logger logger = LoggerFactory.getLogger(RestResponseStatusExceptionResolver.class); + + @Override + protected ModelAndView doResolveException(HttpServletRequest request, + HttpServletResponse response, Object handler, Exception ex) { + try { + if (ex instanceof IllegalArgumentException) { + return handleIllegalArgument( + (IllegalArgumentException) ex, request, response, handler); + } + } catch (Exception handlerException) { + logger.warn("Handling of [{}] resulted in Exception", ex.getClass().getName(), handlerException); + } + return null; + } + + private ModelAndView handleIllegalArgument(IllegalArgumentException ex, + final HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + final String accept = request.getHeader(HttpHeaders.ACCEPT); + + response.sendError(HttpServletResponse.SC_CONFLICT); + response.setHeader("ContentType", accept); + + final ModelAndView modelAndView = new ModelAndView("error"); + modelAndView.addObject("error", prepareErrorResponse(accept)); + return modelAndView; + } + + /** Prepares error object based on the provided accept type. + * @param accept The Accept header present in the request. + * @return The response to return + * @throws JsonProcessingException + */ + private String prepareErrorResponse(String accept) throws JsonProcessingException { + final Map error = new HashMap<>(); + error.put("Error", "Application specific error message"); + + final String response; + if(MediaType.APPLICATION_JSON_VALUE.equals(accept)) { + response = new ObjectMapper().writeValueAsString(error); + } else { + response = new XmlMapper().writeValueAsString(error); + } + + return response; + } + + + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/exception/CustomException1.java b/spring-boot-rest/src/main/java/com/baeldung/web/exception/CustomException1.java new file mode 100644 index 0000000000..ed8d34ae2b --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/exception/CustomException1.java @@ -0,0 +1,7 @@ +package com.baeldung.web.exception; + +public class CustomException1 extends RuntimeException { + + private static final long serialVersionUID = 1L; + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/exception/CustomException2.java b/spring-boot-rest/src/main/java/com/baeldung/web/exception/CustomException2.java new file mode 100644 index 0000000000..39b6c98a82 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/exception/CustomException2.java @@ -0,0 +1,7 @@ +package com.baeldung.web.exception; + +public class CustomException2 extends RuntimeException { + + private static final long serialVersionUID = 1L; + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java b/spring-boot-rest/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java index fd002efc28..59bcfde57a 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java @@ -1,5 +1,9 @@ package com.baeldung.web.exception; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) public final class MyResourceNotFoundException extends RuntimeException { public MyResourceNotFoundException() { diff --git a/spring-boot-rest/src/main/resources/WEB-INF/api-servlet.xml b/spring-boot-rest/src/main/resources/WEB-INF/api-servlet.xml deleted file mode 100644 index 78e38e1448..0000000000 --- a/spring-boot-rest/src/main/resources/WEB-INF/api-servlet.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-boot-rest/src/main/resources/persistence-h2.properties b/spring-boot-rest/src/main/resources/persistence-h2.properties index 839a466533..efbf3f7db7 100644 --- a/spring-boot-rest/src/main/resources/persistence-h2.properties +++ b/spring-boot-rest/src/main/resources/persistence-h2.properties @@ -17,6 +17,6 @@ jdbc.user=sa jdbc.pass= # hibernate.X -hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.dialect=com.baeldung.persistence.config.CustomH2Dialect hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop diff --git a/spring-boot-rest/src/test/java/com/baeldung/springhateoas/CustomerControllerIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/springhateoas/CustomerControllerIntegrationTest.java index b08da6d2cd..644ce5132a 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/springhateoas/CustomerControllerIntegrationTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/springhateoas/CustomerControllerIntegrationTest.java @@ -70,7 +70,7 @@ public class CustomerControllerIntegrationTest { this.mvc.perform(get("/customers/" + DEFAULT_CUSTOMER_ID + "/orders").accept(MediaTypes.HAL_JSON_VALUE)) .andExpect(status().isOk()) - .andExpect(jsonPath("$._embedded.orderList[0]._links.self.href", + .andExpect(jsonPath("$._embedded.orders[0]._links.self.href", is("http://localhost/customers/customer1/order1"))) .andExpect(jsonPath("$._links.self.href", is("http://localhost/customers/customer1/orders"))); } @@ -89,8 +89,8 @@ public class CustomerControllerIntegrationTest { this.mvc.perform(get("/customers/").accept(MediaTypes.HAL_JSON_VALUE)) .andExpect(status().isOk()) .andExpect( - jsonPath("$._embedded.customerList[0]._links.self.href", is("http://localhost/customers/customer1"))) - .andExpect(jsonPath("$._embedded.customerList[0]._links.allOrders.href", + jsonPath("$._embedded.customers[0]._links.self.href", is("http://localhost/customers/customer1"))) + .andExpect(jsonPath("$._embedded.customers[0]._links.allOrders.href", is("http://localhost/customers/customer1/orders"))) .andExpect(jsonPath("$._links.self.href", is("http://localhost/customers"))); } diff --git a/spring-boot-rest/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java b/spring-boot-rest/src/test/java/com/baeldung/springpagination/PostDtoUnitTest.java similarity index 89% rename from spring-boot-rest/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java rename to spring-boot-rest/src/test/java/com/baeldung/springpagination/PostDtoUnitTest.java index 6e94cc4289..948247e166 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/springpagination/PostDtoUnitTest.java @@ -1,12 +1,12 @@ -package com.baeldung.modelmapper; +package com.baeldung.springpagination; import static org.junit.Assert.assertEquals; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import org.junit.Test; import org.modelmapper.ModelMapper; -import com.baeldung.modelmapper.dto.PostDto; -import com.baeldung.modelmapper.model.Post; +import com.baeldung.springpagination.dto.PostDto; +import com.baeldung.springpagination.model.Post; public class PostDtoUnitTest { diff --git a/spring-boot-rest/src/test/java/com/baeldung/test/JacksonMarshaller.java b/spring-boot-rest/src/test/java/com/baeldung/test/JacksonMarshaller.java index 23b5d60b6b..0f89e0a9de 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/test/JacksonMarshaller.java +++ b/spring-boot-rest/src/test/java/com/baeldung/test/JacksonMarshaller.java @@ -60,7 +60,7 @@ public final class JacksonMarshaller implements IMarshaller { List entities = null; try { if (clazz.equals(Foo.class)) { - entities = objectMapper.readValue(resourcesAsString, new TypeReference>() { + entities = objectMapper.readValue(resourcesAsString, new TypeReference>() { // ... }); } else { diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java index bd98523b0a..4d4a274b1a 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java @@ -10,8 +10,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.util.Collections; import org.hamcrest.Matchers; +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.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; @@ -24,6 +26,7 @@ import org.springframework.test.web.servlet.MockMvc; import com.baeldung.persistence.model.Foo; import com.baeldung.persistence.service.IFooService; import com.baeldung.web.controller.FooController; +import com.baeldung.web.exception.CustomException1; import com.baeldung.web.hateoas.event.PaginatedResultsRetrievedEvent; /** @@ -56,5 +59,15 @@ public class FooControllerWebLayerIntegrationTest { .andExpect(status().isOk()) .andExpect(jsonPath("$",Matchers.hasSize(1))); } - + + @Test + public void delete_forException_fromService() throws Exception { + Mockito.when(service.findAll()).thenThrow(new CustomException1()); + this.mockMvc.perform(get("/foos")).andDo(h -> { + final Exception expectedException = h.getResolvedException(); + Assert.assertTrue(expectedException instanceof CustomException1); + + }); + } + } diff --git a/spring-boot-runtime/README.md b/spring-boot-runtime/README.md deleted file mode 100644 index a544faf830..0000000000 --- a/spring-boot-runtime/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Spring Boot Runtime - -This module contains articles about administering a Spring Boot runtime - -### Relevant Articles: - - [Shutdown a Spring Boot Application](https://www.baeldung.com/spring-boot-shutdown) - - [Programmatically Restarting a Spring Boot Application](https://www.baeldung.com/java-restart-spring-boot-app) - - [Logging HTTP Requests with Spring Boot Actuator HTTP Tracing](https://www.baeldung.com/spring-boot-actuator-http) - - [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) - - [Spring Boot Embedded Tomcat Logs](https://www.baeldung.com/spring-boot-embedded-tomcat-logs) - - [How to Change the Default Port in Spring Boot](https://www.baeldung.com/spring-boot-change-port) - - [Project Configuration with Spring](https://www.baeldung.com/project-configuration-with-spring) - - [CORS with Spring](https://www.baeldung.com/spring-cors) - - [Spring – Log Incoming Requests](https://www.baeldung.com/spring-http-logging) \ No newline at end of file diff --git a/spring-boot-runtime/disabling-console-jul/README.md b/spring-boot-runtime/disabling-console-jul/README.md deleted file mode 100644 index 554f051b41..0000000000 --- a/spring-boot-runtime/disabling-console-jul/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) diff --git a/spring-boot-runtime/disabling-console-jul/pom.xml b/spring-boot-runtime/disabling-console-jul/pom.xml deleted file mode 100644 index 2dc1a834b6..0000000000 --- a/spring-boot-runtime/disabling-console-jul/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - disabling-console-jul - disabling-console-jul - - - - org.springframework.boot - spring-boot-starter-parent - 2.1.1.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 - - - - - \ No newline at end of file diff --git a/spring-boot-runtime/disabling-console-log4j2/README.md b/spring-boot-runtime/disabling-console-log4j2/README.md deleted file mode 100644 index 554f051b41..0000000000 --- a/spring-boot-runtime/disabling-console-log4j2/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) diff --git a/spring-boot-runtime/disabling-console-log4j2/pom.xml b/spring-boot-runtime/disabling-console-log4j2/pom.xml deleted file mode 100644 index b743c4bdac..0000000000 --- a/spring-boot-runtime/disabling-console-log4j2/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - 4.0.0 - disabling-console-log4j2 - disabling-console-log4j2 - - - - org.springframework.boot - spring-boot-starter-parent - 2.1.1.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 - - - - - \ No newline at end of file diff --git a/spring-boot-runtime/disabling-console-logback/README.md b/spring-boot-runtime/disabling-console-logback/README.md deleted file mode 100644 index 554f051b41..0000000000 --- a/spring-boot-runtime/disabling-console-logback/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) diff --git a/spring-boot-runtime/disabling-console-logback/pom.xml b/spring-boot-runtime/disabling-console-logback/pom.xml deleted file mode 100644 index 1a415328b6..0000000000 --- a/spring-boot-runtime/disabling-console-logback/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - 4.0.0 - disabling-console-logback - disabling-console-logback - - - com.baeldung - spring-boot-disable-console-logging - 0.0.1-SNAPSHOT - ../ - - - - - org.springframework.boot - spring-boot-starter-web - - - - \ No newline at end of file diff --git a/spring-boot-runtime/pom.xml b/spring-boot-runtime/pom.xml deleted file mode 100644 index baa7faebf8..0000000000 --- a/spring-boot-runtime/pom.xml +++ /dev/null @@ -1,169 +0,0 @@ - - - 4.0.0 - spring-boot-runtime - spring-boot-runtime - war - Demo project for Spring Boot - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-thymeleaf - provided - - - - org.springframework.boot - spring-boot-starter-test - test - - - - commons-io - commons-io - 2.6 - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-starter-mail - - - - org.springframework.boot - spring-boot-starter-actuator - - - - org.springframework.boot - spring-boot-starter-security - - - de.codecentric - spring-boot-admin-starter-client - ${spring-boot-admin-starter-client.version} - - - org.springframework.security - spring-security-test - - - - com.h2database - h2 - runtime - - - - javax.persistence - javax.persistence-api - ${jpa.version} - - - - com.google.guava - guava - ${guava.version} - - - - org.subethamail - subethasmtp - ${subethasmtp.version} - test - - - - org.springframework.cloud - spring-cloud-context - ${springcloud.version} - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - - - - ${project.artifactId} - - - src/main/resources - true - - **/conf.properties - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - - - 2.2 - 18.0 - 3.1.7 - 2.0.2.RELEASE - 4.5.8 - 2.1.6 - - - diff --git a/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java b/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java deleted file mode 100644 index f20fba737a..0000000000 --- a/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.web.log.app; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; -import org.springframework.context.annotation.PropertySource; - -import com.baeldung.web.log.config.CustomeRequestLoggingFilter; - -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; - -@EnableAutoConfiguration -@ComponentScan("com.baeldung.web.log") -@PropertySource("application-log.properties") -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - - public static void main(final String[] args) { - SpringApplication.run(Application.class, args); - } - - @Override - public void onStartup(ServletContext container) throws ServletException { - - AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.setConfigLocation("com.baeldung.web.log"); - container.addListener(new ContextLoaderListener(context)); - - ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(context)); - dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/"); - - container.addFilter("customRequestLoggingFilter", CustomeRequestLoggingFilter.class).addMappingForServletNames(null, false, "dispatcher"); - } -} \ No newline at end of file diff --git a/spring-boot-security/README.md b/spring-boot-security/README.md deleted file mode 100644 index be4690f321..0000000000 --- a/spring-boot-security/README.md +++ /dev/null @@ -1,19 +0,0 @@ -## Spring Boot Security - -This module contains articles about Spring Boot Security - -### Relevant Articles: - -- [Spring Boot Security Auto-Configuration](https://www.baeldung.com/spring-boot-security-autoconfiguration) -- [Spring Security for Spring Boot Integration Tests](https://www.baeldung.com/spring-security-integration-tests) -- [Introduction to Spring Security Taglibs](https://www.baeldung.com/spring-security-taglibs) - -### Spring Boot Security Auto-Configuration - -- mvn clean install -- uncomment actuator dependency simultaneously with the line from basic auth main class -- uncomment security properties for easy testing. If not random will be generated. - -### CURL commands - -- curl -X POST -u baeldung-admin:baeldung -d grant_type=client_credentials -d username=baeldung-admin -d password=baeldung http://localhost:8080/oauth/token diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml deleted file mode 100644 index 62c04b4dc3..0000000000 --- a/spring-boot-security/pom.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - 4.0.0 - spring-boot-security - spring-boot-security - Spring Boot Security Auto-Configuration - jar - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.security.oauth - spring-security-oauth2 - 2.3.3.RELEASE - - - org.springframework.security.oauth.boot - spring-security-oauth2-autoconfigure - 2.1.2.RELEASE - - - 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 - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - org.springframework.boot - spring-boot-autoconfigure - 2.1.1.RELEASE - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - com.baeldung.springbootsecurity.basic_auth.SpringBootSecurityApplication - - - diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/SpringBootAuthorizationServerApplication.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/SpringBootAuthorizationServerApplication.java deleted file mode 100644 index 44dabefbb8..0000000000 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/SpringBootAuthorizationServerApplication.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.springbootsecurity.oauth2server; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.security.Principal; - -@EnableResourceServer -@EnableAuthorizationServer -@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurity.oauth2server") -public class SpringBootAuthorizationServerApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringBootAuthorizationServerApplication.class, args); - } - - @RestController - class UserController { - - @GetMapping("/user") - public Principal user(Principal user) { - return user; - } - - } -} diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/CustomConfigAuthorizationServerIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/CustomConfigAuthorizationServerIntegrationTest.java deleted file mode 100644 index cc953eef5a..0000000000 --- a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/CustomConfigAuthorizationServerIntegrationTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.springbootsecurity.oauth2server; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.security.oauth2.client.OAuth2RestTemplate; -import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException; -import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; - -import static java.util.Collections.singletonList; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootAuthorizationServerApplication.class) -@ActiveProfiles("authz") -public class CustomConfigAuthorizationServerIntegrationTest extends OAuth2IntegrationTestSupport { - - @Test - public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() { - ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read")); - OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); - - OAuth2AccessToken accessToken = restTemplate.getAccessToken(); - - assertNotNull(accessToken); - - } - - @Test(expected = OAuth2AccessDeniedException.class) - public void givenOAuth2Context_whenAccessTokenIsRequestedWithInvalidException_ThenExceptionIsThrown() { - ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("write")); - OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); - - restTemplate.getAccessToken(); - } - - @Test - public void givenOAuth2Context_whenAccessTokenIsRequestedByClientWithWriteScope_ThenAccessTokenIsNotNull() { - ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung-admin", singletonList("write")); - OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); - - OAuth2AccessToken accessToken = restTemplate.getAccessToken(); - - assertNotNull(accessToken); - } - -} - diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/OAuth2IntegrationTestSupport.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/OAuth2IntegrationTestSupport.java deleted file mode 100644 index 3eef206c7d..0000000000 --- a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/OAuth2IntegrationTestSupport.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.springbootsecurity.oauth2server; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; -import org.springframework.security.oauth2.client.OAuth2RestTemplate; -import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; - -import java.util.List; - -import static java.lang.String.format; -import static java.util.Collections.singletonList; - -public class OAuth2IntegrationTestSupport { - - @Value("${local.server.port}") protected int port; - - protected ClientCredentialsResourceDetails getClientCredentialsResourceDetails(final String clientId, final List scopes) { - ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); - resourceDetails.setAccessTokenUri(format("http://localhost:%d/oauth/token", port)); - resourceDetails.setClientId(clientId); - resourceDetails.setClientSecret("baeldung"); - resourceDetails.setScope(scopes); - resourceDetails.setGrantType("client_credentials"); - return resourceDetails; - } - - protected OAuth2RestTemplate getOAuth2RestTemplate(final ClientCredentialsResourceDetails resourceDetails) { - DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext(); - OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails, clientContext); - restTemplate.setMessageConverters(singletonList(new MappingJackson2HttpMessageConverter())); - return restTemplate; - } -} diff --git a/spring-boot-springdoc/pom.xml b/spring-boot-springdoc/pom.xml deleted file mode 100644 index 8c35e38ae6..0000000000 --- a/spring-boot-springdoc/pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - 4.0.0 - spring-boot-springdoc - 0.0.1-SNAPSHOT - spring-boot-springdoc - jar - Project for Springdoc integration - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - org.springdoc - springdoc-openapi-core - 1.1.45 - - - org.springdoc - springdoc-openapi-ui - 1.1.45 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - - integration - - - - org.springframework.boot - spring-boot-maven-plugin - 2.1.8.RELEASE - - - pre-integration-test - - start - - - - post-integration-test - - stop - - - - - - org.springdoc - springdoc-openapi-maven-plugin - 0.2 - - - integration-test - - generate - - - - - http://localhost:8080/api-docs - openapi.json - ${project.build.directory} - - - - - - - - \ No newline at end of file diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java deleted file mode 100644 index 4d7d9e3d85..0000000000 --- a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.springdoc.controller; - -import java.util.Collection; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PatchMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -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.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; - -import com.baeldung.springdoc.exception.BookNotFoundException; -import com.baeldung.springdoc.model.Book; -import com.baeldung.springdoc.repository.BookRepository; - -@RestController -@RequestMapping("/api/book") -public class BookController { - - @Autowired - private BookRepository repository; - - @GetMapping("/{id}") - public Book findById(@PathVariable long id) { - return repository.findById(id) - .orElseThrow(() -> new BookNotFoundException()); - } - - @GetMapping("/") - public Collection findBooks() { - return repository.getBooks(); - } - - @PutMapping("/{id}") - @ResponseStatus(HttpStatus.OK) - public Book updateBook(@PathVariable("id") final String id, @RequestBody final Book book) { - return book; - } - - @PatchMapping("/{id}") - @ResponseStatus(HttpStatus.OK) - public Book patchBook(@PathVariable("id") final String id, @RequestBody final Book book) { - return book; - } - - @PostMapping("/") - @ResponseStatus(HttpStatus.CREATED) - public Book postBook(@NotNull @Valid @RequestBody final Book book) { - return book; - } - - @RequestMapping(method = RequestMethod.HEAD, value = "/") - @ResponseStatus(HttpStatus.OK) - public Book headBook() { - return new Book(); - } - - @DeleteMapping("/{id}") - @ResponseStatus(HttpStatus.OK) - public long deleteBook(@PathVariable final long id) { - return id; - } -} diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/repository/BookRepository.java b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/repository/BookRepository.java deleted file mode 100644 index 4040ba28c2..0000000000 --- a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/repository/BookRepository.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.springdoc.repository; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -import org.springframework.stereotype.Repository; - -import com.baeldung.springdoc.model.Book; - -@Repository -public class BookRepository { - - private Map books = new HashMap<>(); - - public Optional findById(long id) { - return Optional.ofNullable(books.get(id)); - } - - public void add(Book book) { - books.put(book.getId(), book); - } - - public Collection getBooks() { - return books.values(); - } -} diff --git a/spring-boot-springdoc/src/main/resources/application.properties b/spring-boot-springdoc/src/main/resources/application.properties deleted file mode 100644 index f03e90feb6..0000000000 --- a/spring-boot-springdoc/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -# custom path for swagger-ui -springdoc.swagger-ui.path=/swagger-ui-custom.html - -# custom path for api docs -springdoc.api-docs.path=/api-docs diff --git a/spring-boot-testing/.mvn/wrapper/maven-wrapper.jar b/spring-boot-testing/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 9cc84ea9b4..0000000000 Binary files a/spring-boot-testing/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/spring-boot-testing/README.md b/spring-boot-testing/README.md deleted file mode 100644 index 0b2533e6bc..0000000000 --- a/spring-boot-testing/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Spring Boot Testing - -This module contains articles about Spring Boot testing - -### The Course - -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles: - -- [Testing with Spring and Spock](https://www.baeldung.com/spring-spock-testing) -- [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test) -- [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level) -- [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis) diff --git a/spring-boot-testing/pom.xml b/spring-boot-testing/pom.xml deleted file mode 100644 index ebe87fdd70..0000000000 --- a/spring-boot-testing/pom.xml +++ /dev/null @@ -1,136 +0,0 @@ - - - 4.0.0 - spring-boot-testing - spring-boot-testing - war - This is simple boot application for demonstrating testing features. - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-test - test - - - - - it.ozimov - embedded-redis - 0.7.2 - test - - - - org.spockframework - spock-core - ${spock.version} - test - - - - org.spockframework - spock-spring - ${spock.version} - test - - - - io.rest-assured - rest-assured - test - - - - - - spring-boot-testing - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-war-plugin - - - - pl.project13.maven - git-commit-id-plugin - ${git-commit-id-plugin.version} - - - get-the-git-infos - - revision - - initialize - - - validate-the-git-infos - - validateRevision - - package - - - - true - ${project.build.outputDirectory}/git.properties - - - - - org.codehaus.gmavenplus - gmavenplus-plugin - ${gmavenplus-plugin.version} - - - - compileTests - - - - - - - - - - com.baeldung.boot.Application - 2.2.4 - 1.2-groovy-2.4 - 1.6 - - - diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java deleted file mode 100644 index cdf79b159c..0000000000 --- a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.autoconfig.exclude; - -import static org.junit.Assert.assertEquals; -import io.restassured.RestAssured; - -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.http.HttpStatus; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) -@ActiveProfiles("test") -public class ExcludeAutoConfig2IntegrationTest { - - @Test - public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); - assertEquals(HttpStatus.OK.value(), statusCode); - } -} diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java deleted file mode 100644 index 8429aed6cd..0000000000 --- a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.autoconfig.exclude; - -import static org.junit.Assert.assertEquals; -import io.restassured.RestAssured; - -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.http.HttpStatus; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) -public class ExcludeAutoConfig4IntegrationTest { - - @Test - public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); - assertEquals(HttpStatus.OK.value(), statusCode); - } -} diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java deleted file mode 100644 index fe71f44ddf..0000000000 --- a/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.boot.autoconfig; - -import static org.junit.Assert.assertEquals; -import io.restassured.RestAssured; - -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.http.HttpStatus; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) -public class AutoConfigIntegrationTest { - - @Test - public void givenNoAuthentication_whenAccessHome_thenUnauthorized() { - int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); - assertEquals(HttpStatus.UNAUTHORIZED.value(), statusCode); - } - - @Test - public void givenAuthentication_whenAccessHome_thenOK() { - int statusCode = RestAssured.given().auth().basic("john", "123").get("http://localhost:8080/").statusCode(); - assertEquals(HttpStatus.OK.value(), statusCode); - } -} diff --git a/spring-boot-vue/pom.xml b/spring-boot-vue/pom.xml deleted file mode 100644 index 98bba784d2..0000000000 --- a/spring-boot-vue/pom.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - 4.0.0 - spring-boot-vue - 0.0.1-SNAPSHOT - spring-boot-vue - jar - Demo project for Spring Boot Vue project - - - com.baeldung - parent-boot-2 - 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-thymeleaf - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - UTF-8 - UTF-8 - - - diff --git a/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 16e0708fc9..0000000000 --- a/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.springbootmvc.SpringBootMvcApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringBootMvcApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot/.factorypath b/spring-boot/.factorypath deleted file mode 100644 index 22b8a1ce95..0000000000 --- a/spring-boot/.factorypath +++ /dev/null @@ -1,174 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-boot/.gitignore b/spring-boot/.gitignore deleted file mode 100644 index 88e3308e9d..0000000000 --- a/spring-boot/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -/target/ -.settings/ -.classpath -.project - diff --git a/spring-boot/README.MD b/spring-boot/README.MD deleted file mode 100644 index 2423d6d331..0000000000 --- a/spring-boot/README.MD +++ /dev/null @@ -1,38 +0,0 @@ -## Spring Boot - -This module contains articles about Spring Boot - -### The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles: - -- [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring) -- [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) -- [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) -- [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) -- [Using Custom Banners in Spring Boot](https://www.baeldung.com/spring-boot-custom-banners) -- [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) -- [Create a Custom FailureAnalyzer with Spring Boot](https://www.baeldung.com/spring-boot-failure-analyzer) -- [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) -- [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom) -- [Using @JsonComponent in Spring Boot](https://www.baeldung.com/spring-boot-jsoncomponent) -- [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) -- [How to Get All Spring-Managed Beans?](https://www.baeldung.com/spring-show-all-beans) -- [Spring Boot and Togglz Aspect](https://www.baeldung.com/spring-togglz) -- [Getting Started with GraphQL and Spring Boot](https://www.baeldung.com/spring-graphql) -- [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) -- [An Introduction to Kong](https://www.baeldung.com/kong) -- [Spring Boot: Customize Whitelabel Error Page](https://www.baeldung.com/spring-boot-custom-error-page) -- [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) -- [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) -- [How to Define a Spring Boot Filter?](https://www.baeldung.com/spring-boot-add-filter) -- [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) -- [Guide to the Favicon in Spring Boot](https://www.baeldung.com/spring-boot-favicon) -- [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) -- [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) -- [Introduction to Chaos Monkey](https://www.baeldung.com/spring-boot-chaos-monkey) -- [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report) -- [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information) -- [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) -- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml deleted file mode 100644 index 2152a0a00d..0000000000 --- a/spring-boot/pom.xml +++ /dev/null @@ -1,256 +0,0 @@ - - - 4.0.0 - spring-boot - spring-boot - war - This is simple boot application for Spring boot actuator test - - - com.baeldung - parent-boot-2 - 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-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.ehcache - ehcache - - - org.hibernate - hibernate-ehcache - - - org.springframework.boot - spring-boot-starter-actuator - - - - com.graphql-java - graphql-spring-boot-starter - ${graphql-spring-boot-starter.version} - - - com.graphql-java - graphql-java-tools - ${graphql-java-tools.version} - - - com.graphql-java - graphiql-spring-boot-starter - ${graphiql-spring-boot-starter.version} - - - - org.springframework.boot - spring-boot-starter-tomcat - - - - org.springframework.boot - spring-boot-starter-test - test - - - - io.dropwizard.metrics - metrics-core - - - - com.h2database - h2 - - - - org.springframework.boot - spring-boot-starter - - - com.jayway.jsonpath - json-path - test - - - - com.google.guava - guava - ${guava.version} - - - - org.apache.tomcat - tomcat-servlet-api - ${tomee-servlet-api.version} - provided - - - - org.togglz - togglz-spring-boot-starter - ${togglz.version} - - - - org.togglz - togglz-spring-security - ${togglz.version} - - - - org.apache.activemq - artemis-server - - - - com.rometools - rome - ${rome.version} - - - - de.codecentric - chaos-monkey-spring-boot - ${chaos.monkey.version} - - - - javax.validation - validation-api - - - - - spring-boot - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-war-plugin - - - - pl.project13.maven - git-commit-id-plugin - ${git-commit-id-plugin.version} - - - get-the-git-infos - - revision - - initialize - - - validate-the-git-infos - - validateRevision - - package - - - - true - ${project.build.outputDirectory}/git.properties - - - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - - - - com.baeldung.intro.App - 8.5.11 - 2.4.1.Final - 1.9.0 - 2.0.0 - 5.0.2 - 5.0.2 - 5.2.4 - 18.0 - 2.2.4 - - - diff --git a/spring-boot/src/main/java/com/baeldung/beanvalidation/application/Application.java b/spring-boot/src/main/java/com/baeldung/beanvalidation/application/Application.java deleted file mode 100644 index b37eec9da0..0000000000 --- a/spring-boot/src/main/java/com/baeldung/beanvalidation/application/Application.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.beanvalidation.application; - -import com.baeldung.beanvalidation.application.entities.User; -import com.baeldung.beanvalidation.application.repositories.UserRepository; - -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 { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - - @Bean - public CommandLineRunner run(UserRepository userRepository) throws Exception { - return (String[] args) -> { - User user1 = new User("Bob", "bob@domain.com"); - User user2 = new User("Jenny", "jenny@domain.com"); - userRepository.save(user1); - userRepository.save(user2); - userRepository.findAll().forEach(System.out::println); - }; - } -} diff --git a/spring-boot/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java b/spring-boot/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java deleted file mode 100644 index 0c47e27e25..0000000000 --- a/spring-boot/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.beanvalidation.application.controllers; - -import com.baeldung.beanvalidation.application.entities.User; -import com.baeldung.beanvalidation.application.repositories.UserRepository; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.validation.Valid; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.validation.FieldError; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class UserController { - - private final UserRepository userRepository; - - @Autowired - public UserController(UserRepository userRepository) { - this.userRepository = userRepository; - } - - @GetMapping("/users") - public List getUsers() { - return (List) userRepository.findAll(); - } - - @PostMapping("/users") - ResponseEntity addUser(@Valid @RequestBody User user) { - return ResponseEntity.ok("User is valid"); - } - - @ResponseStatus(HttpStatus.BAD_REQUEST) - @ExceptionHandler(MethodArgumentNotValidException.class) - public Map handleValidationExceptions(MethodArgumentNotValidException ex) { - Map errors = new HashMap<>(); - ex.getBindingResult().getAllErrors().forEach((error) -> { - String fieldName = ((FieldError) error).getField(); - String errorMessage = error.getDefaultMessage(); - errors.put(fieldName, errorMessage); - }); - return errors; - } -} diff --git a/spring-boot/src/main/java/com/baeldung/beanvalidation/application/entities/User.java b/spring-boot/src/main/java/com/baeldung/beanvalidation/application/entities/User.java deleted file mode 100644 index 8233d08f4e..0000000000 --- a/spring-boot/src/main/java/com/baeldung/beanvalidation/application/entities/User.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.beanvalidation.application.entities; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.validation.constraints.NotBlank; - -@Entity -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - @NotBlank(message = "Name is mandatory") - private String name; - - @NotBlank(message = "Email is mandatory") - private String email; - - public User(){} - - public User(String name, String email) { - this.name = name; - this.email = email; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - @Override - public String toString() { - return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; - } -} diff --git a/spring-boot/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java b/spring-boot/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java deleted file mode 100644 index 8bf7a9f8b2..0000000000 --- a/spring-boot/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.beanvalidation.application.repositories; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.beanvalidation.application.entities.User; - -@Repository -public interface UserRepository extends CrudRepository {} diff --git a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java b/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java deleted file mode 100644 index 97165f2cf3..0000000000 --- a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.bootcustomfilters.controller; - -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.baeldung.bootcustomfilters.model.User; - -/** - * Rest controller for User - * @author hemant - * - */ -@RestController -@RequestMapping("/users") -public class UserController { - - private static final Logger LOG = LoggerFactory.getLogger(UserController.class); - - @GetMapping("") - public List getAllUsers() { - LOG.info("Fetching all the users"); - return Arrays.asList( - new User(UUID.randomUUID().toString(), "User1", "user1@test.com"), - new User(UUID.randomUUID().toString(), "User1", "user1@test.com"), - new User(UUID.randomUUID().toString(), "User1", "user1@test.com")); - } - -} 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 deleted file mode 100644 index 630820ff9f..0000000000 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java +++ /dev/null @@ -1,23 +0,0 @@ -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; - -import com.baeldung.displayallbeans.service.FooService; - -@Controller -public class FooController { - @Autowired - private FooService fooService; - - @GetMapping(value = "/displayallbeans") - public ResponseEntity getHeaderAndBody(Map model) { - model.put("header", fooService.getHeader()); - model.put("message", fooService.getBody()); - return ResponseEntity.ok("displayallbeans"); - } -} diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java deleted file mode 100644 index 1f3c15ee0e..0000000000 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.displayallbeans.service; - -import org.springframework.stereotype.Service; - -@Service -public class FooService { - - public String getHeader() { - return "Display All Beans"; - } - - public String getBody() { - return "This is a sample application that displays all beans " + "in Spring IoC container using ListableBeanFactory interface " + "and Spring Boot Actuators."; - } - -} diff --git a/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java b/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java deleted file mode 100644 index 5dd55ef077..0000000000 --- a/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.errorhandling; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.errorhandling") -public class ErrorHandlingApplication { - - public static void main(String [] args) { - System.setProperty("spring.profiles.active", "errorhandling"); - SpringApplication.run(ErrorHandlingApplication.class, args); - } -} diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyService.java b/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyService.java deleted file mode 100644 index 72334ca8fa..0000000000 --- a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyService.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.failureanalyzer; - -import javax.annotation.Resource; - -import org.springframework.stereotype.Service; - -@Service -public class MyService { - - @Resource(name = "myDAO") - private MyDAO myDAO; - -} diff --git a/spring-boot/src/main/java/com/baeldung/git/README.md b/spring-boot/src/main/java/com/baeldung/git/README.md deleted file mode 100644 index 7e6a597c28..0000000000 --- a/spring-boot/src/main/java/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/spring-boot/src/main/java/com/baeldung/intro/App.java b/spring-boot/src/main/java/com/baeldung/intro/App.java deleted file mode 100644 index b5d53f0da3..0000000000 --- a/spring-boot/src/main/java/com/baeldung/intro/App.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.intro; - -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, args); - } -} diff --git a/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java b/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java deleted file mode 100644 index 32f22f2cae..0000000000 --- a/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.intro.controller; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class HomeController { - - @GetMapping("/") - public String root() { - return "Index Page"; - } - - @GetMapping("/local") - public String local() { - return "/local"; - } -} diff --git a/spring-boot/src/main/java/org/baeldung/boot/Application.java b/spring-boot/src/main/java/org/baeldung/boot/Application.java deleted file mode 100644 index c1b6558b26..0000000000 --- a/spring-boot/src/main/java/org/baeldung/boot/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -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/config/WebConfig.java b/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java deleted file mode 100644 index 9554facb12..0000000000 --- a/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung.boot.config; - -import org.baeldung.boot.converter.StringToEmployeeConverter; -import org.baeldung.boot.converter.StringToEnumConverterFactory; -import org.baeldung.boot.converter.GenericBigDecimalConverter; -import org.springframework.context.annotation.Configuration; -import org.springframework.format.FormatterRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class WebConfig implements WebMvcConfigurer { - - @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/converter/GenericBigDecimalConverter.java b/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java deleted file mode 100644 index 8add28fc2d..0000000000 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java +++ /dev/null @@ -1,31 +0,0 @@ -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/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java deleted file mode 100644 index 1bf75b38f0..0000000000 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.boot.converter; - -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])); - } -} 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 deleted file mode 100644 index 27bad4c387..0000000000 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.boot.converter.controller; - -import org.springframework.http.ResponseEntity; -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 -public class StringToEmployeeConverterController { - - @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/boot/domain/Modes.java b/spring-boot/src/main/java/org/baeldung/boot/domain/Modes.java deleted file mode 100644 index dcba064e8c..0000000000 --- a/spring-boot/src/main/java/org/baeldung/boot/domain/Modes.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.baeldung.boot.domain; - -public enum Modes { - - ALPHA, BETA; -} diff --git a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/User.java b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/User.java deleted file mode 100644 index 1f14131300..0000000000 --- a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/User.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.boot.jsoncomponent; - -import javafx.scene.paint.Color; - -public class User { - private final Color favoriteColor; - - public User(Color favoriteColor) { - this.favoriteColor = favoriteColor; - } - - public Color getFavoriteColor() { - return favoriteColor; - } -} diff --git a/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java b/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java deleted file mode 100644 index 4a88fcea07..0000000000 --- a/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.demo; - -import com.baeldung.graphql.GraphqlConfiguration; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -import org.springframework.context.annotation.Import; - -@SpringBootApplication -@Import(GraphqlConfiguration.class) -public class DemoApplication { - - public static void main(String[] args) { - System.setProperty("spring.config.name", "demo"); - SpringApplication.run(DemoApplication.class, args); - } - -} diff --git a/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java b/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java deleted file mode 100644 index 645ce2838a..0000000000 --- a/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.baeldung.demo.boottest; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.validation.constraints.Size; -import java.util.Date; - -@Entity -@Table(name = "person") -public class Employee { - - public Employee() { - } - - public Employee(String name) { - this.name = name; - } - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Size(min = 3, max = 20) - private String name; - - private Date birthday; - - 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; - } -} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java deleted file mode 100644 index 00fdbfaae4..0000000000 --- a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.demo.boottest; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -@Repository -@Transactional -public interface EmployeeRepository extends JpaRepository { - - public Employee findByName(String name); - - public List findAll(); - -} diff --git a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java deleted file mode 100644 index 07765a511c..0000000000 --- a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.demo.boottest; - -import java.util.List; - -public interface EmployeeService { - - public Employee getEmployeeById(Long id); - - public Employee getEmployeeByName(String name); - - public List getAllEmployees(); - - public boolean exists(String email); - - public Employee save(Employee employee); -} diff --git a/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java b/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java deleted file mode 100644 index 66943f6461..0000000000 --- a/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.demo.components; - -import org.baeldung.demo.model.Foo; -import org.baeldung.demo.repository.FooRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class FooService { - - @Autowired - private FooRepository fooRepository; - - public Foo getFooWithId(Integer id) throws Exception { - return fooRepository.findById(id).orElse(null); - } - - public Foo getFooWithName(String name) { - return fooRepository.findByName(name); - } -} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/demo/model/Foo.java b/spring-boot/src/main/java/org/baeldung/demo/model/Foo.java deleted file mode 100644 index e5638cfd3d..0000000000 --- a/spring-boot/src/main/java/org/baeldung/demo/model/Foo.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.baeldung.demo.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -@Entity -public class Foo implements Serializable { - private static final long serialVersionUID = 1L; - @Id - @GeneratedValue - private Integer id; - private String name; - - public Foo() { - } - - public Foo(String name) { - this.name = name; - } - - public Foo(Integer id, String name) { - super(); - this.id = id; - this.name = 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/src/main/java/org/baeldung/demo/repository/FooRepository.java b/spring-boot/src/main/java/org/baeldung/demo/repository/FooRepository.java deleted file mode 100644 index c04e0c7438..0000000000 --- a/spring-boot/src/main/java/org/baeldung/demo/repository/FooRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.demo.repository; - -import org.baeldung.demo.model.Foo; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface FooRepository extends JpaRepository { - public Foo findByName(String name); -} diff --git a/spring-boot/src/main/java/org/baeldung/demo/service/FooController.java b/spring-boot/src/main/java/org/baeldung/demo/service/FooController.java deleted file mode 100644 index c28dcde1a7..0000000000 --- a/spring-boot/src/main/java/org/baeldung/demo/service/FooController.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.demo.service; - -import org.baeldung.demo.components.FooService; -import org.baeldung.demo.model.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class FooController { - - @Autowired - private FooService fooService; - - @GetMapping("/{id}") - public Foo getFooWithId(@PathVariable Integer id) throws Exception { - return fooService.getFooWithId(id); - } - - @GetMapping("/") - public Foo getFooWithName(@RequestParam String name) throws Exception { - return fooService.getFooWithName(name); - } -} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/model/User.java b/spring-boot/src/main/java/org/baeldung/model/User.java deleted file mode 100644 index eb886338a0..0000000000 --- a/spring-boot/src/main/java/org/baeldung/model/User.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.baeldung.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/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java deleted file mode 100644 index 752664cd5d..0000000000 --- a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.baeldung.repository; - -import org.baeldung.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.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; - -@Repository("userRepository") -public interface UserRepository extends JpaRepository { - - int countByStatus(int status); - - Optional findOneByName(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/src/main/java/org/baeldung/session/exception/Application.java b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java deleted file mode 100644 index 354c64c258..0000000000 --- a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.session.exception; - -import org.baeldung.demo.model.Foo; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; - -@EntityScan(basePackageClasses = Foo.class) -@SpringBootApplication -public class Application { - public static void main(String[] args) { - System.setProperty("spring.config.name", "exception"); - System.setProperty("spring.profiles.active", "exception"); - SpringApplication.run(Application.class, args); - } -} diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java deleted file mode 100644 index ce7bbfe57b..0000000000 --- a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.session.exception.repository; - -import org.baeldung.demo.model.Foo; - -public interface FooRepository { - - void save(Foo foo); - - Foo get(Integer id); -} diff --git a/spring-boot/src/main/resources/application-errorhandling.properties b/spring-boot/src/main/resources/application-errorhandling.properties deleted file mode 100644 index 6ffcfbaf52..0000000000 --- a/spring-boot/src/main/resources/application-errorhandling.properties +++ /dev/null @@ -1,10 +0,0 @@ -#server -server.port=9000 -server.servlet-path=/ -server.context-path=/ -#server.error.whitelabel.enabled=false - -#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration - -#for Spring Boot 2.0+ -#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration \ No newline at end of file diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties deleted file mode 100644 index 918fe5ea67..0000000000 --- a/spring-boot/src/main/resources/application.properties +++ /dev/null @@ -1,74 +0,0 @@ -server.port=9090 -server.servlet.contextPath=/springbootapp -management.server.port=8081 -management.server.address=127.0.0.1 -#debug=true -spring.jpa.show-sql=true -spring.jpa.hibernate.ddl-auto = update - -management.endpoints.jmx.domain=Spring Sample Application -spring.jmx.unique-names=true - -management.endpoints.web.exposure.include=* -management.endpoint.shutdown.enabled=true - -##jolokia.config.debug=true -##endpoints.jolokia.enabled=true -##endpoints.jolokia.path=jolokia - -spring.jmx.enabled=true - -## for pretty printing of json when endpoints accessed over HTTP -http.mappers.jsonPrettyPrint=true - -## Configuring info endpoint -info.app.name=Spring Sample Application -info.app.description=This is my first spring boot application G1 -info.app.version=1.0.0 -info.java-vendor = ${java.specification.vendor} - -logging.level.org.springframework=INFO - -#Servlet Configuration -servlet.name=dispatcherExample -servlet.mapping=/dispatcherExampleURL - -#spring.banner.charset=UTF-8 -#spring.banner.location=classpath:banner.txt -#spring.banner.image.location=classpath:banner.gif -#spring.banner.image.width= //TODO -#spring.banner.image.height= //TODO -#spring.banner.image.margin= //TODO -#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/public/error/404.html b/spring-boot/src/main/resources/public/error/404.html deleted file mode 100644 index 02d6092bee..0000000000 --- a/spring-boot/src/main/resources/public/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/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/test/java/org/baeldung/boot/ApplicationIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java deleted file mode 100644 index 5e351157c8..0000000000 --- a/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.boot; - -import org.baeldung.session.exception.Application; -import org.junit.Test; -import org.junit.runner.RunWith; -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 = Application.class) -@TestPropertySource("classpath:exception.properties") -public class ApplicationIntegrationTest { - @Test - public void contextLoads() { - } -} diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java deleted file mode 100644 index 5d02d34f53..0000000000 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.boot.repository; - -import static org.junit.Assert.assertThat; - -import org.baeldung.boot.DemoApplicationIntegrationTest; -import org.baeldung.demo.model.Foo; -import org.baeldung.demo.repository.FooRepository; - -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.is; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class FooRepositoryIntegrationTest extends DemoApplicationIntegrationTest { - @Autowired - private FooRepository fooRepository; - - @Before - public void setUp() { - fooRepository.save(new Foo("Foo")); - fooRepository.save(new Foo("Bar")); - } - - @Test - public void testFindByName() { - Foo foo = fooRepository.findByName("Bar"); - assertThat(foo, notNullValue()); - assertThat(foo.getId(), is(2)); - } - -} 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 deleted file mode 100644 index baa4f70e83..0000000000 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.baeldung.boot.repository; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertThat; - -import org.baeldung.boot.DemoApplicationIntegrationTest; -import org.baeldung.demo.model.Foo; -import org.baeldung.demo.repository.FooRepository; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class HibernateSessionIntegrationTest extends DemoApplicationIntegrationTest { - @Autowired - private FooRepository fooRepository; - - @Test - public void whenSavingWithCurrentSession_thenThrowNoException() { - Foo foo = new Foo("Exception Solved"); - fooRepository.save(foo); - foo = null; - foo = fooRepository.findByName("Exception Solved"); - - assertThat(foo, notNullValue()); - assertThat(foo.getId(), is(1)); - assertThat(foo.getName(), is("Exception Solved")); - } -} diff --git a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java deleted file mode 100644 index ea7f118967..0000000000 --- a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.baeldung.repository; - -import org.baeldung.boot.config.H2JpaConfig; -import org.baeldung.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.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Created by adam. - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = H2JpaConfig.class) -public class UserRepositoryIntegrationTest { - - private final String USER_NAME_ADAM = "Adam"; - private final Integer ACTIVE_STATUS = 1; - - @Autowired - private UserRepository userRepository; - - @Test - public void givenEmptyDBWhenFindOneByNameThenReturnEmptyOptional() { - Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); - - assertThat(foundUser.isPresent()).isEqualTo(false); - } - - @Test - public void givenUserInDBWhenFindOneByNameThenReturnOptionalWithUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - userRepository.save(user); - - Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); - - assertThat(foundUser.isPresent()).isEqualTo(true); - - assertThat(foundUser - .get() - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - CompletableFuture userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS); - - assertThat(userByStatus - .get() - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @After - public void cleanUp() { - userRepository.deleteAll(); - } - -} diff --git a/spring-boot/src/test/resources/logback-test.xml b/spring-boot/src/test/resources/logback-test.xml deleted file mode 100644 index 9e0f4e221f..0000000000 --- a/spring-boot/src/test/resources/logback-test.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-caching/README.md b/spring-caching/README.md index 14dfe94041..3efbfe3eaa 100644 --- a/spring-caching/README.md +++ b/spring-caching/README.md @@ -2,3 +2,4 @@ - [Introduction To Ehcache](http://www.baeldung.com/ehcache) - [A Guide To Caching in Spring](http://www.baeldung.com/spring-cache-tutorial) - [Spring Cache – Creating a Custom KeyGenerator](http://www.baeldung.com/spring-cache-custom-keygenerator) +- [Cache Eviction in Spring Boot](https://www.baeldung.com/spring-boot-evict-cache) diff --git a/spring-caching/pom.xml b/spring-caching/pom.xml index c3ededbd14..80644f8a5f 100644 --- a/spring-caching/pom.xml +++ b/spring-caching/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 spring-caching 0.1-SNAPSHOT @@ -15,10 +16,18 @@ + + org.springframework.boot + spring-boot-starter-web + org.springframework spring-context + + org.springframework.boot + spring-boot-starter-cache + org.springframework spring-web @@ -36,10 +45,21 @@ spring-test test + + com.github.ben-manes.caffeine + caffeine + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-jdbc + - 3.5.2 - - \ No newline at end of file + diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java b/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java new file mode 100644 index 0000000000..afa1d0ec99 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java @@ -0,0 +1,18 @@ +package com.baeldung.caching.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; +//import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@EnableCaching +//to run any module like ehcache,caching or multiplecachemanager in local machine +//add it's package for ComponentScan like below +//@ComponentScan("com.baeldung.multiplecachemanager") +public class CacheApplication { + + public static void main(String[] args) { + SpringApplication.run(CacheApplication.class, args); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java b/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java new file mode 100644 index 0000000000..a76a01caae --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java @@ -0,0 +1,24 @@ +package com.baeldung.caching.boot; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.stereotype.Component; + +import static java.util.Arrays.asList; + +@Component +public class SimpleCacheCustomizer implements CacheManagerCustomizer { + + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleCacheCustomizer.class); + + static final String USERS_CACHE = "users"; + static final String TRANSACTIONS_CACHE = "transactions"; + + @Override + public void customize(ConcurrentMapCacheManager cacheManager) { + LOGGER.info("Customizing Cache Manager"); + cacheManager.setCacheNames(asList(USERS_CACHE, TRANSACTIONS_CACHE)); + } +} diff --git a/spring-caching/src/main/java/org/baeldung/caching/config/ApplicationCacheConfig.java b/spring-caching/src/main/java/com/baeldung/caching/config/ApplicationCacheConfig.java similarity index 96% rename from spring-caching/src/main/java/org/baeldung/caching/config/ApplicationCacheConfig.java rename to spring-caching/src/main/java/com/baeldung/caching/config/ApplicationCacheConfig.java index 8bf23de2cc..9a8759cbff 100644 --- a/spring-caching/src/main/java/org/baeldung/caching/config/ApplicationCacheConfig.java +++ b/spring-caching/src/main/java/com/baeldung/caching/config/ApplicationCacheConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.caching.config; +package com.baeldung.caching.config; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; diff --git a/spring-caching/src/main/java/org/baeldung/caching/config/CachingConfig.java b/spring-caching/src/main/java/com/baeldung/caching/config/CachingConfig.java similarity index 90% rename from spring-caching/src/main/java/org/baeldung/caching/config/CachingConfig.java rename to spring-caching/src/main/java/com/baeldung/caching/config/CachingConfig.java index c995bca68d..d245b05502 100644 --- a/spring-caching/src/main/java/org/baeldung/caching/config/CachingConfig.java +++ b/spring-caching/src/main/java/com/baeldung/caching/config/CachingConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.caching.config; +package com.baeldung.caching.config; import java.util.Arrays; @@ -12,7 +12,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableCaching -@ComponentScan("org.baeldung.caching.example") +@ComponentScan("com.baeldung.caching.example") public class CachingConfig { @Bean diff --git a/spring-caching/src/main/java/org/baeldung/caching/config/CustomKeyGenerator.java b/spring-caching/src/main/java/com/baeldung/caching/config/CustomKeyGenerator.java similarity index 92% rename from spring-caching/src/main/java/org/baeldung/caching/config/CustomKeyGenerator.java rename to spring-caching/src/main/java/com/baeldung/caching/config/CustomKeyGenerator.java index c1da9493e0..173f44bfbc 100644 --- a/spring-caching/src/main/java/org/baeldung/caching/config/CustomKeyGenerator.java +++ b/spring-caching/src/main/java/com/baeldung/caching/config/CustomKeyGenerator.java @@ -1,4 +1,4 @@ -package org.baeldung.caching.config; +package com.baeldung.caching.config; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.util.StringUtils; diff --git a/spring-caching/src/main/java/org/baeldung/caching/eviction/controllers/CachingController.java b/spring-caching/src/main/java/com/baeldung/caching/eviction/controllers/CachingController.java similarity index 78% rename from spring-caching/src/main/java/org/baeldung/caching/eviction/controllers/CachingController.java rename to spring-caching/src/main/java/com/baeldung/caching/eviction/controllers/CachingController.java index aaaf8a5918..2980e32763 100644 --- a/spring-caching/src/main/java/org/baeldung/caching/eviction/controllers/CachingController.java +++ b/spring-caching/src/main/java/com/baeldung/caching/eviction/controllers/CachingController.java @@ -1,6 +1,6 @@ -package org.baeldung.caching.eviction.controllers; +package com.baeldung.caching.eviction.controllers; -import org.baeldung.caching.eviction.service.CachingService; +import com.baeldung.caching.eviction.service.CachingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-caching/src/main/java/org/baeldung/caching/eviction/service/CachingService.java b/spring-caching/src/main/java/com/baeldung/caching/eviction/service/CachingService.java similarity index 97% rename from spring-caching/src/main/java/org/baeldung/caching/eviction/service/CachingService.java rename to spring-caching/src/main/java/com/baeldung/caching/eviction/service/CachingService.java index a0dd30c329..d44da332d4 100644 --- a/spring-caching/src/main/java/org/baeldung/caching/eviction/service/CachingService.java +++ b/spring-caching/src/main/java/com/baeldung/caching/eviction/service/CachingService.java @@ -1,4 +1,4 @@ -package org.baeldung.caching.eviction.service; +package com.baeldung.caching.eviction.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/AbstractService.java b/spring-caching/src/main/java/com/baeldung/caching/example/AbstractService.java new file mode 100644 index 0000000000..5893ffdfcf --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/example/AbstractService.java @@ -0,0 +1,76 @@ +package com.baeldung.caching.example; + +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.cache.annotation.Caching; + +public abstract class AbstractService { + + // this method configuration is equivalent to xml configuration + @Cacheable(value = "addresses", key = "#customer.name") + public String getAddress(final Customer customer) { + return customer.getAddress(); + } + + /** + * The method returns the customer's address, + only it doesn't find it the cache- addresses and directory. + * + * @param customer the customer + * @return the address + */ + @Cacheable({ "addresses", "directory" }) + public String getAddress1(final Customer customer) { + return customer.getAddress(); + } + + /** + * The method returns the customer's address, + but refreshes all the entries in the cache to load new ones. + * + * @param customer the customer + * @return the address + */ + @CacheEvict(value = "addresses", allEntries = true) + public String getAddress2(final Customer customer) { + return customer.getAddress(); + } + + /** + * The method returns the customer's address, + but not before selectively evicting the cache as per specified paramters. + * + * @param customer the customer + * @return the address + */ + @Caching(evict = { @CacheEvict("addresses"), @CacheEvict(value = "directory", key = "#customer.name") }) + public String getAddress3(final Customer customer) { + return customer.getAddress(); + } + + /** + * The method uses the class level cache to look up for entries. + * + * @param customer the customer + * @return the address + */ + @Cacheable + // parameter not required as we have declared it using @CacheConfig + public String getAddress4(final Customer customer) { + return customer.getAddress(); + } + + /** + * The method selectively caches the results that meet the predefined criteria. + * + * @param customer the customer + * @return the address + */ + @CachePut(value = "addresses", condition = "#customer.name=='Tom'") + // @CachePut(value = "addresses", unless = "#result.length>64") + public String getAddress5(final Customer customer) { + return customer.getAddress(); + } + +} diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/BookService.java b/spring-caching/src/main/java/com/baeldung/caching/example/BookService.java new file mode 100644 index 0000000000..2b335ac10d --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/example/BookService.java @@ -0,0 +1,21 @@ +package com.baeldung.caching.example; + +import com.baeldung.caching.model.Book; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; + +@Component +public class BookService { + + @Cacheable(value="books", keyGenerator="customKeyGenerator") + public List getBooks() { + List books = new ArrayList(); + books.add(new Book(1, "The Counterfeiters", "André Gide")); + books.add(new Book(2, "Peer Gynt and Hedda Gabler", "Henrik Ibsen")); + return books; + } + +} diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/Customer.java b/spring-caching/src/main/java/com/baeldung/caching/example/Customer.java new file mode 100644 index 0000000000..52de4bc1cc --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/example/Customer.java @@ -0,0 +1,48 @@ +package com.baeldung.caching.example; + +public class Customer { + + private int id; + private String name; + private String address; + + public Customer() { + super(); + } + + public Customer(final String name, final String address) { + this.name = name; + this.address = address; + } + + // + + 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 getAddress() { + return address; + } + + public void setAddress(final String address) { + this.address = address; + } + + public void setCustomerAddress(final String address) { + this.address = name + "," + address; + } + +} diff --git a/spring-caching/src/main/java/org/baeldung/caching/example/CustomerDataService.java b/spring-caching/src/main/java/com/baeldung/caching/example/CustomerDataService.java similarity index 98% rename from spring-caching/src/main/java/org/baeldung/caching/example/CustomerDataService.java rename to spring-caching/src/main/java/com/baeldung/caching/example/CustomerDataService.java index 1c595057a8..005a85fcb4 100644 --- a/spring-caching/src/main/java/org/baeldung/caching/example/CustomerDataService.java +++ b/spring-caching/src/main/java/com/baeldung/caching/example/CustomerDataService.java @@ -1,4 +1,4 @@ -package org.baeldung.caching.example; +package com.baeldung.caching.example; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; diff --git a/spring-caching/src/main/java/org/baeldung/caching/example/CustomerServiceWithParent.java b/spring-caching/src/main/java/com/baeldung/caching/example/CustomerServiceWithParent.java similarity index 86% rename from spring-caching/src/main/java/org/baeldung/caching/example/CustomerServiceWithParent.java rename to spring-caching/src/main/java/com/baeldung/caching/example/CustomerServiceWithParent.java index a5ded7daf9..be201413b4 100644 --- a/spring-caching/src/main/java/org/baeldung/caching/example/CustomerServiceWithParent.java +++ b/spring-caching/src/main/java/com/baeldung/caching/example/CustomerServiceWithParent.java @@ -1,4 +1,4 @@ -package org.baeldung.caching.example; +package com.baeldung.caching.example; import org.springframework.cache.annotation.CacheConfig; import org.springframework.stereotype.Component; diff --git a/spring-caching/src/main/java/com/baeldung/caching/model/Book.java b/spring-caching/src/main/java/com/baeldung/caching/model/Book.java new file mode 100644 index 0000000000..fd8abf1816 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/model/Book.java @@ -0,0 +1,41 @@ +package com.baeldung.caching.model; + +public class Book { + + private int id; + private String author; + private String title; + + public Book() { + } + + public Book(int id, String author, String title) { + this.id = id; + this.author = author; + this.title = title; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/spring-caching/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java b/spring-caching/src/main/java/com/baeldung/ehcache/calculator/SquaredCalculator.java similarity index 86% rename from spring-caching/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java rename to spring-caching/src/main/java/com/baeldung/ehcache/calculator/SquaredCalculator.java index 25957539df..caf1df2a1b 100644 --- a/spring-caching/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java +++ b/spring-caching/src/main/java/com/baeldung/ehcache/calculator/SquaredCalculator.java @@ -1,6 +1,6 @@ -package org.baeldung.ehcache.calculator; +package com.baeldung.ehcache.calculator; -import org.baeldung.ehcache.config.CacheHelper; +import com.baeldung.ehcache.config.CacheHelper; public class SquaredCalculator { private CacheHelper cache; diff --git a/spring-caching/src/main/java/org/baeldung/ehcache/config/CacheHelper.java b/spring-caching/src/main/java/com/baeldung/ehcache/config/CacheHelper.java similarity index 96% rename from spring-caching/src/main/java/org/baeldung/ehcache/config/CacheHelper.java rename to spring-caching/src/main/java/com/baeldung/ehcache/config/CacheHelper.java index 7f59ad8cfb..d138f6e84c 100644 --- a/spring-caching/src/main/java/org/baeldung/ehcache/config/CacheHelper.java +++ b/spring-caching/src/main/java/com/baeldung/ehcache/config/CacheHelper.java @@ -1,4 +1,4 @@ -package org.baeldung.ehcache.config; +package com.baeldung.ehcache.config; import org.ehcache.Cache; import org.ehcache.CacheManager; diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java new file mode 100644 index 0000000000..3da4c23e28 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java @@ -0,0 +1,28 @@ +package com.baeldung.multiplecachemanager.bo; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import com.baeldung.multiplecachemanager.entity.Customer; +import com.baeldung.multiplecachemanager.entity.Order; +import com.baeldung.multiplecachemanager.repository.CustomerDetailRepository; + +@Component +public class CustomerDetailBO { + + @Autowired + private CustomerDetailRepository customerDetailRepository; + + @Cacheable(cacheNames = "customers") + public Customer getCustomerDetail(Integer customerId) { + return customerDetailRepository.getCustomerDetail(customerId); + } + + @Cacheable(cacheNames = "customerOrders", cacheManager = "alternateCacheManager") + public List getCustomerOrders(Integer customerId) { + return customerDetailRepository.getCustomerOrders(customerId); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java new file mode 100644 index 0000000000..390881167f --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java @@ -0,0 +1,25 @@ +package com.baeldung.multiplecachemanager.bo; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import com.baeldung.multiplecachemanager.entity.Order; +import com.baeldung.multiplecachemanager.repository.OrderDetailRepository; + +@Component +public class OrderDetailBO { + + @Autowired + private OrderDetailRepository orderDetailRepository; + + @Cacheable(cacheNames = "orders", cacheResolver = "cacheResolver") + public Order getOrderDetail(Integer orderId) { + return orderDetailRepository.getOrderDetail(orderId); + } + + @Cacheable(cacheNames = "orderprice", cacheResolver = "cacheResolver") + public double getOrderPrice(Integer orderId) { + return orderDetailRepository.getOrderPrice(orderId); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java new file mode 100644 index 0000000000..247a9b596b --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java @@ -0,0 +1,40 @@ +package com.baeldung.multiplecachemanager.config; + +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CachingConfigurerSupport; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.caffeine.CaffeineCacheManager; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.cache.interceptor.CacheResolver; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +//import org.springframework.context.annotation.Primary; + +import com.github.benmanes.caffeine.cache.Caffeine; + +@Configuration +@EnableCaching +public class MultipleCacheManagerConfig extends CachingConfigurerSupport { + + @Bean + //@Primary + public CacheManager cacheManager() { + CaffeineCacheManager cacheManager = new CaffeineCacheManager("customers", "orders"); + cacheManager.setCaffeine(Caffeine.newBuilder() + .initialCapacity(200) + .maximumSize(500) + .weakKeys() + .recordStats()); + return cacheManager; + } + + @Bean + public CacheManager alternateCacheManager() { + return new ConcurrentMapCacheManager("customerOrders", "orderprice"); + } + + @Bean + public CacheResolver cacheResolver() { + return new MultipleCacheResolver(alternateCacheManager(), cacheManager()); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java new file mode 100644 index 0000000000..1bd869d98e --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java @@ -0,0 +1,38 @@ +package com.baeldung.multiplecachemanager.config; + +import java.util.ArrayList; +import java.util.Collection; + +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.interceptor.CacheOperationInvocationContext; +import org.springframework.cache.interceptor.CacheResolver; + +public class MultipleCacheResolver implements CacheResolver { + + private final CacheManager simpleCacheManager; + + private final CacheManager caffeineCacheManager; + + private static final String ORDER_CACHE = "orders"; + + private static final String ORDER_PRICE_CACHE = "orderprice"; + + public MultipleCacheResolver(CacheManager simpleCacheManager, CacheManager caffeineCacheManager) { + this.simpleCacheManager = simpleCacheManager; + this.caffeineCacheManager = caffeineCacheManager; + + } + + @Override + public Collection resolveCaches(CacheOperationInvocationContext context) { + Collection caches = new ArrayList(); + if ("getOrderDetail".equals(context.getMethod() + .getName())) { + caches.add(caffeineCacheManager.getCache(ORDER_CACHE)); + } else { + caches.add(simpleCacheManager.getCache(ORDER_PRICE_CACHE)); + } + return caches; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java new file mode 100644 index 0000000000..17a73bb27a --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java @@ -0,0 +1,43 @@ +package com.baeldung.multiplecachemanager.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.multiplecachemanager.bo.CustomerDetailBO; +import com.baeldung.multiplecachemanager.bo.OrderDetailBO; +import com.baeldung.multiplecachemanager.entity.Customer; +import com.baeldung.multiplecachemanager.entity.Order; + +@RestController +public class MultipleCacheManagerController { + + @Autowired + private CustomerDetailBO customerDetailBO; + + @Autowired + private OrderDetailBO orderDetailBO; + + @GetMapping(value = "/getCustomer/{customerid}") + public Customer getCustomer(@PathVariable Integer customerid) { + return customerDetailBO.getCustomerDetail(customerid); + } + + @GetMapping(value = "/getCustomerOrders/{customerid}") + public List getCustomerOrders(@PathVariable Integer customerid) { + return customerDetailBO.getCustomerOrders(customerid); + } + + @GetMapping(value = "/getOrder/{orderid}") + public Order getOrder(@PathVariable Integer orderid) { + return orderDetailBO.getOrderDetail(orderid); + } + + @GetMapping(value = "/getOrderPrice/{orderid}") + public double getOrderPrice(@PathVariable Integer orderid) { + return orderDetailBO.getOrderPrice(orderid); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java new file mode 100644 index 0000000000..cfae15f4e9 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java @@ -0,0 +1,24 @@ +package com.baeldung.multiplecachemanager.entity; + +public class Customer { + + private int customerId; + + private String customerName; + + public int getCustomerId() { + return customerId; + } + + public void setCustomerId(int customerId) { + this.customerId = customerId; + } + + public String getCustomerName() { + return customerName; + } + + public void setCustomerName(String customerName) { + this.customerName = customerName; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java new file mode 100644 index 0000000000..4131464981 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java @@ -0,0 +1,34 @@ +package com.baeldung.multiplecachemanager.entity; + +public class Item { + + private int itemId; + + private String itemDesc; + + private double itemPrice; + + public int getItemId() { + return itemId; + } + + public void setItemId(int itemId) { + this.itemId = itemId; + } + + public String getItemDesc() { + return itemDesc; + } + + public void setItemDesc(String itemDesc) { + this.itemDesc = itemDesc; + } + + public double getItemPrice() { + return itemPrice; + } + + public void setItemPrice(double itemPrice) { + this.itemPrice = itemPrice; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java new file mode 100644 index 0000000000..15da60d6ea --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java @@ -0,0 +1,44 @@ +package com.baeldung.multiplecachemanager.entity; + +public class Order { + + private int orderId; + + private int itemId; + + private int quantity; + + private int customerId; + + public int getOrderId() { + return orderId; + } + + public void setOrderId(int orderId) { + this.orderId = orderId; + } + + public int getItemId() { + return itemId; + } + + public void setItemId(int itemId) { + this.itemId = itemId; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public int getCustomerId() { + return customerId; + } + + public void setCustomerId(int customerId) { + this.customerId = customerId; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java new file mode 100644 index 0000000000..aab011427d --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java @@ -0,0 +1,49 @@ +package com.baeldung.multiplecachemanager.repository; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.stereotype.Repository; + +import com.baeldung.multiplecachemanager.entity.Customer; +import com.baeldung.multiplecachemanager.entity.Order; + +@Repository +public class CustomerDetailRepository { + + @Autowired + private JdbcTemplate jdbcTemplate; + + public Customer getCustomerDetail(Integer customerId) { + String customerQuery = "select * from customer where customerid = ? "; + Customer customer = new Customer(); + jdbcTemplate.query(customerQuery, new Object[] { customerId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + customer.setCustomerId(rs.getInt("customerid")); + customer.setCustomerName(rs.getString("customername")); + } + }); + return customer; + } + + public List getCustomerOrders(Integer customerId) { + String customerOrderQuery = "select * from orderdetail where customerid = ? "; + List orders = new ArrayList(); + jdbcTemplate.query(customerOrderQuery, new Object[] { customerId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + Order order = new Order(); + order.setCustomerId(rs.getInt("customerid")); + order.setItemId(rs.getInt("orderid")); + order.setOrderId(rs.getInt("orderid")); + order.setQuantity(rs.getInt("quantity")); + orders.add(order); + } + }); + return orders; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java new file mode 100644 index 0000000000..58c0968e48 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java @@ -0,0 +1,53 @@ +package com.baeldung.multiplecachemanager.repository; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.stereotype.Repository; + +import com.baeldung.multiplecachemanager.entity.Item; +import com.baeldung.multiplecachemanager.entity.Order; + +@Repository +public class OrderDetailRepository { + + @Autowired + private JdbcTemplate jdbcTemplate; + + public Order getOrderDetail(Integer orderId) { + String orderDetailQuery = "select * from orderdetail where orderid = ? "; + Order order = new Order(); + jdbcTemplate.query(orderDetailQuery, new Object[] { orderId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + order.setCustomerId(rs.getInt("customerid")); + order.setOrderId(rs.getInt("orderid")); + order.setItemId(rs.getInt("itemid")); + order.setQuantity(rs.getInt("quantity")); + } + }); + return order; + } + + public double getOrderPrice(Integer orderId) { + + String orderItemJoinQuery = "select * from ( select * from orderdetail where orderid = ? ) o left join item on o.itemid = ITEM.itemid"; + Order order = new Order(); + Item item = new Item(); + + jdbcTemplate.query(orderItemJoinQuery, new Object[] { orderId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + order.setCustomerId(rs.getInt("customerid")); + order.setOrderId(rs.getInt("orderid")); + order.setItemId(rs.getInt("itemid")); + order.setQuantity(rs.getInt("quantity")); + item.setItemDesc("itemdesc"); + item.setItemId(rs.getInt("itemid")); + item.setItemPrice(rs.getDouble("price")); + } + }); + return order.getQuantity() * item.getItemPrice(); + } +} diff --git a/spring-caching/src/main/java/org/baeldung/caching/example/AbstractService.java b/spring-caching/src/main/java/org/baeldung/caching/example/AbstractService.java deleted file mode 100644 index 02b8c3c159..0000000000 --- a/spring-caching/src/main/java/org/baeldung/caching/example/AbstractService.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.baeldung.caching.example; - -import org.springframework.cache.annotation.CacheEvict; -import org.springframework.cache.annotation.CachePut; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.cache.annotation.Caching; - -public abstract class AbstractService { - - // this method configuration is equivalent to xml configuration - @Cacheable(value = "addresses", key = "#customer.name") - public String getAddress(final Customer customer) { - return customer.getAddress(); - } - - /** - * The method returns the customer's address, - only it doesn't find it the cache- addresses and directory. - * - * @param customer the customer - * @return the address - */ - @Cacheable({ "addresses", "directory" }) - public String getAddress1(final Customer customer) { - return customer.getAddress(); - } - - /** - * The method returns the customer's address, - but refreshes all the entries in the cache to load new ones. - * - * @param customer the customer - * @return the address - */ - @CacheEvict(value = "addresses", allEntries = true) - public String getAddress2(final Customer customer) { - return customer.getAddress(); - } - - /** - * The method returns the customer's address, - but not before selectively evicting the cache as per specified paramters. - * - * @param customer the customer - * @return the address - */ - @Caching(evict = { @CacheEvict("addresses"), @CacheEvict(value = "directory", key = "#customer.name") }) - public String getAddress3(final Customer customer) { - return customer.getAddress(); - } - - /** - * The method uses the class level cache to look up for entries. - * - * @param customer the customer - * @return the address - */ - @Cacheable - // parameter not required as we have declared it using @CacheConfig - public String getAddress4(final Customer customer) { - return customer.getAddress(); - } - - /** - * The method selectively caches the results that meet the predefined criteria. - * - * @param customer the customer - * @return the address - */ - @CachePut(value = "addresses", condition = "#customer.name=='Tom'") - // @CachePut(value = "addresses", unless = "#result.length>64") - public String getAddress5(final Customer customer) { - return customer.getAddress(); - } - -} diff --git a/spring-caching/src/main/java/org/baeldung/caching/example/BookService.java b/spring-caching/src/main/java/org/baeldung/caching/example/BookService.java deleted file mode 100644 index 9f3aaf89cf..0000000000 --- a/spring-caching/src/main/java/org/baeldung/caching/example/BookService.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.caching.example; - -import org.baeldung.caching.model.Book; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.stereotype.Component; - -import java.util.ArrayList; -import java.util.List; - -@Component -public class BookService { - - @Cacheable(value="books", keyGenerator="customKeyGenerator") - public List getBooks() { - List books = new ArrayList(); - books.add(new Book(1, "The Counterfeiters", "André Gide")); - books.add(new Book(2, "Peer Gynt and Hedda Gabler", "Henrik Ibsen")); - return books; - } - -} diff --git a/spring-caching/src/main/java/org/baeldung/caching/example/Customer.java b/spring-caching/src/main/java/org/baeldung/caching/example/Customer.java deleted file mode 100644 index a57f08e35b..0000000000 --- a/spring-caching/src/main/java/org/baeldung/caching/example/Customer.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.baeldung.caching.example; - -public class Customer { - - private int id; - private String name; - private String address; - - public Customer() { - super(); - } - - public Customer(final String name, final String address) { - this.name = name; - this.address = address; - } - - // - - 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 getAddress() { - return address; - } - - public void setAddress(final String address) { - this.address = address; - } - - public void setCustomerAddress(final String address) { - this.address = name + "," + address; - } - -} diff --git a/spring-caching/src/main/java/org/baeldung/caching/model/Book.java b/spring-caching/src/main/java/org/baeldung/caching/model/Book.java deleted file mode 100644 index c110c79db0..0000000000 --- a/spring-caching/src/main/java/org/baeldung/caching/model/Book.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.caching.model; - -public class Book { - - private int id; - private String author; - private String title; - - public Book() { - } - - public Book(int id, String author, String title) { - this.id = id; - this.author = author; - this.title = title; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } -} diff --git a/spring-caching/src/main/resources/application.properties b/spring-caching/src/main/resources/application.properties new file mode 100644 index 0000000000..ee7b5e62c0 --- /dev/null +++ b/spring-caching/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= + +# Enabling H2 Console +spring.h2.console.enabled=true +spring.h2.console.path=/h2 diff --git a/spring-caching/src/main/resources/config.xml b/spring-caching/src/main/resources/config.xml index 23458539b0..666e91e173 100644 --- a/spring-caching/src/main/resources/config.xml +++ b/spring-caching/src/main/resources/config.xml @@ -13,7 +13,7 @@ - + @@ -34,7 +34,7 @@ - + diff --git a/spring-caching/src/main/resources/data.sql b/spring-caching/src/main/resources/data.sql new file mode 100644 index 0000000000..e4165ae71f --- /dev/null +++ b/spring-caching/src/main/resources/data.sql @@ -0,0 +1,7 @@ +INSERT INTO CUSTOMER VALUES(1001,'BAELDUNG'); + +INSERT INTO ITEM VALUES(10001,'ITEM1',50.0); +INSERT INTO ITEM VALUES(10002,'ITEM2',100.0); + +INSERT INTO ORDERDETAIL VALUES(300001,1001,10001,2); +INSERT INTO ORDERDETAIL VALUES(300002,1001,10002,5); \ No newline at end of file diff --git a/spring-caching/src/main/resources/schema.sql b/spring-caching/src/main/resources/schema.sql new file mode 100644 index 0000000000..5862499bc0 --- /dev/null +++ b/spring-caching/src/main/resources/schema.sql @@ -0,0 +1,19 @@ +CREATE TABLE CUSTOMER( + CUSTOMERID INT PRIMARY KEY, + CUSTOMERNAME VARCHAR(250) NOT NULL +); + +CREATE TABLE ITEM( +ITEMID INT PRIMARY KEY, +ITEMDESC VARCHAR(250), +PRICE DOUBLE +); + +CREATE TABLE ORDERDETAIL( +ORDERID INT PRIMARY KEY, +CUSTOMERID INT NOT NULL, +ITEMID INT NOT NULL, +QUANTITY INT, +FOREIGN KEY (customerid) references CUSTOMER(customerid), +FOREIGN KEY (itemid) references ITEM(itemid) +); \ No newline at end of file diff --git a/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java b/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java new file mode 100644 index 0000000000..3c83065c5c --- /dev/null +++ b/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.caching.boot; + +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.cache.CacheManager; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest("spring.cache.type=simple") +public class SimpleCacheCustomizerIntegrationTest { + + @Autowired + private CacheManager cacheManager; + + @Test + public void givenCacheManagerCustomizerWhenBootstrappedThenCacheManagerCustomized() { + assertThat(cacheManager.getCacheNames()) + .containsOnly(SimpleCacheCustomizer.USERS_CACHE, SimpleCacheCustomizer.TRANSACTIONS_CACHE); + } +} \ No newline at end of file diff --git a/spring-caching/src/test/java/org/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java b/spring-caching/src/test/java/com/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java similarity index 96% rename from spring-caching/src/test/java/org/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java rename to spring-caching/src/test/java/com/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java index 28b0d26bed..7363022268 100644 --- a/spring-caching/src/test/java/org/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java +++ b/spring-caching/src/test/java/com/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.caching.test; +package com.baeldung.caching.test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; @@ -7,7 +7,7 @@ import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; -import org.baeldung.caching.eviction.service.CachingService; +import com.baeldung.caching.eviction.service.CachingService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-caching/src/test/java/org/baeldung/caching/test/CacheManagerEvictIntegrationTest.java b/spring-caching/src/test/java/com/baeldung/caching/test/CacheManagerEvictIntegrationTest.java similarity index 97% rename from spring-caching/src/test/java/org/baeldung/caching/test/CacheManagerEvictIntegrationTest.java rename to spring-caching/src/test/java/com/baeldung/caching/test/CacheManagerEvictIntegrationTest.java index ffcc88febc..fa3168fc62 100644 --- a/spring-caching/src/test/java/org/baeldung/caching/test/CacheManagerEvictIntegrationTest.java +++ b/spring-caching/src/test/java/com/baeldung/caching/test/CacheManagerEvictIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.caching.test; +package com.baeldung.caching.test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; @@ -7,7 +7,7 @@ import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; -import org.baeldung.caching.eviction.service.CachingService; +import com.baeldung.caching.eviction.service.CachingService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-caching/src/test/java/org/baeldung/caching/test/SpringCachingIntegrationTest.java b/spring-caching/src/test/java/com/baeldung/caching/test/SpringCachingIntegrationTest.java similarity index 88% rename from spring-caching/src/test/java/org/baeldung/caching/test/SpringCachingIntegrationTest.java rename to spring-caching/src/test/java/com/baeldung/caching/test/SpringCachingIntegrationTest.java index 8c4ebaa7ec..080044f359 100644 --- a/spring-caching/src/test/java/org/baeldung/caching/test/SpringCachingIntegrationTest.java +++ b/spring-caching/src/test/java/com/baeldung/caching/test/SpringCachingIntegrationTest.java @@ -1,9 +1,9 @@ -package org.baeldung.caching.test; +package com.baeldung.caching.test; -import org.baeldung.caching.config.CachingConfig; -import org.baeldung.caching.example.Customer; -import org.baeldung.caching.example.CustomerDataService; -import org.baeldung.caching.example.CustomerServiceWithParent; +import com.baeldung.caching.config.CachingConfig; +import com.baeldung.caching.example.Customer; +import com.baeldung.caching.example.CustomerDataService; +import com.baeldung.caching.example.CustomerServiceWithParent; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-caching/src/test/java/org/baeldung/ehcache/SquareCalculatorUnitTest.java b/spring-caching/src/test/java/com/baeldung/ehcache/SquareCalculatorUnitTest.java similarity index 90% rename from spring-caching/src/test/java/org/baeldung/ehcache/SquareCalculatorUnitTest.java rename to spring-caching/src/test/java/com/baeldung/ehcache/SquareCalculatorUnitTest.java index 0e6ac6fd8e..37df749bab 100644 --- a/spring-caching/src/test/java/org/baeldung/ehcache/SquareCalculatorUnitTest.java +++ b/spring-caching/src/test/java/com/baeldung/ehcache/SquareCalculatorUnitTest.java @@ -1,7 +1,7 @@ -package org.baeldung.ehcache; +package com.baeldung.ehcache; -import org.baeldung.ehcache.calculator.SquaredCalculator; -import org.baeldung.ehcache.config.CacheHelper; +import com.baeldung.ehcache.calculator.SquaredCalculator; +import com.baeldung.ehcache.config.CacheHelper; import org.junit.Before; import org.junit.Test; diff --git a/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationUnitTest.java b/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationUnitTest.java new file mode 100644 index 0000000000..e02e5da246 --- /dev/null +++ b/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.multiplecachemanager; + +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.caffeine.CaffeineCache; +import org.springframework.util.Assert; + +import com.baeldung.multiplecachemanager.bo.OrderDetailBO; +import com.baeldung.multiplecachemanager.entity.Order; +import com.baeldung.multiplecachemanager.repository.OrderDetailRepository; + +@SpringBootApplication +@SpringBootTest +public class MultipleCacheManagerIntegrationUnitTest { + + @MockBean + private OrderDetailRepository orderDetailRepository; + + @Autowired + private OrderDetailBO orderDetailBO; + + @Autowired + private CacheManager cacheManager; + + @Autowired + private CacheManager alternateCacheManager; + + @Test + public void givenCacheResolverIsConfigured_whenCallGetOrderDetail_thenDataShouldBeInCaffieneCacheManager() { + Integer key = 30001; + cacheManager.getCache("orders") + .evict(key); + Order order = new Order(); + order.setCustomerId(1001); + order.setItemId(10001); + order.setOrderId(30001); + order.setQuantity(2); + Mockito.when(orderDetailRepository.getOrderDetail(key)) + .thenReturn(order); + orderDetailBO.getOrderDetail(key); + org.springframework.cache.caffeine.CaffeineCache cache = (CaffeineCache) cacheManager.getCache("orders"); + Assert.notNull(cache.get(key) + .get(), "caffieneCache should have had the data"); + } + + @Test + public void givenCacheResolverIsConfigured_whenCallGetOrderPrice_thenDataShouldBeInAlternateCacheManager() { + Integer key = 30001; + alternateCacheManager.getCache("orderprice") + .evict(key); + Mockito.when(orderDetailRepository.getOrderPrice(key)) + .thenReturn(500.0); + orderDetailBO.getOrderPrice(key); + Cache cache = alternateCacheManager.getCache("orderprice"); + Assert.notNull(cache.get(key) + .get(), "alternateCache should have had the data"); + } +} diff --git a/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..de1f96a168 --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,33 @@ +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; + +import com.baeldung.SpringCloudConfigClientApplication; + +/** + * This LiveTest requires: + * 1- The 'spring-cloud-bus/spring-cloud-config-server' service running, with valid Spring Cloud Config properties, for instance: + * 1.1- `spring.cloud.config.server.git.uri` pointing to a valid URI, which has `user.role` and `user.password` properties configured in a properties file. For example, to achieve this in a dev environment: + * 1.1.1- `cd my/custom/path` + * 1.1.2- `git init .` + * 1.1.3- `echo user.role=Programmer >> application.properties` + * 1.1.4- `echo user.password=d3v3L >> application.properties` + * 1.1.5- `git add .` + * 1.1.6- `git commit -m 'inital commit'` + * 1.1.7- 'spring-cloud-bus/spring-cloud-config-server' with property `spring.cloud.config.server.git.uri=my/custom/path` + * + * Note: This is enough to run the ContextTest successfully, but to get the full functionality shown in the related article, we'll need also a RabbitMQ instance running (e.g. `docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 -p 5672:5672 rabbitmq:3-management`) + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudConfigClientApplication.class) +public class SpringContextLiveTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index a401d41e1e..0000000000 --- a/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.SpringCloudConfigClientApplication; - -/** - * This LiveTest requires: - * 1- The 'spring-cloud-bus/spring-cloud-config-server' service running, with valid Spring Cloud Config properties, for instance: - * 1.1- `spring.cloud.config.server.git.uri` pointing to a valid URI, which has `user.role` and `user.password` properties configured in a properties file. For example, to achieve this in a dev environment: - * 1.1.1- `cd my/custom/path` - * 1.1.2- `git init .` - * 1.1.3- `echo user.role=Programmer >> application.properties` - * 1.1.4- `echo user.password=d3v3L >> application.properties` - * 1.1.5- `git add .` - * 1.1.6- `git commit -m 'inital commit'` - * 1.1.7- 'spring-cloud-bus/spring-cloud-config-server' with property `spring.cloud.config.server.git.uri=my/custom/path` - * - * Note: This is enough to run the ContextTest successfully, but to get the full functionality shown in the related article, we'll need also a RabbitMQ instance running (e.g. `docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 -p 5672:5672 rabbitmq:3-management`) - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringCloudConfigClientApplication.class) -public class SpringContextLiveTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0770db220c --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +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; + +import com.baeldung.SpringCloudConfigServerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudConfigServerApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 19ca53c4a7..0000000000 --- a/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.SpringCloudConfigServerApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringCloudConfigServerApplication.class) -public class SpringContextTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud-data-flow/batch-job/pom.xml b/spring-cloud-data-flow/batch-job/pom.xml index 1ed0017bc0..e11df0df8e 100644 --- a/spring-cloud-data-flow/batch-job/pom.xml +++ b/spring-cloud-data-flow/batch-job/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung.spring.cloud + com.baeldung.spring.cloud batch-job 0.0.1-SNAPSHOT batch-job 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/com/baeldung/spring/cloud/BatchJobApplication.java similarity index 91% rename from spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/BatchJobApplication.java rename to spring-cloud-data-flow/batch-job/src/main/java/com/baeldung/spring/cloud/BatchJobApplication.java index 30f6ff6897..6eea25f16f 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/com/baeldung/spring/cloud/BatchJobApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud; +package com.baeldung.spring.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; 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/com/baeldung/spring/cloud/JobConfiguration.java similarity index 95% rename from spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/JobConfiguration.java rename to spring-cloud-data-flow/batch-job/src/main/java/com/baeldung/spring/cloud/JobConfiguration.java index 7ce867b60a..ba30e54446 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/com/baeldung/spring/cloud/JobConfiguration.java @@ -1,39 +1,39 @@ -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; -import org.springframework.batch.core.step.tasklet.Tasklet; -import org.springframework.batch.repeat.RepeatStatus; -import org.springframework.beans.factory.annotation.Autowired; -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); - - @Autowired - public JobBuilderFactory jobBuilderFactory; - - @Autowired - public StepBuilderFactory stepBuilderFactory; - - @Bean - public Job job() { - return jobBuilderFactory.get("job").start(stepBuilderFactory.get("jobStep1").tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { - logger.info("Job was run"); - return RepeatStatus.FINISHED; - } - }).build()).build(); - } -} +package com.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; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.repeat.RepeatStatus; +import org.springframework.beans.factory.annotation.Autowired; +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); + + @Autowired + public JobBuilderFactory jobBuilderFactory; + + @Autowired + public StepBuilderFactory stepBuilderFactory; + + @Bean + public Job job() { + return jobBuilderFactory.get("job").start(stepBuilderFactory.get("jobStep1").tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + logger.info("Job was run"); + return RepeatStatus.FINISHED; + } + }).build()).build(); + } +} diff --git a/spring-cloud-data-flow/batch-job/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud-data-flow/batch-job/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0684c32c08 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import com.baeldung.spring.cloud.JobConfiguration; +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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/com/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java similarity index 92% rename from spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java rename to spring-cloud-data-flow/batch-job/src/test/java/com/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java index 1f77351acc..0209a0ba5c 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/com/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud; +package com.baeldung.spring.cloud; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 3ac11452d3..0000000000 --- a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.cloud.JobConfiguration; -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 SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/main/java/org/baeldung/spring/cloud/DataFlowServerApplication.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/main/java/com/baeldung/spring/cloud/DataFlowServerApplication.java similarity index 92% rename from spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/main/java/org/baeldung/spring/cloud/DataFlowServerApplication.java rename to spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/main/java/com/baeldung/spring/cloud/DataFlowServerApplication.java index 227c10b620..4d742b95c6 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/main/java/org/baeldung/spring/cloud/DataFlowServerApplication.java +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/main/java/com/baeldung/spring/cloud/DataFlowServerApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud; +package com.baeldung.spring.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d5b01c8b9c --- /dev/null +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import com.baeldung.spring.cloud.DataFlowServerApplication; +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(classes = DataFlowServerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/com/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java similarity index 97% rename from spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java rename to spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/com/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java index 9eba12fc12..68f0db60eb 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/com/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud; +package com.baeldung.spring.cloud; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 83cb8067cf..0000000000 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.cloud.DataFlowServerApplication; -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(classes = DataFlowServerApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/main/java/org/baeldung/spring/cloud/DataFlowShellApplication.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/main/java/com/baeldung/spring/cloud/DataFlowShellApplication.java similarity index 91% rename from spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/main/java/org/baeldung/spring/cloud/DataFlowShellApplication.java rename to spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/main/java/com/baeldung/spring/cloud/DataFlowShellApplication.java index 36c421f5bf..82335e792c 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/main/java/org/baeldung/spring/cloud/DataFlowShellApplication.java +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/main/java/com/baeldung/spring/cloud/DataFlowShellApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud; +package com.baeldung.spring.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..d899af69a3 --- /dev/null +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,26 @@ +package com.baeldung; + +import com.baeldung.spring.cloud.DataFlowShellApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * This live test requires: + * complete data-flow server and shell setup running + * + *
+ * For more info: + * https://www.baeldung.com/spring-cloud-data-flow-stream-processing + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = DataFlowShellApplication.class) +public class SpringContextLiveTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index 1784eb772a..0000000000 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.cloud.DataFlowShellApplication; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * This live test requires: - * complete data-flow server and shell setup running - * - *
- * For more info: - * https://www.baeldung.com/spring-cloud-data-flow-stream-processing - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = DataFlowShellApplication.class) -public class SpringContextLiveTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/main/java/org/baeldung/spring/cloud/LogSinkApplication.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/main/java/com/baeldung/spring/cloud/LogSinkApplication.java similarity index 95% rename from spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/main/java/org/baeldung/spring/cloud/LogSinkApplication.java rename to spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/main/java/com/baeldung/spring/cloud/LogSinkApplication.java index a2b9968539..b7fa0a8c85 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/main/java/org/baeldung/spring/cloud/LogSinkApplication.java +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/main/java/com/baeldung/spring/cloud/LogSinkApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud; +package com.baeldung.spring.cloud; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..844ab5f499 --- /dev/null +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.spring.cloud.LogSinkApplication; +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(classes = LogSinkApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 42903189d3..0000000000 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.cloud.LogSinkApplication; -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(classes = LogSinkApplication.class) -public class SpringContextTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/main/java/org/baeldung/spring/cloud/TimeProcessorApplication.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/main/java/com/baeldung/spring/cloud/TimeProcessorApplication.java similarity index 96% rename from spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/main/java/org/baeldung/spring/cloud/TimeProcessorApplication.java rename to spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/main/java/com/baeldung/spring/cloud/TimeProcessorApplication.java index 7a2763d436..161fd0ef23 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/main/java/org/baeldung/spring/cloud/TimeProcessorApplication.java +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/main/java/com/baeldung/spring/cloud/TimeProcessorApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud; +package com.baeldung.spring.cloud; import java.text.DateFormat; import java.text.SimpleDateFormat; diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..dc863bad07 --- /dev/null +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.spring.cloud.TimeProcessorApplication; +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(classes = TimeProcessorApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index d090e626d2..0000000000 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.cloud.TimeProcessorApplication; -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(classes = TimeProcessorApplication.class) -public class SpringContextTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/main/java/org/baeldung/spring/cloud/TimeSourceApplication.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/main/java/com/baeldung/spring/cloud/TimeSourceApplication.java similarity index 96% rename from spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/main/java/org/baeldung/spring/cloud/TimeSourceApplication.java rename to spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/main/java/com/baeldung/spring/cloud/TimeSourceApplication.java index 5bce39ebe0..e731b36e8a 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/main/java/org/baeldung/spring/cloud/TimeSourceApplication.java +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/main/java/com/baeldung/spring/cloud/TimeSourceApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud; +package com.baeldung.spring.cloud; import java.util.Date; diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a850707827 --- /dev/null +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.spring.cloud.TimeSourceApplication; +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(classes = TimeSourceApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e19b88de90..0000000000 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.cloud.TimeSourceApplication; -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(classes = TimeSourceApplication.class) -public class SpringContextTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 23ad11b03f..c4e606e190 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -35,7 +35,7 @@ spring-cloud-archaius spring-cloud-functions spring-cloud-vault - + spring-cloud-security spring-cloud-task spring-cloud-zuul spring-cloud-zuul-fallback diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3b32f2d9f4 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.cloud.archaius.basic.BasicArchaiusApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BasicArchaiusApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 7674713ff8..0000000000 --- a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.archaius.basic.BasicArchaiusApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BasicArchaiusApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..21bb7f87a4 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.cloud.archaius.extraconfigs.ExtraConfigsApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ExtraConfigsApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index a03bd8c23b..0000000000 --- a/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.archaius.extraconfigs.ExtraConfigsApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ExtraConfigsApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-aws/README.md b/spring-cloud/spring-cloud-aws/README.md index bf33728c74..ddcc97420f 100644 --- a/spring-cloud/spring-cloud-aws/README.md +++ b/spring-cloud/spring-cloud-aws/README.md @@ -23,7 +23,6 @@ Let's say that the RDS instance is called `spring-cloud-test-db` having the mast to write the following in `application.properties`: ``` -cloud.aws.rds.spring-cloud-test-db cloud.aws.rds.spring-cloud-test-db.password=se3retpass ``` Multiple application classes are available under this project. To launch InstanceProfileAwsApplication application, replace `start-class` under `pom.xml`: diff --git a/spring-cloud/spring-cloud-aws/pom.xml b/spring-cloud/spring-cloud-aws/pom.xml index c1fc458a24..2b05020888 100644 --- a/spring-cloud/spring-cloud-aws/pom.xml +++ b/spring-cloud/spring-cloud-aws/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -43,6 +43,12 @@ org.postgresql postgresql + + + mysql + mysql-connector-java + + @@ -50,7 +56,7 @@ org.springframework.cloud spring-cloud-aws - 2.0.1.RELEASE + ${spring-cloud} pom import @@ -60,6 +66,7 @@ com.baeldung.spring.cloud.aws.SpringCloudAwsApplication Dalston.SR4 + 2.2.1.RELEASE
diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3.java index cfad6e904f..acfd6d339e 100644 --- a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3.java +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3.java @@ -1,12 +1,5 @@ package com.baeldung.spring.cloud.aws.s3; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.core.io.WritableResource; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.stereotype.Component; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -14,14 +7,29 @@ import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.StandardCopyOption; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.aws.core.io.s3.PathMatchingSimpleStorageResourcePatternResolver; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.WritableResource; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.stereotype.Component; + +import com.amazonaws.services.s3.AmazonS3; + @Component public class SpringCloudS3 { @Autowired ResourceLoader resourceLoader; + private ResourcePatternResolver resourcePatternResolver; + @Autowired - ResourcePatternResolver resourcePatternResolver; + public void setupResolver(ApplicationContext applicationContext, AmazonS3 amazonS3) { + this.resourcePatternResolver = new PathMatchingSimpleStorageResourcePatternResolver(amazonS3, applicationContext); + } public void downloadS3Object(String s3Url) throws IOException { Resource resource = resourceLoader.getResource(s3Url); diff --git a/spring-cloud/spring-cloud-aws/src/main/resources/application.properties b/spring-cloud/spring-cloud-aws/src/main/resources/application.properties index 690eda13a2..e8139326b9 100644 --- a/spring-cloud/spring-cloud-aws/src/main/resources/application.properties +++ b/spring-cloud/spring-cloud-aws/src/main/resources/application.properties @@ -2,7 +2,6 @@ cloud.aws.credentials.accessKey=YourAccessKey cloud.aws.credentials.secretKey=YourSecretKey cloud.aws.region.static=us-east-1 -cloud.aws.rds.spring-cloud-test-db cloud.aws.rds.spring-cloud-test-db.password=se3retpass # These 3 properties are optional diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..35691c7aad --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.cloud.bootstrap.config.ConfigApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 98ae3e4895..0000000000 --- a/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.bootstrap.config.ConfigApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..2e7b52ac68 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,23 @@ +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; + +import com.baeldung.spring.cloud.bootstrap.discovery.DiscoveryApplication; + +/** + * + * This Live Test requires: + * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = DiscoveryApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index e4e2e95e04..0000000000 --- a/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.bootstrap.discovery.DiscoveryApplication; - -/** - * - * This Live Test requires: - * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = DiscoveryApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..f5c005b11f --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,23 @@ +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; + +import com.baeldung.spring.cloud.bootstrap.gateway.GatewayApplication; + +/** + * + * This Live Test requires: + * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GatewayApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index e0342cf82c..0000000000 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.bootstrap.gateway.GatewayApplication; - -/** - * - * This Live Test requires: - * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = GatewayApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..c5bbc74d95 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,23 @@ +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; + +import com.baeldung.spring.cloud.bootstrap.svcbook.BookServiceApplication; + +/** + * + * This Live Test requires: + * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookServiceApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index 2e437aa3f7..0000000000 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.bootstrap.svcbook.BookServiceApplication; - -/** - * - * This Live Test requires: - * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookServiceApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..fbd13720d2 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,24 @@ +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; + +import com.baeldung.spring.cloud.bootstrap.svcrating.RatingServiceApplication; + + +/** + * + * This Live Test requires: + * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = RatingServiceApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index e2921f0308..0000000000 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.bootstrap.svcrating.RatingServiceApplication; - - -/** - * - * This Live Test requires: - * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = RatingServiceApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..71e67df191 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.cloud.bootstrap.zipkin.ZipkinApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ZipkinApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 76b7539b6b..0000000000 --- a/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.bootstrap.zipkin.ZipkinApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ZipkinApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-circuit-breaker/README.md b/spring-cloud/spring-cloud-circuit-breaker/README.md new file mode 100644 index 0000000000..894be93408 --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/README.md @@ -0,0 +1,7 @@ +## Spring Cloud Circuit Breaker + +This module contains articles about Spring Cloud Circuit Breaker + +### Relevant Articles: + +- [Quick Guide to Spring Cloud Circuit Breaker](https://www.baeldung.com/spring-cloud-circuit-breaker) diff --git a/spring-cloud/spring-cloud-circuit-breaker/pom.xml b/spring-cloud/spring-cloud-circuit-breaker/pom.xml new file mode 100644 index 0000000000..188fc4bf8e --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + spring-cloud-circuit-breaker + spring-cloud-gateway + jar + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/libs-snapshot + + true + + + false + + + + + + + + org.springframework.boot + spring-boot-dependencies + 2.2.4.RELEASE + pom + import + + + + + + + org.springframework.cloud + spring-cloud-starter-circuitbreaker-resilience4j + 1.0.2.RELEASE + + + org.springframework.boot + spring-boot-starter-web + + + + diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/AlbumService.java b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/AlbumService.java new file mode 100644 index 0000000000..67163c8c9a --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/AlbumService.java @@ -0,0 +1,40 @@ +package com.baeldung.circuitbreaker; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.circuitbreaker.CircuitBreaker; +import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.nio.file.Files; +import java.nio.file.Paths; + +@Service +public class AlbumService { + + private static final Logger LOGGER = LoggerFactory.getLogger(AlbumService.class); + + @Autowired + private CircuitBreakerFactory circuitBreakerFactory; + + private RestTemplate restTemplate = new RestTemplate(); + + public String getAlbumList() { + CircuitBreaker circuitBreaker = circuitBreakerFactory.create("circuitbreaker"); + String url = "https://jsonplaceholder.typicode.com/albums"; + + return circuitBreaker.run(() -> restTemplate.getForObject(url, String.class), throwable -> getDefaultAlbumList()); + } + + private String getDefaultAlbumList() { + try { + return new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("fallback-album-list.json").toURI()))); + } catch (Exception e) { + LOGGER.error("error occurred while reading the file", e); + } + return null; + } + +} diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/Controller.java b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/Controller.java new file mode 100644 index 0000000000..10f7c57a7a --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/Controller.java @@ -0,0 +1,18 @@ +package com.baeldung.circuitbreaker; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class Controller { + + @Autowired + private AlbumService service; + + @GetMapping("/albums") + public String albums() { + return service.getAlbumList(); + } + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/SpringApp.java b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/SpringApp.java new file mode 100644 index 0000000000..f891e7693f --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/SpringApp.java @@ -0,0 +1,71 @@ +package com.baeldung.circuitbreaker; + +import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig; +import io.github.resilience4j.timelimiter.TimeLimiterConfig; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory; +import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder; +import org.springframework.cloud.client.circuitbreaker.Customizer; +import org.springframework.context.annotation.Bean; + +import java.time.Duration; + +@SpringBootApplication +public class SpringApp { + + public static void main(String[] args) { + SpringApplication.run(SpringApp.class, args); + } + + @Bean + public Customizer globalCustomConfiguration() { + TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() + .timeoutDuration(Duration.ofSeconds(4)) + .build(); + CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofMillis(1000)) + .slidingWindowSize(2) + .build(); + + return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id) + .timeLimiterConfig(timeLimiterConfig) + .circuitBreakerConfig(circuitBreakerConfig) + .build()); + } + + @Bean + public Customizer specificCustomConfiguration1() { + + TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() + .timeoutDuration(Duration.ofSeconds(4)) + .build(); + CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofMillis(1000)) + .slidingWindowSize(2) + .build(); + + return factory -> factory.configure(builder -> builder.circuitBreakerConfig(circuitBreakerConfig) + .timeLimiterConfig(timeLimiterConfig).build(), "circuitBreaker"); + } + + @Bean + public Customizer specificCustomConfiguration2() { + + TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() + .timeoutDuration(Duration.ofSeconds(4)) + .build(); + CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofMillis(1000)) + .slidingWindowSize(2) + .build(); + + return factory -> factory.configure(builder -> builder.circuitBreakerConfig(circuitBreakerConfig) + .timeLimiterConfig(timeLimiterConfig).build(), + "circuitBreaker1", "circuitBreaker2", "circuitBreaker3"); + } + +} diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/resources/fallback-album-list.json b/spring-cloud/spring-cloud-circuit-breaker/src/main/resources/fallback-album-list.json new file mode 100644 index 0000000000..001df7610a --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/resources/fallback-album-list.json @@ -0,0 +1,12 @@ +[ + { + "userId": 1, + "id": 1, + "title": "quidem molestiae enim" + }, + { + "userId": 1, + "id": 2, + "title": "sunt qui excepturi placeat culpa" + } +] \ 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 b1f6acd9fe..f7f5f84c56 100644 --- a/spring-cloud/spring-cloud-consul/pom.xml +++ b/spring-cloud/spring-cloud-consul/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-cloud-consul spring-cloud-consul jar diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b491597d0e --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.cloud.springcloudcontractconsumer.SpringCloudContractConsumerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudContractConsumerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e9098b1467..0000000000 --- a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.springcloudcontractconsumer.SpringCloudContractConsumerApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringCloudContractConsumerApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml index c41ad687ed..e909dbc253 100644 --- a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml @@ -36,7 +36,7 @@ org.springframework.cloud spring-cloud-contract-maven-plugin - 2.1.1.RELEASE + ${spring-cloud.version} true com.baeldung.spring.cloud.springcloudcontractproducer.BaseTestClass @@ -45,4 +45,8 @@ + + + 2.1.1.RELEASE + diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9542ddabb9 --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.cloud.springcloudcontractproducer.SpringCloudContractProducerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudContractProducerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 7d77cbbd7a..0000000000 --- a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.springcloudcontractproducer.SpringCloudContractProducerApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringCloudContractProducerApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-functions/pom.xml b/spring-cloud/spring-cloud-functions/pom.xml index 2e1b747c2e..03510d0504 100644 --- a/spring-cloud/spring-cloud-functions/pom.xml +++ b/spring-cloud/spring-cloud-functions/pom.xml @@ -65,7 +65,7 @@ org.springframework.boot.experimental spring-boot-thin-layout - 1.0.10.RELEASE + ${spring-boot-thin.version} @@ -88,6 +88,7 @@ 2.0.2 1.1.0 2.0.4.RELEASE + 1.0.10.RELEASE diff --git a/spring-cloud/spring-cloud-gateway/README.md b/spring-cloud/spring-cloud-gateway/README.md index e87bc547e1..9c8e0d443a 100644 --- a/spring-cloud/spring-cloud-gateway/README.md +++ b/spring-cloud/spring-cloud-gateway/README.md @@ -4,3 +4,5 @@ This module contains articles about Spring Cloud Gateway ### Relevant Articles: - [Exploring the new Spring Cloud Gateway](http://www.baeldung.com/spring-cloud-gateway) +- [Writing Custom Spring Cloud Gateway Filters](https://www.baeldung.com/spring-cloud-custom-gateway-filters) +- [Spring Cloud Gateway Routing Predicate Factories](https://www.baeldung.com/spring-cloud-gateway-routing-predicate-factories) diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index 10cd49cc04..c692eed7ec 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -1,7 +1,7 @@ + xmlns="http://maven.apache.org/POM/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 spring-cloud-gateway spring-cloud-gateway @@ -49,6 +49,26 @@ spring-cloud-starter-gateway + + + org.springframework.cloud + spring-cloud-starter-circuitbreaker-reactor-resilience4j + + + + + org.springframework.boot + spring-boot-starter-data-redis-reactive + + + + + it.ozimov + embedded-redis + ${redis.version} + test + + org.hibernate hibernate-validator-cdi @@ -68,6 +88,10 @@ spring-boot-starter-test test + + org.springframework.boot + spring-boot-devtools + @@ -80,11 +104,10 @@ - Greenwich.SR3 - - - 2.1.9.RELEASE + Hoxton.SR3 + 2.2.6.RELEASE 6.0.2.Final + 0.7.2 diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplication.java new file mode 100644 index 0000000000..e209b6cdf0 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.springcloudgateway.custompredicates; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; + +@SpringBootApplication +public class CustomPredicatesApplication { + + public static void main(String[] args) { + new SpringApplicationBuilder(CustomPredicatesApplication.class) + .profiles("customroutes") + .run(args); + } + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java new file mode 100644 index 0000000000..0e88b29bcf --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java @@ -0,0 +1,38 @@ +package com.baeldung.springcloudgateway.custompredicates.config; + +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.springcloudgateway.custompredicates.factories.GoldenCustomerRoutePredicateFactory; +import com.baeldung.springcloudgateway.custompredicates.factories.GoldenCustomerRoutePredicateFactory.Config; +import com.baeldung.springcloudgateway.custompredicates.service.GoldenCustomerService; + +@Configuration +public class CustomPredicatesConfig { + + + @Bean + public GoldenCustomerRoutePredicateFactory goldenCustomer(GoldenCustomerService goldenCustomerService) { + return new GoldenCustomerRoutePredicateFactory(goldenCustomerService); + } + + + //@Bean + public RouteLocator routes(RouteLocatorBuilder builder, GoldenCustomerRoutePredicateFactory gf ) { + + return builder.routes() + .route("dsl_golden_route", r -> r.path("/dsl_api/**") + .filters(f -> f.stripPrefix(1)) + .uri("https://httpbin.org") + .predicate(gf.apply(new Config(true, "customerId")))) + .route("dsl_common_route", r -> r.path("/dsl_api/**") + .filters(f -> f.stripPrefix(1)) + .uri("https://httpbin.org") + .predicate(gf.apply(new Config(false, "customerId")))) + .build(); + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/factories/GoldenCustomerRoutePredicateFactory.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/factories/GoldenCustomerRoutePredicateFactory.java new file mode 100644 index 0000000000..cb5c3a0b50 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/factories/GoldenCustomerRoutePredicateFactory.java @@ -0,0 +1,102 @@ +/** + * + */ +package com.baeldung.springcloudgateway.custompredicates.factories; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; + +import javax.validation.constraints.NotEmpty; + +import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory; +import org.springframework.http.HttpCookie; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.server.ServerWebExchange; + +import com.baeldung.springcloudgateway.custompredicates.service.GoldenCustomerService; + +/** + * @author Philippe + * + */ +public class GoldenCustomerRoutePredicateFactory extends AbstractRoutePredicateFactory { + + private final GoldenCustomerService goldenCustomerService; + + public GoldenCustomerRoutePredicateFactory(GoldenCustomerService goldenCustomerService ) { + super(Config.class); + this.goldenCustomerService = goldenCustomerService; + } + + + @Override + public List shortcutFieldOrder() { + return Arrays.asList("isGolden","customerIdCookie"); + } + + + @Override + public Predicate apply(Config config) { + + return (ServerWebExchange t) -> { + List cookies = t.getRequest() + .getCookies() + .get(config.getCustomerIdCookie()); + + boolean isGolden; + if ( cookies == null || cookies.isEmpty()) { + isGolden = false; + } + else { + String customerId = cookies.get(0).getValue(); + isGolden = goldenCustomerService.isGoldenCustomer(customerId); + } + + return config.isGolden()?isGolden:!isGolden; + }; + } + + + @Validated + public static class Config { + boolean isGolden = true; + + @NotEmpty + String customerIdCookie = "customerId"; + + + public Config() {} + + public Config( boolean isGolden, String customerIdCookie) { + this.isGolden = isGolden; + this.customerIdCookie = customerIdCookie; + } + + public boolean isGolden() { + return isGolden; + } + + public void setGolden(boolean value) { + this.isGolden = value; + } + + /** + * @return the customerIdCookie + */ + public String getCustomerIdCookie() { + return customerIdCookie; + } + + /** + * @param customerIdCookie the customerIdCookie to set + */ + public void setCustomerIdCookie(String customerIdCookie) { + this.customerIdCookie = customerIdCookie; + } + + + + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/service/GoldenCustomerService.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/service/GoldenCustomerService.java new file mode 100644 index 0000000000..82bf2e6ae9 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/service/GoldenCustomerService.java @@ -0,0 +1,26 @@ +/** + * + */ +package com.baeldung.springcloudgateway.custompredicates.service; + +import org.springframework.stereotype.Component; + +/** + * @author Philippe + * + */ +@Component +public class GoldenCustomerService { + + public boolean isGoldenCustomer(String customerId) { + + // TODO: Add some AI logic to check is this customer deserves a "golden" status ;^) + if ( "baeldung".equalsIgnoreCase(customerId)) { + return true; + } + else { + return false; + } + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java new file mode 100644 index 0000000000..852e5cadba --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.springcloudgateway.webfilters; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; + +@SpringBootApplication +public class WebFilterGatewayApplication { + + public static void main(String[] args) { + new SpringApplicationBuilder(WebFilterGatewayApplication.class) + .profiles("webfilters") + .run(args); + } + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/ModifyBodyRouteConfig.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/ModifyBodyRouteConfig.java new file mode 100644 index 0000000000..7b6188b66a --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/ModifyBodyRouteConfig.java @@ -0,0 +1,49 @@ +package com.baeldung.springcloudgateway.webfilters.config; + +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.MediaType; + +import reactor.core.publisher.Mono; + +@Configuration +public class ModifyBodyRouteConfig { + + @Bean + public RouteLocator routes(RouteLocatorBuilder builder) { + return builder.routes() + .route("modify_request_body", r -> r.path("/post") + .filters(f -> f.modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE, + (exchange, s) -> Mono.just(new Hello(s.toUpperCase())))).uri("https://httpbin.org")) + .build(); + } + + @Bean + public RouteLocator responseRoutes(RouteLocatorBuilder builder) { + return builder.routes() + .route("modify_response_body", r -> r.path("/put/**") + .filters(f -> f.modifyResponseBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE, + (exchange, s) -> Mono.just(new Hello("New Body")))).uri("https://httpbin.org")) + .build(); + } + + static class Hello { + String message; + + public Hello() { } + + public Hello(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + } +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/RequestRateLimiterResolverConfig.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/RequestRateLimiterResolverConfig.java new file mode 100644 index 0000000000..f80a742fa6 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/RequestRateLimiterResolverConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.springcloudgateway.webfilters.config; + +import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import reactor.core.publisher.Mono; + +@Configuration +public class RequestRateLimiterResolverConfig { + + @Bean + KeyResolver userKeyResolver() { + return exchange -> Mono.just("1"); + } +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-customroutes.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-customroutes.yml new file mode 100644 index 0000000000..859aa60bda --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-customroutes.yml @@ -0,0 +1,26 @@ +spring: + cloud: + gateway: + routes: + - id: golden_route + uri: https://httpbin.org + predicates: + - Path=/api/** + - GoldenCustomer=true + filters: + - StripPrefix=1 + - AddRequestHeader=GoldenCustomer,true + - id: common_route + uri: https://httpbin.org + predicates: + - Path=/api/** + - name: GoldenCustomer + args: + golden: false + customerIdCookie: customerId + filters: + - StripPrefix=1 + - AddRequestHeader=GoldenCustomer,false + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-webfilters.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-webfilters.yml new file mode 100644 index 0000000000..3348cbbba0 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-webfilters.yml @@ -0,0 +1,102 @@ +logging: + level: + org.springframework.cloud.gateway: INFO + reactor.netty.http.client: INFO + +spring: + redis: + host: localhost + port: 6379 + cloud: + gateway: + routes: + - id: request_header_route + uri: https://httpbin.org + predicates: + - Path=/get/** + filters: + - AddRequestHeader=My-Header-Good,Good + - AddRequestHeader=My-Header-Remove,Remove + - AddRequestParameter=var, good + - AddRequestParameter=var2, remove + - MapRequestHeader=My-Header-Good, My-Header-Bad + - MapRequestHeader=My-Header-Set, My-Header-Bad + - SetRequestHeader=My-Header-Set, Set + - RemoveRequestHeader=My-Header-Remove + - RemoveRequestParameter=var2 + - PreserveHostHeader + + - id: response_header_route + uri: https://httpbin.org + predicates: + - Path=/header/post/** + filters: + - AddResponseHeader=My-Header-Good,Good + - AddResponseHeader=My-Header-Set,Good + - AddResponseHeader=My-Header-Rewrite, password=12345678 + - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin + - AddResponseHeader=My-Header-Remove,Remove + - SetResponseHeader=My-Header-Set, Set + - RemoveResponseHeader=My-Header-Remove + - RewriteResponseHeader=My-Header-Rewrite, password=[^&]+, password=*** + - RewriteLocationResponseHeader=AS_IN_REQUEST, Location, , + - StripPrefix=1 + + - id: path_route + uri: https://httpbin.org + predicates: + - Path=/new/post/** + filters: + - RewritePath=/new(?/?.*), $\{segment} + - SetPath=/post + + - id: redirect_route + uri: https://httpbin.org + predicates: + - Path=/fake/post/** + filters: + - RedirectTo=302, https://httpbin.org + + - id: status_route + uri: https://httpbin.org + predicates: + - Path=/delete/** + filters: + - SetStatus=401 + + - id: size_route + uri: https://httpbin.org + predicates: + - Path=/anything + filters: + - name: RequestSize + args: + maxSize: 5000000 + + - id: retry_test + uri: https://httpbin.org + predicates: + - Path=/status/502 + filters: + - name: Retry + args: + retries: 3 + statuses: BAD_GATEWAY + methods: GET,POST + backoff: + firstBackoff: 10ms + maxBackoff: 50ms + factor: 2 + basedOnPreviousValue: false + + - id: request_rate_limiter + uri: https://httpbin.org + predicates: + - Path=/redis/get/** + filters: + - StripPrefix=1 + - name: RequestRateLimiter + args: + redis-rate-limiter.replenishRate: 10 + redis-rate-limiter.burstCapacity: 5 + key-resolver: "#{@userKeyResolver}" \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java index a4bb3f8068..f49f8c68b6 100644 --- a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; import org.assertj.core.api.Condition; import org.junit.jupiter.api.BeforeEach; 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.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; @@ -27,6 +28,7 @@ public class CustomFiltersLiveTest { @LocalServerPort String port; + @Autowired private WebTestClient client; @BeforeEach diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplicationLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplicationLiveTest.java new file mode 100644 index 0000000000..d9988ceb5e --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplicationLiveTest.java @@ -0,0 +1,67 @@ +package com.baeldung.springcloudgateway.custompredicates; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +import java.net.URI; + +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.junit.Before; +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.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; + +/** + * This test requires + */ +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("customroutes") +public class CustomPredicatesApplicationLiveTest { + + @LocalServerPort + String serverPort; + + @Autowired + private TestRestTemplate restTemplate; + + @Test + void givenNormalCustomer_whenCallHeadersApi_thenResponseForNormalCustomer() throws JSONException { + + String url = "http://localhost:" + serverPort + "/api/headers"; + ResponseEntity response = restTemplate.getForEntity(url, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + JSONObject headers = json.getJSONObject("headers"); + assertThat(headers.getString("Goldencustomer")).isEqualTo("false"); + + } + + @Test + void givenGoldenCustomer_whenCallHeadersApi_thenResponseForGoldenCustomer() throws JSONException { + + String url = "http://localhost:" + serverPort + "/api/headers"; + RequestEntity request = RequestEntity + .get(URI.create(url)) + .header("Cookie", "customerId=baeldung") + .build(); + + ResponseEntity response = restTemplate.exchange(request, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + JSONObject headers = json.getJSONObject("headers"); + assertThat(headers.getString("Goldencustomer")).isEqualTo("true"); + + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/RedisWebFilterFactoriesLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/RedisWebFilterFactoriesLiveTest.java new file mode 100644 index 0000000000..a28eb68775 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/RedisWebFilterFactoriesLiveTest.java @@ -0,0 +1,64 @@ +package com.baeldung.springcloudgateway.webfilters; + +import org.junit.After; +import org.junit.Before; +import org.junit.jupiter.api.RepeatedTest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; + +import redis.embedded.RedisServer; + +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("webfilters") +@TestConfiguration +public class RedisWebFilterFactoriesLiveTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(RedisWebFilterFactoriesLiveTest.class); + + private RedisServer redisServer; + + public RedisWebFilterFactoriesLiveTest() { + } + + @Before + public void postConstruct() { + this.redisServer = new RedisServer(6379); + redisServer.start(); + } + + @LocalServerPort + String port; + + @Autowired + private TestRestTemplate restTemplate; + + @Autowired + TestRestTemplate template; + + @RepeatedTest(25) + public void whenCallRedisGetThroughGateway_thenOKStatusOrIsReceived() { + String url = "http://localhost:" + port + "/redis/get"; + + ResponseEntity r = restTemplate.getForEntity(url, String.class); + // assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + LOGGER.info("Received: status->{}, reason->{}, remaining->{}", + r.getStatusCodeValue(), r.getStatusCode().getReasonPhrase(), + r.getHeaders().get("X-RateLimit-Remaining")); + } + + @After + public void preDestroy() { + redisServer.stop(); + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/WebFilterFactoriesLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/WebFilterFactoriesLiveTest.java new file mode 100644 index 0000000000..67e00a42fc --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/WebFilterFactoriesLiveTest.java @@ -0,0 +1,136 @@ +package com.baeldung.springcloudgateway.webfilters; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.assertj.core.api.Condition; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.jupiter.api.BeforeEach; +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.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +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.ActiveProfiles; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; + +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("webfilters") +public class WebFilterFactoriesLiveTest { + + @LocalServerPort + String port; + + @Autowired + private WebTestClient client; + + @Autowired + private TestRestTemplate restTemplate; + + @BeforeEach + public void configureClient() { + client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .build(); + } + + @Test + public void whenCallGetThroughGateway_thenAllHTTPRequestHeadersParametersAreSet() throws JSONException { + String url = "http://localhost:" + port + "/get"; + ResponseEntity response = restTemplate.getForEntity(url, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + JSONObject headers = json.getJSONObject("headers"); + assertThat(headers.getString("My-Header-Good")).isEqualTo("Good"); + assertThat(headers.getString("My-Header-Bad")).isEqualTo("Good"); + assertThat(headers.getString("My-Header-Set")).isEqualTo("Set"); + assertTrue(headers.isNull("My-Header-Remove")); + JSONObject vars = json.getJSONObject("args"); + assertThat(vars.getString("var")).isEqualTo("good"); + } + + @Test + public void whenCallHeaderPostThroughGateway_thenAllHTTPResponseHeadersAreSet() { + ResponseSpec response = client.post() + .uri("/header/post") + .exchange(); + + response.expectStatus() + .isOk() + .expectHeader() + .valueEquals("My-Header-Rewrite", "password=***") + .expectHeader() + .valueEquals("My-Header-Set", "Set") + .expectHeader() + .valueEquals("My-Header-Good", "Good") + .expectHeader() + .doesNotExist("My-Header-Remove"); + } + + @Test + public void whenCallPostThroughGateway_thenBodyIsRetrieved() throws JSONException { + String url = "http://localhost:" + port + "/post"; + + HttpEntity entity = new HttpEntity<>("content", new HttpHeaders()); + + ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + JSONObject data = json.getJSONObject("json"); + assertThat(data.getString("message")).isEqualTo("CONTENT"); + } + + @Test + public void whenCallPutThroughGateway_thenBodyIsRetrieved() throws JSONException { + String url = "http://localhost:" + port + "/put"; + + HttpEntity entity = new HttpEntity<>("CONTENT", new HttpHeaders()); + + ResponseEntity response = restTemplate.exchange(url, HttpMethod.PUT, entity, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + assertThat(json.getString("message")).isEqualTo("New Body"); + } + + @Test + public void whenCallDeleteThroughGateway_thenIsUnauthorizedCodeIsSet() { + ResponseSpec response = client.delete() + .uri("/delete") + .exchange(); + + response.expectStatus() + .isUnauthorized(); + } + + @Test + public void whenCallFakePostThroughGateway_thenIsUnauthorizedCodeIsSet() { + ResponseSpec response = client.post() + .uri("/fake/post") + .exchange(); + + response.expectStatus() + .is3xxRedirection(); + } + + @Test + public void whenCallStatus504ThroughGateway_thenCircuitBreakerIsExecuted() throws JSONException { + String url = "http://localhost:" + port + "/status/504"; + ResponseEntity response = restTemplate.getForEntity(url, String.class); + + JSONObject json = new JSONObject(response.getBody()); + assertThat(json.getString("url")).contains("anything"); + } +} diff --git a/spring-cloud/spring-cloud-gateway/src/test/resources/logback-test.xml b/spring-cloud/spring-cloud-gateway/src/test/resources/logback-test.xml index 6fcdb6317f..6980d119b1 100644 --- a/spring-cloud/spring-cloud-gateway/src/test/resources/logback-test.xml +++ b/spring-cloud/spring-cloud-gateway/src/test/resources/logback-test.xml @@ -3,7 +3,15 @@ + + + %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/kubernetes-guide/client-service/pom.xml b/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/client-service/pom.xml index e5f76d5d9c..07de78a92e 100644 --- a/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/client-service/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/client-service/pom.xml @@ -89,7 +89,7 @@ - Finchley.SR2 + Hoxton.SR1 1.0.0.RELEASE diff --git a/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/client-service/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/client-service/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8539e2af45 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/client-service/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.cloud.kubernetes.client.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/client-service/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/client-service/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index af59614f7c..0000000000 --- a/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/client-service/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.kubernetes.client.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void contextLoads() { - } -} diff --git a/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/travel-agency-service/pom.xml b/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/travel-agency-service/pom.xml index 93734a19a7..5459b77682 100644 --- a/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/travel-agency-service/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/kubernetes-guide/travel-agency-service/pom.xml @@ -24,7 +24,7 @@ ch.qos.logback logback-classic - 1.2.3 + ${logback.version} @@ -71,6 +71,7 @@ Finchley.SR2 + 1.2.3 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..837c24264c --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +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; + +import com.baeldung.spring.cloud.kubernetes.backend.KubernetesBackendApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KubernetesBackendApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index af393cb697..0000000000 --- a/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.kubernetes.backend.KubernetesBackendApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = KubernetesBackendApplication.class) -public class SpringContextTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1bf977a606 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +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; + +import com.baeldung.spring.cloud.kubernetes.frontend.KubernetesFrontendApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KubernetesFrontendApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 17cb5a5f39..0000000000 --- a/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.kubernetes.frontend.KubernetesFrontendApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = KubernetesFrontendApplication.class) -public class SpringContextTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/spring-cloud-openfeign/pom.xml b/spring-cloud/spring-cloud-openfeign/pom.xml index e20fe338c1..df529d7fb1 100644 --- a/spring-cloud/spring-cloud-openfeign/pom.xml +++ b/spring-cloud/spring-cloud-openfeign/pom.xml @@ -3,9 +3,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.cloud - openfeign + spring-cloud-openfeign 0.0.1-SNAPSHOT - openfeign + spring-cloud-openfeign OpenFeign project for Spring Boot diff --git a/spring-cloud/spring-cloud-rest/pom.xml b/spring-cloud/spring-cloud-rest/pom.xml index 8677b742de..1136fca020 100644 --- a/spring-cloud/spring-cloud-rest/pom.xml +++ b/spring-cloud/spring-cloud-rest/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-cloud-rest 1.0.0-SNAPSHOT spring-cloud-rest 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 b34e325eb8..042f7657ab 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 @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-cloud-rest-books-api 0.0.1-SNAPSHOT spring-cloud-rest-books-api diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/BooksApiApplication.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/BooksApiApplication.java similarity index 94% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/BooksApiApplication.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/BooksApiApplication.java index 3a843ba3fb..abcbabe737 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/BooksApiApplication.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/BooksApiApplication.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/SessionConfig.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/SessionConfig.java new file mode 100644 index 0000000000..6c984fb6d5 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/SessionConfig.java @@ -0,0 +1,8 @@ +package com.baeldung; + +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; + +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/persistence/dao/BookRepository.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/persistence/dao/BookRepository.java new file mode 100644 index 0000000000..434d4332f7 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/persistence/dao/BookRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.Book; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +@RepositoryRestResource(collectionResourceRel = "books", path = "books") +public interface BookRepository extends CrudRepository { + Page findByTitle(@Param("title") String title, Pageable pageable); +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/persistence/model/Book.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/persistence/model/Book.java new file mode 100644 index 0000000000..26fe3625ec --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/com/baeldung/persistence/model/Book.java @@ -0,0 +1,111 @@ +package com.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Book { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false, unique = true) + private String title; + + @Column(nullable = false) + private String author; + + // + + public Book() { + super(); + } + + public Book(String title, String author) { + super(); + this.title = title; + this.author = 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; + } + final 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() { + final StringBuilder builder = new StringBuilder(); + builder.append("Book [id=").append(id).append(", title=").append(title).append(", author=").append(author).append("]"); + return builder.toString(); + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/SessionConfig.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/SessionConfig.java deleted file mode 100644 index bd1c0013ca..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/SessionConfig.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung; - -import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; -import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; - -@EnableRedisHttpSession -public class SessionConfig extends AbstractHttpSessionApplicationInitializer { -} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/persistence/dao/BookRepository.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/persistence/dao/BookRepository.java deleted file mode 100644 index 1b0c32218f..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/persistence/dao/BookRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.Book; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.data.rest.core.annotation.RepositoryRestResource; - -@RepositoryRestResource(collectionResourceRel = "books", path = "books") -public interface BookRepository extends CrudRepository { - Page findByTitle(@Param("title") String title, Pageable pageable); -} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/persistence/model/Book.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/persistence/model/Book.java deleted file mode 100644 index ad5630ea33..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/java/org/baeldung/persistence/model/Book.java +++ /dev/null @@ -1,111 +0,0 @@ -package org.baeldung.persistence.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Book { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - @Column(nullable = false, unique = true) - private String title; - - @Column(nullable = false) - private String author; - - // - - public Book() { - super(); - } - - public Book(String title, String author) { - super(); - this.title = title; - this.author = 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; - } - final 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() { - final StringBuilder builder = new StringBuilder(); - builder.append("Book [id=").append(id).append(", title=").append(title).append(", author=").append(author).append("]"); - return builder.toString(); - } - -} 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/com/baeldung/BooksApiIntegrationTest.java similarity index 98% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/BooksApiIntegrationTest.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/com/baeldung/BooksApiIntegrationTest.java index 15056e110c..2a90b668cb 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/com/baeldung/BooksApiIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/com/baeldung/RestApiLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/com/baeldung/RestApiLiveTest.java new file mode 100644 index 0000000000..4184b3aef7 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/com/baeldung/RestApiLiveTest.java @@ -0,0 +1,156 @@ +package com.baeldung; + +import static io.restassured.RestAssured.preemptive; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.baeldung.BooksApiApplication; +import io.restassured.RestAssured; +import io.restassured.response.Response; + +import com.baeldung.persistence.model.Book; +import org.junit.Before; +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.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { BooksApiApplication.class }, webEnvironment = WebEnvironment.DEFINED_PORT) +public class RestApiLiveTest { + + private static final String API_URI = "http://localhost:8084/books"; + + @Before + public void setUp() { + RestAssured.authentication = preemptive().basic("user", "userPass"); + } + + // GET + + @Test + public void whenGetAllBooks_thenOK() { + final Response response = RestAssured.get(API_URI); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + } + + @Test + public void whenGetCreatedBookById_thenOK() { + final Book book = createRandomBook(); + final String location = createBookAsUri(book); + + final Response response = RestAssured.get(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertEquals(book.getTitle(), response.jsonPath().get("title")); + } + + @Test + public void whenGetCreatedBookByName_thenOK() { + final Book book = createRandomBook(); + createBookAsUri(book); + + final Response response = RestAssured.get(API_URI + "/search/findByTitle?title=" + book.getTitle()); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertTrue(response.jsonPath().getLong("page.totalElements") > 0); + } + + @Test + public void whenGetNotExistBookById_thenNotFound() { + final Response response = RestAssured.get(API_URI + "/" + randomNumeric(4)); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + @Test + public void whenGetNotExistBookByName_thenNotFound() { + final Response response = RestAssured.get(API_URI + "/search/findByTitle?title=" + randomAlphabetic(20)); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertTrue(response.jsonPath().getLong("page.totalElements") == 0); + } + + // POST + @Test + public void whenCreateNewBook_thenCreated() { + final Book book = createRandomBook(); + + final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI); + assertEquals(HttpStatus.CREATED.value(), response.getStatusCode()); + } + + @Test + public void whenCreateDuplicateBook_thenError() { + final Book book = createRandomBook(); + createBookAsUri(book); + + // duplicate + final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI); + assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode()); + } + + @Test + public void whenInvalidBook_thenError() { + final Book book = createRandomBook(); + book.setAuthor(null); + + final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI); + assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode()); + } + + @Test + public void whenUpdateCreatedBook_thenUpdated() { + // create + final Book book = createRandomBook(); + final String location = createBookAsUri(book); + + // update + book.setAuthor("newAuthor"); + Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).put(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + + // check if changes saved + response = RestAssured.get(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertEquals("newAuthor", response.jsonPath().get("author")); + + } + + @Test + public void whenDeleteCreatedBook_thenOk() { + // create + final Book book = createRandomBook(); + final String location = createBookAsUri(book); + + // delete + Response response = RestAssured.delete(location); + assertEquals(HttpStatus.NO_CONTENT.value(), response.getStatusCode()); + + // confirm it was deleted + response = RestAssured.get(location); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + @Test + public void whenDeleteNotExistBook_thenError() { + final Response response = RestAssured.delete(API_URI + "/" + randomNumeric(4)); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + // =============================== Util + + private Book createRandomBook() { + final Book book = new Book(); + book.setTitle(randomAlphabetic(10)); + book.setAuthor(randomAlphabetic(15)); + return book; + } + + private String createBookAsUri(Book book) { + final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI); + return response.jsonPath().get("_links.self.href"); + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SessionLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/com/baeldung/SessionLiveTest.java similarity index 95% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SessionLiveTest.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/com/baeldung/SessionLiveTest.java index 3e5fa4f046..9869a650b4 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SessionLiveTest.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/com/baeldung/SessionLiveTest.java @@ -1,7 +1,10 @@ -package org.baeldung; +package com.baeldung; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; + +import com.baeldung.BooksApiApplication; +import com.baeldung.SessionConfig; import io.restassured.RestAssured; import io.restassured.response.Response; diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..783c2f99c0 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,22 @@ +package com.baeldung; + +import com.baeldung.BooksApiApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * + * This Live Test requires: + * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BooksApiApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/RestApiLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/RestApiLiveTest.java deleted file mode 100644 index 830ec96e08..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/RestApiLiveTest.java +++ /dev/null @@ -1,154 +0,0 @@ -package org.baeldung; - -import static io.restassured.RestAssured.preemptive; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import io.restassured.RestAssured; -import io.restassured.response.Response; - -import org.baeldung.persistence.model.Book; -import org.junit.Before; -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.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = { BooksApiApplication.class }, webEnvironment = WebEnvironment.DEFINED_PORT) -public class RestApiLiveTest { - - private static final String API_URI = "http://localhost:8084/books"; - - @Before - public void setUp() { - RestAssured.authentication = preemptive().basic("user", "userPass"); - } - - // GET - - @Test - public void whenGetAllBooks_thenOK() { - final Response response = RestAssured.get(API_URI); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - } - - @Test - public void whenGetCreatedBookById_thenOK() { - final Book book = createRandomBook(); - final String location = createBookAsUri(book); - - final Response response = RestAssured.get(location); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - assertEquals(book.getTitle(), response.jsonPath().get("title")); - } - - @Test - public void whenGetCreatedBookByName_thenOK() { - final Book book = createRandomBook(); - createBookAsUri(book); - - final Response response = RestAssured.get(API_URI + "/search/findByTitle?title=" + book.getTitle()); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - assertTrue(response.jsonPath().getLong("page.totalElements") > 0); - } - - @Test - public void whenGetNotExistBookById_thenNotFound() { - final Response response = RestAssured.get(API_URI + "/" + randomNumeric(4)); - assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); - } - - @Test - public void whenGetNotExistBookByName_thenNotFound() { - final Response response = RestAssured.get(API_URI + "/search/findByTitle?title=" + randomAlphabetic(20)); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - assertTrue(response.jsonPath().getLong("page.totalElements") == 0); - } - - // POST - @Test - public void whenCreateNewBook_thenCreated() { - final Book book = createRandomBook(); - - final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI); - assertEquals(HttpStatus.CREATED.value(), response.getStatusCode()); - } - - @Test - public void whenCreateDuplicateBook_thenError() { - final Book book = createRandomBook(); - createBookAsUri(book); - - // duplicate - final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI); - assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode()); - } - - @Test - public void whenInvalidBook_thenError() { - final Book book = createRandomBook(); - book.setAuthor(null); - - final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI); - assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode()); - } - - @Test - public void whenUpdateCreatedBook_thenUpdated() { - // create - final Book book = createRandomBook(); - final String location = createBookAsUri(book); - - // update - book.setAuthor("newAuthor"); - Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).put(location); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - - // check if changes saved - response = RestAssured.get(location); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - assertEquals("newAuthor", response.jsonPath().get("author")); - - } - - @Test - public void whenDeleteCreatedBook_thenOk() { - // create - final Book book = createRandomBook(); - final String location = createBookAsUri(book); - - // delete - Response response = RestAssured.delete(location); - assertEquals(HttpStatus.NO_CONTENT.value(), response.getStatusCode()); - - // confirm it was deleted - response = RestAssured.get(location); - assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); - } - - @Test - public void whenDeleteNotExistBook_thenError() { - final Response response = RestAssured.delete(API_URI + "/" + randomNumeric(4)); - assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); - } - - // =============================== Util - - private Book createRandomBook() { - final Book book = new Book(); - book.setTitle(randomAlphabetic(10)); - book.setAuthor(randomAlphabetic(15)); - return book; - } - - private String createBookAsUri(Book book) { - final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI); - return response.jsonPath().get("_links.self.href"); - } - -} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index eb56c16c6a..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * - * This Live Test requires: - * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BooksApiApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} 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 b3bb6fafdc..5fb9364752 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 @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-cloud-rest-config-server 0.0.1-SNAPSHOT spring-cloud-rest-config-server diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/main/java/org/baeldung/SpringCloudRestConfigApplication.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/main/java/com/baeldung/SpringCloudRestConfigApplication.java similarity index 95% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/main/java/org/baeldung/SpringCloudRestConfigApplication.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/main/java/com/baeldung/SpringCloudRestConfigApplication.java index 90c6fe3ec9..d49a21f4ed 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/main/java/org/baeldung/SpringCloudRestConfigApplication.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/main/java/com/baeldung/SpringCloudRestConfigApplication.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1548d6a95e --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +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(classes = SpringCloudRestConfigApplication.class) +public class SpringContextTest { + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 1b4083e7a6..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.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(classes = SpringCloudRestConfigApplication.class) -public class SpringContextTest { - @Test - public void contextLoads() { - } - -} 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 aec51ca38a..5e35a7c0f5 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 @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-cloud-rest-discovery-server 0.0.1-SNAPSHOT spring-cloud-rest-discovery-server diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/com/baeldung/SessionConfig.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/com/baeldung/SessionConfig.java new file mode 100644 index 0000000000..6c984fb6d5 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/com/baeldung/SessionConfig.java @@ -0,0 +1,8 @@ +package com.baeldung; + +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; + +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/org/baeldung/SpringCloudRestServerApplication.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/com/baeldung/SpringCloudRestServerApplication.java similarity index 95% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/org/baeldung/SpringCloudRestServerApplication.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/com/baeldung/SpringCloudRestServerApplication.java index 2845ccf961..1cc0f2982c 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/org/baeldung/SpringCloudRestServerApplication.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/com/baeldung/SpringCloudRestServerApplication.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/org/baeldung/SessionConfig.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/org/baeldung/SessionConfig.java deleted file mode 100644 index bd1c0013ca..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/java/org/baeldung/SessionConfig.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung; - -import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; -import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; - -@EnableRedisHttpSession -public class SessionConfig extends AbstractHttpSessionApplicationInitializer { -} 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/com/baeldung/SpringCloudRestServerIntegrationTest.java similarity index 98% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringCloudRestServerIntegrationTest.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/com/baeldung/SpringCloudRestServerIntegrationTest.java index 14597d5c2f..1ee895b6b1 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/com/baeldung/SpringCloudRestServerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..92acd482cd --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,21 @@ +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; + +/** + * + * This Live Test requires: + * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudRestServerApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index 01266a3bda..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * - * This Live Test requires: - * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringCloudRestServerApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} 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 161b996496..7503418ad2 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 @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-cloud-rest-reviews-api 0.0.1-SNAPSHOT spring-cloud-rest-reviews-api diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/BookReviewsApiApplication.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/BookReviewsApiApplication.java similarity index 94% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/BookReviewsApiApplication.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/BookReviewsApiApplication.java index f3b05e95b1..707c97cb69 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/BookReviewsApiApplication.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/BookReviewsApiApplication.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/SessionConfig.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/SessionConfig.java new file mode 100644 index 0000000000..6c984fb6d5 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/SessionConfig.java @@ -0,0 +1,8 @@ +package com.baeldung; + +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; + +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/persistence/dao/BookReviewRepository.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/persistence/dao/BookReviewRepository.java similarity index 85% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/persistence/dao/BookReviewRepository.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/persistence/dao/BookReviewRepository.java index 2107786d62..1f29b66867 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/persistence/dao/BookReviewRepository.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/persistence/dao/BookReviewRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.dao; +package com.baeldung.persistence.dao; -import org.baeldung.persistence.model.BookReview; +import com.baeldung.persistence.model.BookReview; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.CrudRepository; diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/persistence/model/BookReview.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/persistence/model/BookReview.java similarity index 98% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/persistence/model/BookReview.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/persistence/model/BookReview.java index d8d6aa4fef..4b6ff7f32b 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/persistence/model/BookReview.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/com/baeldung/persistence/model/BookReview.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.model; +package com.baeldung.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/SessionConfig.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/SessionConfig.java deleted file mode 100644 index bd1c0013ca..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/java/org/baeldung/SessionConfig.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung; - -import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; -import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; - -@EnableRedisHttpSession -public class SessionConfig extends AbstractHttpSessionApplicationInitializer { -} 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/com/baeldung/BookReviewsApiIntegrationTest.java similarity index 98% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/BookReviewsApiIntegrationTest.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/com/baeldung/BookReviewsApiIntegrationTest.java index c63b4ebb08..7d7867f9ac 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/com/baeldung/BookReviewsApiIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/com/baeldung/RestApiLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/com/baeldung/RestApiLiveTest.java new file mode 100644 index 0000000000..88f845adcc --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/com/baeldung/RestApiLiveTest.java @@ -0,0 +1,147 @@ +package com.baeldung; + +import static io.restassured.RestAssured.preemptive; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.baeldung.BookReviewsApiApplication; +import io.restassured.RestAssured; +import io.restassured.response.Response; + +import com.baeldung.persistence.model.BookReview; +import org.junit.Before; +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.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { BookReviewsApiApplication.class }, webEnvironment = WebEnvironment.DEFINED_PORT) +public class RestApiLiveTest { + + private static final String API_URI = "http://localhost:8085/reviews"; + + @Before + public void setUp() { + RestAssured.authentication = preemptive().basic("user", "userPass"); + } + + // GET + + @Test + public void whenGetAllReviews_thenOK() { + final Response response = RestAssured.get(API_URI); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + } + + @Test + public void whenGetCreatedReviewById_thenOK() { + final BookReview review = createRandomReview(); + final String location = createReviewAsUri(review); + + final Response response = RestAssured.get(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertEquals(review.getContent(), response.jsonPath().get("content")); + } + + @Test + public void whenGetCreatedReviewByBookId_thenOK() { + final BookReview review = createRandomReview(); + createReviewAsUri(review); + + final Response response = RestAssured.get(API_URI + "/search/findByBookId?bookId=" + review.getBookId()); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertTrue(response.jsonPath().getLong("page.totalElements") > 0); + } + + @Test + public void whenGetNotExistReviewById_thenNotFound() { + final Response response = RestAssured.get(API_URI + "/" + randomNumeric(4)); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + @Test + public void whenGetNotExistReviewByBookId_thenNotFound() { + final Response response = RestAssured.get(API_URI + "/search/findByBookId?bookId=" + randomNumeric(4)); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertTrue(response.jsonPath().getLong("page.totalElements") == 0); + } + + // POST + @Test + public void whenCreateNewReview_thenCreated() { + final BookReview review = createRandomReview(); + + final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(review).post(API_URI); + assertEquals(HttpStatus.CREATED.value(), response.getStatusCode()); + } + + @Test + public void whenCreateInvalidReview_thenError() { + final BookReview review = createRandomReview(); + review.setBookId(null); + + final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(review).post(API_URI); + assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode()); + } + + @Test + public void whenUpdateCreatedReview_thenUpdated() { + // create + final BookReview review = createRandomReview(); + final String location = createReviewAsUri(review); + + // update + review.setRating(4); + Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(review).put(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + + // check if changes saved + response = RestAssured.get(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertEquals(4, response.jsonPath().getInt("rating")); + + } + + @Test + public void whenDeleteCreatedReview_thenOk() { + // create + final BookReview review = createRandomReview(); + final String location = createReviewAsUri(review); + + // delete + Response response = RestAssured.delete(location); + assertEquals(HttpStatus.NO_CONTENT.value(), response.getStatusCode()); + + // confirm it was deleted + response = RestAssured.get(location); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + @Test + public void whenDeleteNotExistReview_thenError() { + final Response response = RestAssured.delete(API_URI + "/" + randomNumeric(4)); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + // =============================== Util + + private BookReview createRandomReview() { + final BookReview review = new BookReview(); + review.setContent(randomAlphabetic(10)); + review.setRating(3); + review.setBookId(1L); + return review; + } + + private String createReviewAsUri(BookReview review) { + final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(review).post(API_URI); + return response.jsonPath().get("_links.self.href"); + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..6bb75ed1eb --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,22 @@ +package com.baeldung; + +import com.baeldung.BookReviewsApiApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * + * This Live Test requires: + * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookReviewsApiApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/RestApiLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/RestApiLiveTest.java deleted file mode 100644 index 91f76d386a..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/RestApiLiveTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package org.baeldung; - -import static io.restassured.RestAssured.preemptive; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import io.restassured.RestAssured; -import io.restassured.response.Response; - -import org.baeldung.persistence.model.BookReview; -import org.junit.Before; -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.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = { BookReviewsApiApplication.class }, webEnvironment = WebEnvironment.DEFINED_PORT) -public class RestApiLiveTest { - - private static final String API_URI = "http://localhost:8085/reviews"; - - @Before - public void setUp() { - RestAssured.authentication = preemptive().basic("user", "userPass"); - } - - // GET - - @Test - public void whenGetAllReviews_thenOK() { - final Response response = RestAssured.get(API_URI); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - } - - @Test - public void whenGetCreatedReviewById_thenOK() { - final BookReview review = createRandomReview(); - final String location = createReviewAsUri(review); - - final Response response = RestAssured.get(location); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - assertEquals(review.getContent(), response.jsonPath().get("content")); - } - - @Test - public void whenGetCreatedReviewByBookId_thenOK() { - final BookReview review = createRandomReview(); - createReviewAsUri(review); - - final Response response = RestAssured.get(API_URI + "/search/findByBookId?bookId=" + review.getBookId()); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - assertTrue(response.jsonPath().getLong("page.totalElements") > 0); - } - - @Test - public void whenGetNotExistReviewById_thenNotFound() { - final Response response = RestAssured.get(API_URI + "/" + randomNumeric(4)); - assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); - } - - @Test - public void whenGetNotExistReviewByBookId_thenNotFound() { - final Response response = RestAssured.get(API_URI + "/search/findByBookId?bookId=" + randomNumeric(4)); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - assertTrue(response.jsonPath().getLong("page.totalElements") == 0); - } - - // POST - @Test - public void whenCreateNewReview_thenCreated() { - final BookReview review = createRandomReview(); - - final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(review).post(API_URI); - assertEquals(HttpStatus.CREATED.value(), response.getStatusCode()); - } - - @Test - public void whenCreateInvalidReview_thenError() { - final BookReview review = createRandomReview(); - review.setBookId(null); - - final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(review).post(API_URI); - assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode()); - } - - @Test - public void whenUpdateCreatedReview_thenUpdated() { - // create - final BookReview review = createRandomReview(); - final String location = createReviewAsUri(review); - - // update - review.setRating(4); - Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(review).put(location); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - - // check if changes saved - response = RestAssured.get(location); - assertEquals(HttpStatus.OK.value(), response.getStatusCode()); - assertEquals(4, response.jsonPath().getInt("rating")); - - } - - @Test - public void whenDeleteCreatedReview_thenOk() { - // create - final BookReview review = createRandomReview(); - final String location = createReviewAsUri(review); - - // delete - Response response = RestAssured.delete(location); - assertEquals(HttpStatus.NO_CONTENT.value(), response.getStatusCode()); - - // confirm it was deleted - response = RestAssured.get(location); - assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); - } - - @Test - public void whenDeleteNotExistReview_thenError() { - final Response response = RestAssured.delete(API_URI + "/" + randomNumeric(4)); - assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); - } - - // =============================== Util - - private BookReview createRandomReview() { - final BookReview review = new BookReview(); - review.setContent(randomAlphabetic(10)); - review.setRating(3); - review.setBookId(1L); - return review; - } - - private String createReviewAsUri(BookReview review) { - final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(review).post(API_URI); - return response.jsonPath().get("_links.self.href"); - } - -} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index 070abd246f..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * - * This Live Test requires: - * * A Redis instance running in port 6379 (e.g. using `docker run --name some-redis -p 6379:6379 -d redis`) - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookReviewsApiApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..949718e627 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.cloud.ribbon.client.ServerLocationApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ServerLocationApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 23dbcf8ff6..0000000000 --- a/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.ribbon.client.ServerLocationApp; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ServerLocationApp.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..33e5530667 --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +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; + +import com.baeldung.CloudSite; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CloudSite.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/baeldung/example/springoath2/Springoath2ApplicationIntegrationTest.java similarity index 90% rename from spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java rename to spring-cloud/spring-cloud-security/auth-client/src/test/java/com/baeldung/example/springoath2/Springoath2ApplicationIntegrationTest.java index 37cff095db..1c5198125e 100644 --- a/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java +++ b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/baeldung/example/springoath2/Springoath2ApplicationIntegrationTest.java @@ -1,4 +1,4 @@ -package com.example.springoath2; +package com.baeldung.example.springoath2; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 02c429acf5..0000000000 --- a/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -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(classes = CloudSite.class) -public class SpringContextTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..cce93f2c3e --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +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; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index a061928bf5..0000000000 --- a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/spring-cloud-security/auth-server/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-server/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d61a9c279f --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-server/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +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; + +import com.baeldung.AuthServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AuthServer.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index aec56a574c..0000000000 --- a/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.AuthServer; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AuthServer.class) -public class SpringContextTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/spring-cloud-stream/pom.xml b/spring-cloud/spring-cloud-stream/pom.xml index df17b778da..ebaaab0801 100644 --- a/spring-cloud/spring-cloud-stream/pom.xml +++ b/spring-cloud/spring-cloud-stream/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-cloud-stream spring-cloud-stream pom diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/pom.xml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/pom.xml index 4273bd8701..4aa42f03d7 100644 --- a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/pom.xml +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/pom.xml @@ -8,7 +8,7 @@ Simple Spring Cloud Stream - org.baeldung + com.baeldung spring-cloud-stream 1.0.0-SNAPSHOT .. diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c74013f1a6 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.cloud.stream.rabbit.MultipleOutputsServiceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MultipleOutputsServiceApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 0f3b8de901..0000000000 --- a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.stream.rabbit.MultipleOutputsServiceApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = MultipleOutputsServiceApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml index be920bb93d..fd10322efb 100644 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml @@ -3,7 +3,7 @@ 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 - org.baeldung.cloud + com.baeldung.cloud springcloudtaskbatch springcloudtaskbatch diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..32224bf91b --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.task.JobConfiguration; +import com.baeldung.task.TaskDemo; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootApplication +@ContextConfiguration(classes = { JobConfiguration.class, TaskDemo.class }, initializers = { ConfigFileApplicationContextInitializer.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 3dd350b571..0000000000 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.task.JobConfiguration; -import com.baeldung.task.TaskDemo; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootApplication -@ContextConfiguration(classes = { JobConfiguration.class, TaskDemo.class }, initializers = { ConfigFileApplicationContextInitializer.class }) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml index 441924f1d3..93255959e4 100644 --- a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - SpringCloudTaskSink - SpringCloudTaskSink + springcloudtasksink + springcloudtasksink jar Demo project for Spring Boot diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..35c36bbb82 --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.SpringCloudTaskFinal.SpringCloudTaskSinkApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudTaskSinkApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 51f0926429..0000000000 --- a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.SpringCloudTaskFinal.SpringCloudTaskSinkApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringCloudTaskSinkApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-vault/pom.xml b/spring-cloud/spring-cloud-vault/pom.xml index cbb32ac937..dbdbcb2c50 100644 --- a/spring-cloud/spring-cloud-vault/pom.xml +++ b/spring-cloud/spring-cloud-vault/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung.spring.cloud + com.baeldung.spring.cloud spring-cloud-vault spring-cloud-vault jar diff --git a/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/AccountRepo.java b/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/AccountRepo.java new file mode 100644 index 0000000000..700334946d --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/AccountRepo.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.cloud.vaultsample; + +import com.baeldung.spring.cloud.vaultsample.domain.Account; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AccountRepo extends JpaRepository{ + +} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/AccountResource.java b/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/AccountResource.java new file mode 100644 index 0000000000..34147d3719 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/AccountResource.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.cloud.vaultsample; + +import com.baeldung.spring.cloud.vaultsample.domain.Account; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class AccountResource { + @Autowired + private AccountRepo repo; + + @GetMapping("/account/{id}") + public ResponseEntity getAccount(@PathVariable("id") Long id) { + + Account acc = repo.findById(id).orElse(null); + if ( acc != null ) { + return new ResponseEntity(acc, HttpStatus.OK); + } + else { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + } +} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/SecretResource.java b/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/SecretResource.java similarity index 95% rename from spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/SecretResource.java rename to spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/SecretResource.java index c4579da045..9f51a4512f 100644 --- a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/SecretResource.java +++ b/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/SecretResource.java @@ -1,7 +1,7 @@ /** * */ -package org.baeldung.spring.cloud.vaultsample; +package com.baeldung.spring.cloud.vaultsample; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java b/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java similarity index 86% rename from spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java rename to spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java index 81ece1ca4c..450aa41f7a 100644 --- a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java +++ b/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud.vaultsample; +package com.baeldung.spring.cloud.vaultsample; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/domain/Account.java b/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/domain/Account.java new file mode 100644 index 0000000000..577b108cfd --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/com/baeldung/spring/cloud/vaultsample/domain/Account.java @@ -0,0 +1,133 @@ +/** + * + */ +package com.baeldung.spring.cloud.vaultsample.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.NotNull; + +/** + * @author Philippe + * + */ +@Entity +@Table(name = "account") +public class Account { + + @Id + private Long id; + + @NotNull + private String name; + + private Long branchId; + private Long customerId; + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the branchId + */ + public Long getBranchId() { + return branchId; + } + + /** + * @param branchId the branchId to set + */ + public void setBranchId(Long branchId) { + this.branchId = branchId; + } + + /** + * @return the customerId + */ + public Long getCustomerId() { + return customerId; + } + + /** + * @param customerId the customerId to set + */ + public void setCustomerId(Long customerId) { + this.customerId = customerId; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((branchId == null) ? 0 : branchId.hashCode()); + result = prime * result + ((customerId == null) ? 0 : customerId.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Account other = (Account) obj; + if (branchId == null) { + if (other.branchId != null) + return false; + } else if (!branchId.equals(other.branchId)) + return false; + if (customerId == null) { + if (other.customerId != null) + return false; + } else if (!customerId.equals(other.customerId)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + +} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountRepo.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountRepo.java deleted file mode 100644 index 318cc84957..0000000000 --- a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountRepo.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.spring.cloud.vaultsample; - -import org.baeldung.spring.cloud.vaultsample.domain.Account; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface AccountRepo extends JpaRepository{ - -} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountResource.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountResource.java deleted file mode 100644 index 8fcaa9e2aa..0000000000 --- a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountResource.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.baeldung.spring.cloud.vaultsample; - -import org.baeldung.spring.cloud.vaultsample.domain.Account; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class AccountResource { - @Autowired - private AccountRepo repo; - - @GetMapping("/account/{id}") - public ResponseEntity getAccount(@PathVariable("id") Long id) { - - Account acc = repo.findById(id).orElse(null); - if ( acc != null ) { - return new ResponseEntity(acc, HttpStatus.OK); - } - else { - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - } -} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/domain/Account.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/domain/Account.java deleted file mode 100644 index df4778831b..0000000000 --- a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/domain/Account.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * - */ -package org.baeldung.spring.cloud.vaultsample.domain; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.validation.constraints.NotNull; - -/** - * @author Philippe - * - */ -@Entity -@Table(name = "account") -public class Account { - - @Id - private Long id; - - @NotNull - private String name; - - private Long branchId; - private Long customerId; - - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the branchId - */ - public Long getBranchId() { - return branchId; - } - - /** - * @param branchId the branchId to set - */ - public void setBranchId(Long branchId) { - this.branchId = branchId; - } - - /** - * @return the customerId - */ - public Long getCustomerId() { - return customerId; - } - - /** - * @param customerId the customerId to set - */ - public void setCustomerId(Long customerId) { - this.customerId = customerId; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((branchId == null) ? 0 : branchId.hashCode()); - result = prime * result + ((customerId == null) ? 0 : customerId.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Account other = (Account) obj; - if (branchId == null) { - if (other.branchId != null) - return false; - } else if (!branchId.equals(other.branchId)) - return false; - if (customerId == null) { - if (other.customerId != null) - return false; - } else if (!customerId.equals(other.customerId)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - -} diff --git a/spring-cloud/spring-cloud-vault/src/test/java/com/baeldung/spring/cloud/vaultsample/SpringContextLiveTest.java b/spring-cloud/spring-cloud-vault/src/test/java/com/baeldung/spring/cloud/vaultsample/SpringContextLiveTest.java new file mode 100644 index 0000000000..0cf88fe712 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/java/com/baeldung/spring/cloud/vaultsample/SpringContextLiveTest.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.cloud.vaultsample; + +import com.baeldung.spring.cloud.vaultsample.VaultSampleApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * This live test requires: + * vault server up and running on the environment + * + *
+ * For more info on setting up the vault server: + * https://www.baeldung.com/vault + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = VaultSampleApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java b/spring-cloud/spring-cloud-vault/src/test/java/com/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java similarity index 96% rename from spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java rename to spring-cloud/spring-cloud-vault/src/test/java/com/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java index 7a9c5ba11a..22f7f8e168 100644 --- a/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java +++ b/spring-cloud/spring-cloud-vault/src/test/java/com/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud.vaultsample; +package com.baeldung.spring.cloud.vaultsample; import static org.junit.Assert.assertEquals; diff --git a/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextLiveTest.java b/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextLiveTest.java deleted file mode 100644 index 82fe3d7a4a..0000000000 --- a/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextLiveTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.spring.cloud.vaultsample; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * This live test requires: - * vault server up and running on the environment - * - *
- * For more info on setting up the vault server: - * https://www.baeldung.com/vault - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = VaultSampleApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml index b0ee448e87..ac469d8bc4 100644 --- a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml @@ -56,17 +56,23 @@ spring-cloud-starter-feign ${spring-cloud-starter-feign.version} + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + org.hamcrest hamcrest-core - ${hamcrest.version} + ${hamcrest-core.version} test 1.2.5.RELEASE - 1.3 + 1.3 -
\ No newline at end of file +
diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java deleted file mode 100644 index b45e7b9889..0000000000 --- a/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.ribbon.client.ServerLocationApp; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = GreetingApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f7325e425f --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import com.baeldung.spring.cloud.greeting.GreetingApplication; +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(classes = GreetingApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-zuul/README.md b/spring-cloud/spring-cloud-zuul/README.md index b8e1773930..acd56a213c 100644 --- a/spring-cloud/spring-cloud-zuul/README.md +++ b/spring-cloud/spring-cloud-zuul/README.md @@ -5,3 +5,4 @@ This module contains articles about Spring with Netflix Zuul ### Relevant Articles: - [Rate Limiting in Spring Cloud Netflix Zuul](https://www.baeldung.com/spring-cloud-zuul-rate-limit) - [Spring REST with a Zuul Proxy](https://www.baeldung.com/spring-rest-with-zuul-proxy) +- [Modifying the Response Body in a Zuul Filter](https://www.baeldung.com/zuul-filter-modifying-response-body) diff --git a/spring-cloud/spring-cloud-zuul/pom.xml b/spring-cloud/spring-cloud-zuul/pom.xml index b1f2e886de..e0a63ae00b 100644 --- a/spring-cloud/spring-cloud-zuul/pom.xml +++ b/spring-cloud/spring-cloud-zuul/pom.xml @@ -19,6 +19,7 @@ spring-zuul-foos-resource spring-zuul-ui spring-zuul-rate-limiting + spring-zuul-post-filter diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/.gitignore b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/.gitignore new file mode 100644 index 0000000000..0af075f75a --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/.gitignore @@ -0,0 +1,2 @@ +target/* +*.iml diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/pom.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/pom.xml new file mode 100644 index 0000000000..8643309645 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/pom.xml @@ -0,0 +1,25 @@ + + + + spring-cloud-zuul + com.baeldung.spring.cloud + 0.0.1-SNAPSHOT + + 4.0.0 + spring-zuul-post-filter + + + + org.springframework.cloud + spring-cloud-starter-netflix-zuul + + + + + Hoxton.SR1 + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/java/com/baeldung/ZuulPostFilterApplication.java b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/java/com/baeldung/ZuulPostFilterApplication.java new file mode 100644 index 0000000000..c9aad4e08d --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/java/com/baeldung/ZuulPostFilterApplication.java @@ -0,0 +1,14 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.zuul.EnableZuulProxy; + +@SpringBootApplication +@EnableZuulProxy +public class ZuulPostFilterApplication { + + public static void main(String... args) { + SpringApplication.run(ZuulPostFilterApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/java/com/baeldung/controllers/GreetingController.java b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/java/com/baeldung/controllers/GreetingController.java new file mode 100644 index 0000000000..bd21b098ab --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/java/com/baeldung/controllers/GreetingController.java @@ -0,0 +1,16 @@ +package com.baeldung.controllers; + +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/greeting") +public class GreetingController { + + @GetMapping("/simple") + public ResponseEntity getSimple() { + return ResponseEntity.ok("Hi"); + } +} diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/java/com/baeldung/filters/ResponseLogFilter.java b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/java/com/baeldung/filters/ResponseLogFilter.java new file mode 100644 index 0000000000..b0e4f7e313 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/java/com/baeldung/filters/ResponseLogFilter.java @@ -0,0 +1,59 @@ +package com.baeldung.filters; + +import com.google.common.io.CharStreams; +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.context.RequestContext; +import com.netflix.zuul.exception.ZuulException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.io.InputStream; +import java.io.InputStreamReader; + +import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; + +@Component +public class ResponseLogFilter extends ZuulFilter { + + private Logger logger = LoggerFactory.getLogger(ResponseLogFilter.class); + + @Override + public String filterType() { + return POST_TYPE; + } + + @Override + public int filterOrder() { + return 0; + } + + @Override + public boolean shouldFilter() { + return true; + } + + @Override + public Object run() throws ZuulException { + + RequestContext context = RequestContext.getCurrentContext(); + try (final InputStream responseDataStream = context.getResponseDataStream()) { + + if(responseDataStream == null) { + logger.info("BODY: {}", ""); + return null; + } + + String responseData = CharStreams.toString(new InputStreamReader(responseDataStream, "UTF-8")); + logger.info("BODY: {}", responseData); + + context.setResponseBody(responseData); + } + catch (Exception e) { + throw new ZuulException(e, INTERNAL_SERVER_ERROR.value(), e.getMessage()); + } + + return null; + } +} diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/resources/application.yml new file mode 100644 index 0000000000..ebcc7c8be7 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/main/resources/application.yml @@ -0,0 +1,11 @@ +server: + port: 8080 +zuul: + prefix: /api + routes: + greeting-service: + path: /greeting/** + url: forward:/greeting + foos-service: + path: /foos/** + url: http://localhost:8081/spring-zuul-foos-resource/foos \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/test/java/com/baeldung/ZuulPostFilterLiveTest.java b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/test/java/com/baeldung/ZuulPostFilterLiveTest.java new file mode 100644 index 0000000000..475508879e --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/src/test/java/com/baeldung/ZuulPostFilterLiveTest.java @@ -0,0 +1,30 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +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.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.DEFINED_PORT) +public class ZuulPostFilterLiveTest { + + @LocalServerPort + private int port; + private static final String SIMPLE_GREETING = "/api/greeting/simple"; + private TestRestTemplate restTemplate = new TestRestTemplate(); + + @Test + public void whenClientCallApi_thenLogAndReturnResponseBody() { + String url = "http://localhost:" + port + SIMPLE_GREETING; + ResponseEntity response = restTemplate.getForEntity(url, String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals(response.getBody(), "Hi"); + } +} diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml index 09c94663b1..7978d9c77b 100644 --- a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml @@ -24,12 +24,7 @@ org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library + hamcrest test diff --git a/spring-core-2/README.md b/spring-core-2/README.md index 0ed303162d..10d3080b45 100644 --- a/spring-core-2/README.md +++ b/spring-core-2/README.md @@ -7,7 +7,6 @@ This module contains articles about core Spring functionality - [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire) - [Spring Profiles](http://www.baeldung.com/spring-profiles) - [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) -- [Running Setup Data on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) - [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope) - [@Order in Spring](http://www.baeldung.com/spring-order) @@ -15,6 +14,5 @@ This module contains articles about core Spring functionality - [Spring Events](https://www.baeldung.com/spring-events) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) -- [Guide to the Spring BeanFactory](https://www.baeldung.com/spring-beanfactory) -- [Read HttpServletRequest Multiple Times](https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times) -- More articles: [[<-- prev]](/spring-core)[[next -->]](/spring-core-3) \ No newline at end of file +- [Running Setup Data on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) +- More articles: [[<-- prev]](/spring-core)[[next -->]](/spring-core-3) diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index f89a093f30..edbb351bd0 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -135,12 +135,7 @@ org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library + hamcrest test @@ -174,7 +169,7 @@ org.apache.maven.plugins maven-war-plugin - 3.2.2 + ${maven.version} false @@ -201,9 +196,9 @@ - org.baeldung.sample.App + com.baeldung.sample.App - 5.0.6.RELEASE + 5.2.2.RELEASE 1.3.2 5.2.5.Final @@ -214,6 +209,7 @@ 3.6.1 2.1.0 3.22.0-GA + 3.2.2
diff --git a/spring-core-2/src/main/java/com/baeldung/autowire/sample/App.java b/spring-core-2/src/main/java/com/baeldung/autowire/sample/App.java new file mode 100644 index 0000000000..18ff11a49c --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/autowire/sample/App.java @@ -0,0 +1,11 @@ +package com.baeldung.autowire.sample; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class App { + public static void main(String[] args) { + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); + FooService fooService = ctx.getBean(FooService.class); + fooService.doStuff(); + } +} diff --git a/spring-core-2/src/main/java/com/baeldung/autowire/sample/AppConfig.java b/spring-core-2/src/main/java/com/baeldung/autowire/sample/AppConfig.java new file mode 100644 index 0000000000..f948e2bf8e --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/autowire/sample/AppConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.autowire.sample; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.autowire.sample") +public class AppConfig { + +} diff --git a/spring-core-2/src/main/java/org/baeldung/autowire/sample/BarFormatter.java b/spring-core-2/src/main/java/com/baeldung/autowire/sample/BarFormatter.java similarity index 83% rename from spring-core-2/src/main/java/org/baeldung/autowire/sample/BarFormatter.java rename to spring-core-2/src/main/java/com/baeldung/autowire/sample/BarFormatter.java index f7e730fdc6..e67a376d25 100644 --- a/spring-core-2/src/main/java/org/baeldung/autowire/sample/BarFormatter.java +++ b/spring-core-2/src/main/java/com/baeldung/autowire/sample/BarFormatter.java @@ -1,4 +1,4 @@ -package org.baeldung.autowire.sample; +package com.baeldung.autowire.sample; import org.springframework.stereotype.Component; diff --git a/spring-core-2/src/main/java/com/baeldung/autowire/sample/FooDAO.java b/spring-core-2/src/main/java/com/baeldung/autowire/sample/FooDAO.java new file mode 100644 index 0000000000..aec26202ab --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/autowire/sample/FooDAO.java @@ -0,0 +1,5 @@ +package com.baeldung.autowire.sample; + +public class FooDAO { + +} diff --git a/spring-core-2/src/main/java/org/baeldung/autowire/sample/FooFormatter.java b/spring-core-2/src/main/java/com/baeldung/autowire/sample/FooFormatter.java similarity index 83% rename from spring-core-2/src/main/java/org/baeldung/autowire/sample/FooFormatter.java rename to spring-core-2/src/main/java/com/baeldung/autowire/sample/FooFormatter.java index 5fdacbadd4..57f93a53d7 100644 --- a/spring-core-2/src/main/java/org/baeldung/autowire/sample/FooFormatter.java +++ b/spring-core-2/src/main/java/com/baeldung/autowire/sample/FooFormatter.java @@ -1,4 +1,4 @@ -package org.baeldung.autowire.sample; +package com.baeldung.autowire.sample; import org.springframework.stereotype.Component; diff --git a/spring-core-2/src/main/java/com/baeldung/autowire/sample/FooService.java b/spring-core-2/src/main/java/com/baeldung/autowire/sample/FooService.java new file mode 100644 index 0000000000..8a073279bc --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/autowire/sample/FooService.java @@ -0,0 +1,31 @@ +package com.baeldung.autowire.sample; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * This class presents a field, a constructor, and a setter injection type. + * Usually, we'd stick with a single approach for a given property. This is just an educational code. + */ +@Component +public class FooService { + + @Autowired + @FormatterType("Foo") + private Formatter formatter; + + @Autowired + public FooService(@FormatterType("Foo") Formatter formatter) { + this.formatter = formatter; + } + + @Autowired + public void setFormatter(@FormatterType("Foo") Formatter formatter) { + this.formatter = formatter; + } + + public String doStuff() { + return formatter.format(); + } + +} diff --git a/spring-core-2/src/main/java/com/baeldung/autowire/sample/Formatter.java b/spring-core-2/src/main/java/com/baeldung/autowire/sample/Formatter.java new file mode 100644 index 0000000000..59d718050a --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/autowire/sample/Formatter.java @@ -0,0 +1,7 @@ +package com.baeldung.autowire.sample; + +public interface Formatter { + + String format(); + +} diff --git a/spring-core-2/src/main/java/org/baeldung/autowire/sample/FormatterType.java b/spring-core-2/src/main/java/com/baeldung/autowire/sample/FormatterType.java similarity index 91% rename from spring-core-2/src/main/java/org/baeldung/autowire/sample/FormatterType.java rename to spring-core-2/src/main/java/com/baeldung/autowire/sample/FormatterType.java index ea1eec055a..f2961745b5 100644 --- a/spring-core-2/src/main/java/org/baeldung/autowire/sample/FormatterType.java +++ b/spring-core-2/src/main/java/com/baeldung/autowire/sample/FormatterType.java @@ -1,4 +1,4 @@ -package org.baeldung.autowire.sample; +package com.baeldung.autowire.sample; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-core-2/src/main/java/com/baeldung/bean/config/ConstructorBasedShipConfig.java b/spring-core-2/src/main/java/com/baeldung/bean/config/ConstructorBasedShipConfig.java new file mode 100644 index 0000000000..f9f23ee304 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/bean/config/ConstructorBasedShipConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.bean.config; + +import com.baeldung.bean.injection.Helm; +import com.baeldung.bean.injection.Ship; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ConstructorBasedShipConfig { + + @Bean + public Ship ship() { + return new Ship(helm()); + } + + @Bean + public Helm helm() { + return new Helm(); + } +} diff --git a/spring-core-2/src/main/java/com/baeldung/bean/config/SetterBasedShipConfig.java b/spring-core-2/src/main/java/com/baeldung/bean/config/SetterBasedShipConfig.java new file mode 100644 index 0000000000..cea6385fd9 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/bean/config/SetterBasedShipConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.bean.config; + +import com.baeldung.bean.injection.Helm; +import com.baeldung.bean.injection.Ship; +import org.springframework.context.annotation.Bean; + +public class SetterBasedShipConfig { + + @Bean + public Ship ship() { + return new Ship(); + } + + @Bean + public Helm helm() { + return new Helm(); + } +} diff --git a/spring-core-2/src/main/java/org/baeldung/bean/injection/Helm.java b/spring-core-2/src/main/java/com/baeldung/bean/injection/Helm.java similarity index 86% rename from spring-core-2/src/main/java/org/baeldung/bean/injection/Helm.java rename to spring-core-2/src/main/java/com/baeldung/bean/injection/Helm.java index 86f71ce795..e1477bd0d9 100644 --- a/spring-core-2/src/main/java/org/baeldung/bean/injection/Helm.java +++ b/spring-core-2/src/main/java/com/baeldung/bean/injection/Helm.java @@ -1,4 +1,4 @@ -package org.baeldung.bean.injection; +package com.baeldung.bean.injection; public class Helm { diff --git a/spring-core-2/src/main/java/org/baeldung/bean/injection/Ship.java b/spring-core-2/src/main/java/com/baeldung/bean/injection/Ship.java similarity index 91% rename from spring-core-2/src/main/java/org/baeldung/bean/injection/Ship.java rename to spring-core-2/src/main/java/com/baeldung/bean/injection/Ship.java index 69d9fa1276..f69a3a51ca 100644 --- a/spring-core-2/src/main/java/org/baeldung/bean/injection/Ship.java +++ b/spring-core-2/src/main/java/com/baeldung/bean/injection/Ship.java @@ -1,4 +1,4 @@ -package org.baeldung.bean.injection; +package com.baeldung.bean.injection; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-core-2/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java b/spring-core-2/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java new file mode 100644 index 0000000000..2e42a3f744 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java @@ -0,0 +1,9 @@ +package com.baeldung.customannotation; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.customannotation") +public class CustomAnnotationConfiguration { +} diff --git a/spring-core-2/src/main/java/org/baeldung/customannotation/DataAccess.java b/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccess.java similarity index 90% rename from spring-core-2/src/main/java/org/baeldung/customannotation/DataAccess.java rename to spring-core-2/src/main/java/com/baeldung/customannotation/DataAccess.java index 9a8a493a6d..4160bad16d 100644 --- a/spring-core-2/src/main/java/org/baeldung/customannotation/DataAccess.java +++ b/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccess.java @@ -1,4 +1,4 @@ -package org.baeldung.customannotation; +package com.baeldung.customannotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; diff --git a/spring-core-2/src/main/java/org/baeldung/customannotation/DataAccessAnnotationProcessor.java b/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java similarity index 97% rename from spring-core-2/src/main/java/org/baeldung/customannotation/DataAccessAnnotationProcessor.java rename to spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java index c792073745..27008176a8 100644 --- a/spring-core-2/src/main/java/org/baeldung/customannotation/DataAccessAnnotationProcessor.java +++ b/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java @@ -1,4 +1,4 @@ -package org.baeldung.customannotation; +package com.baeldung.customannotation; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-core-2/src/main/java/org/baeldung/customannotation/DataAccessFieldCallback.java b/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java similarity index 99% rename from spring-core-2/src/main/java/org/baeldung/customannotation/DataAccessFieldCallback.java rename to spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java index 8cb62affc4..07b5298ea9 100644 --- a/spring-core-2/src/main/java/org/baeldung/customannotation/DataAccessFieldCallback.java +++ b/spring-core-2/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java @@ -1,4 +1,4 @@ -package org.baeldung.customannotation; +package com.baeldung.customannotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; diff --git a/spring-core-2/src/main/java/org/baeldung/customannotation/GenericDAO.java b/spring-core-2/src/main/java/com/baeldung/customannotation/GenericDAO.java similarity index 94% rename from spring-core-2/src/main/java/org/baeldung/customannotation/GenericDAO.java rename to spring-core-2/src/main/java/com/baeldung/customannotation/GenericDAO.java index 1916b7de6e..0edd33b049 100644 --- a/spring-core-2/src/main/java/org/baeldung/customannotation/GenericDAO.java +++ b/spring-core-2/src/main/java/com/baeldung/customannotation/GenericDAO.java @@ -1,4 +1,4 @@ -package org.baeldung.customannotation; +package com.baeldung.customannotation; import java.util.Collections; import java.util.List; diff --git a/spring-core-2/src/main/java/org/baeldung/customscope/TenantBean.java b/spring-core-2/src/main/java/com/baeldung/customscope/TenantBean.java similarity index 89% rename from spring-core-2/src/main/java/org/baeldung/customscope/TenantBean.java rename to spring-core-2/src/main/java/com/baeldung/customscope/TenantBean.java index 874fcda9f2..e892ae9d9b 100644 --- a/spring-core-2/src/main/java/org/baeldung/customscope/TenantBean.java +++ b/spring-core-2/src/main/java/com/baeldung/customscope/TenantBean.java @@ -1,4 +1,4 @@ -package org.baeldung.customscope; +package com.baeldung.customscope; public class TenantBean { diff --git a/spring-core-2/src/main/java/org/baeldung/customscope/TenantBeanFactoryPostProcessor.java b/spring-core-2/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java similarity index 93% rename from spring-core-2/src/main/java/org/baeldung/customscope/TenantBeanFactoryPostProcessor.java rename to spring-core-2/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java index 2757399fa6..84ed0b46d7 100644 --- a/spring-core-2/src/main/java/org/baeldung/customscope/TenantBeanFactoryPostProcessor.java +++ b/spring-core-2/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java @@ -1,4 +1,4 @@ -package org.baeldung.customscope; +package com.baeldung.customscope; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; diff --git a/spring-core-2/src/main/java/org/baeldung/customscope/TenantBeansConfig.java b/spring-core-2/src/main/java/com/baeldung/customscope/TenantBeansConfig.java similarity index 93% rename from spring-core-2/src/main/java/org/baeldung/customscope/TenantBeansConfig.java rename to spring-core-2/src/main/java/com/baeldung/customscope/TenantBeansConfig.java index be3ac001fb..c219000fe6 100644 --- a/spring-core-2/src/main/java/org/baeldung/customscope/TenantBeansConfig.java +++ b/spring-core-2/src/main/java/com/baeldung/customscope/TenantBeansConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.customscope; +package com.baeldung.customscope; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-core-2/src/main/java/org/baeldung/customscope/TenantScope.java b/spring-core-2/src/main/java/com/baeldung/customscope/TenantScope.java similarity index 97% rename from spring-core-2/src/main/java/org/baeldung/customscope/TenantScope.java rename to spring-core-2/src/main/java/com/baeldung/customscope/TenantScope.java index 144d092be6..f3077bc4c2 100644 --- a/spring-core-2/src/main/java/org/baeldung/customscope/TenantScope.java +++ b/spring-core-2/src/main/java/com/baeldung/customscope/TenantScope.java @@ -1,4 +1,4 @@ -package org.baeldung.customscope; +package com.baeldung.customscope; import java.util.Collections; import java.util.HashMap; diff --git a/spring-core-2/src/main/java/org/baeldung/customscope/TenantScopeConfig.java b/spring-core-2/src/main/java/com/baeldung/customscope/TenantScopeConfig.java similarity index 91% rename from spring-core-2/src/main/java/org/baeldung/customscope/TenantScopeConfig.java rename to spring-core-2/src/main/java/com/baeldung/customscope/TenantScopeConfig.java index d1159b0f60..1829e1e8c4 100644 --- a/spring-core-2/src/main/java/org/baeldung/customscope/TenantScopeConfig.java +++ b/spring-core-2/src/main/java/com/baeldung/customscope/TenantScopeConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.customscope; +package com.baeldung.customscope; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.context.annotation.Bean; diff --git a/spring-core-2/src/main/java/com/baeldung/nullibility/Person.java b/spring-core-2/src/main/java/com/baeldung/nullibility/Person.java new file mode 100644 index 0000000000..8fb60fb7a7 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/nullibility/Person.java @@ -0,0 +1,33 @@ +package com.baeldung.nullibility; + +import org.springframework.lang.NonNull; +import org.springframework.lang.Nullable; + +public class Person { + @NonNull + private String fullName; + @Nullable + private String nickName; + + void setFullName(String fullName) { + if (fullName != null && fullName.isEmpty()) { + fullName = null; + } + this.fullName = fullName; + } + + void setNickName(String nickName) { + if (nickName != null && nickName.isEmpty()) { + nickName = null; + } + this.nickName = nickName; + } + + String getFullName() { + return fullName; + } + + String getNickName() { + return nickName; + } +} diff --git a/spring-core-2/src/main/java/com/baeldung/nullibility/package-info.java b/spring-core-2/src/main/java/com/baeldung/nullibility/package-info.java new file mode 100644 index 0000000000..11a3f7c7aa --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/nullibility/package-info.java @@ -0,0 +1,6 @@ +@NonNullApi +@NonNullFields +package com.baeldung.nullibility; + +import org.springframework.lang.NonNullApi; +import org.springframework.lang.NonNullFields; \ No newline at end of file diff --git a/spring-core-2/src/main/java/org/baeldung/order/Average.java b/spring-core-2/src/main/java/com/baeldung/order/Average.java similarity index 91% rename from spring-core-2/src/main/java/org/baeldung/order/Average.java rename to spring-core-2/src/main/java/com/baeldung/order/Average.java index 3deffaf1ae..0f84f1b436 100644 --- a/spring-core-2/src/main/java/org/baeldung/order/Average.java +++ b/spring-core-2/src/main/java/com/baeldung/order/Average.java @@ -1,4 +1,4 @@ -package org.baeldung.order; +package com.baeldung.order; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; diff --git a/spring-core-2/src/main/java/org/baeldung/order/Excellent.java b/spring-core-2/src/main/java/com/baeldung/order/Excellent.java similarity index 89% rename from spring-core-2/src/main/java/org/baeldung/order/Excellent.java rename to spring-core-2/src/main/java/com/baeldung/order/Excellent.java index 96fea4ac9b..5fd1d18796 100644 --- a/spring-core-2/src/main/java/org/baeldung/order/Excellent.java +++ b/spring-core-2/src/main/java/com/baeldung/order/Excellent.java @@ -1,4 +1,4 @@ -package org.baeldung.order; +package com.baeldung.order; import org.springframework.stereotype.Component; import org.springframework.core.annotation.Order; diff --git a/spring-core-2/src/main/java/org/baeldung/order/Good.java b/spring-core-2/src/main/java/com/baeldung/order/Good.java similarity index 89% rename from spring-core-2/src/main/java/org/baeldung/order/Good.java rename to spring-core-2/src/main/java/com/baeldung/order/Good.java index 4b3e268504..a176904c64 100644 --- a/spring-core-2/src/main/java/org/baeldung/order/Good.java +++ b/spring-core-2/src/main/java/com/baeldung/order/Good.java @@ -1,4 +1,4 @@ -package org.baeldung.order; +package com.baeldung.order; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; diff --git a/spring-core-2/src/main/java/com/baeldung/order/Rating.java b/spring-core-2/src/main/java/com/baeldung/order/Rating.java new file mode 100644 index 0000000000..9125019b5c --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/order/Rating.java @@ -0,0 +1,6 @@ +package com.baeldung.order; + +public interface Rating { + + int getRating(); +} diff --git a/spring-core-2/src/main/java/com/baeldung/persistence/Setup.java b/spring-core-2/src/main/java/com/baeldung/persistence/Setup.java new file mode 100644 index 0000000000..251ea4654c --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/persistence/Setup.java @@ -0,0 +1,26 @@ +package com.baeldung.persistence; + +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.stereotype.Component; + +@Component +public class Setup implements ApplicationListener { + + private boolean setupDone; + + public Setup() { + super(); + } + + // + + @Override + public final void onApplicationEvent(final ContextRefreshedEvent event) { + if (!setupDone) { + System.out.println(); + setupDone = true; + } + } + +} diff --git a/spring-core-2/src/main/java/com/baeldung/primary/Config.java b/spring-core-2/src/main/java/com/baeldung/primary/Config.java new file mode 100644 index 0000000000..eec9fb2ceb --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/primary/Config.java @@ -0,0 +1,22 @@ +package com.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="com.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-core-2/src/main/java/org/baeldung/primary/DepartmentManager.java b/spring-core-2/src/main/java/com/baeldung/primary/DepartmentManager.java similarity index 87% rename from spring-core-2/src/main/java/org/baeldung/primary/DepartmentManager.java rename to spring-core-2/src/main/java/com/baeldung/primary/DepartmentManager.java index 2603951b4e..161b39337b 100644 --- a/spring-core-2/src/main/java/org/baeldung/primary/DepartmentManager.java +++ b/spring-core-2/src/main/java/com/baeldung/primary/DepartmentManager.java @@ -1,4 +1,4 @@ -package org.baeldung.primary; +package com.baeldung.primary; import org.springframework.stereotype.Component; diff --git a/spring-core-2/src/main/java/com/baeldung/primary/Employee.java b/spring-core-2/src/main/java/com/baeldung/primary/Employee.java new file mode 100644 index 0000000000..48c5502921 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/primary/Employee.java @@ -0,0 +1,20 @@ +package com.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-core-2/src/main/java/org/baeldung/primary/GeneralManager.java b/spring-core-2/src/main/java/com/baeldung/primary/GeneralManager.java similarity index 89% rename from spring-core-2/src/main/java/org/baeldung/primary/GeneralManager.java rename to spring-core-2/src/main/java/com/baeldung/primary/GeneralManager.java index 0a94f0f96a..80b5a79471 100644 --- a/spring-core-2/src/main/java/org/baeldung/primary/GeneralManager.java +++ b/spring-core-2/src/main/java/com/baeldung/primary/GeneralManager.java @@ -1,4 +1,4 @@ -package org.baeldung.primary; +package com.baeldung.primary; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; diff --git a/spring-core-2/src/main/java/org/baeldung/primary/Manager.java b/spring-core-2/src/main/java/com/baeldung/primary/Manager.java similarity index 77% rename from spring-core-2/src/main/java/org/baeldung/primary/Manager.java rename to spring-core-2/src/main/java/com/baeldung/primary/Manager.java index 4666a1babf..45e02b2b05 100644 --- a/spring-core-2/src/main/java/org/baeldung/primary/Manager.java +++ b/spring-core-2/src/main/java/com/baeldung/primary/Manager.java @@ -1,4 +1,4 @@ -package org.baeldung.primary; +package com.baeldung.primary; /** * Created by Gebruiker on 7/19/2018. diff --git a/spring-core-2/src/main/java/org/baeldung/primary/ManagerService.java b/spring-core-2/src/main/java/com/baeldung/primary/ManagerService.java similarity index 91% rename from spring-core-2/src/main/java/org/baeldung/primary/ManagerService.java rename to spring-core-2/src/main/java/com/baeldung/primary/ManagerService.java index 94ea6785c9..86390327c2 100644 --- a/spring-core-2/src/main/java/org/baeldung/primary/ManagerService.java +++ b/spring-core-2/src/main/java/com/baeldung/primary/ManagerService.java @@ -1,4 +1,4 @@ -package org.baeldung.primary; +package com.baeldung.primary; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/spring-core-2/src/main/java/org/baeldung/primary/PrimaryApplication.java b/spring-core-2/src/main/java/com/baeldung/primary/PrimaryApplication.java similarity index 95% rename from spring-core-2/src/main/java/org/baeldung/primary/PrimaryApplication.java rename to spring-core-2/src/main/java/com/baeldung/primary/PrimaryApplication.java index ffa2a4028d..f66bf8285b 100644 --- a/spring-core-2/src/main/java/org/baeldung/primary/PrimaryApplication.java +++ b/spring-core-2/src/main/java/com/baeldung/primary/PrimaryApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.primary; +package com.baeldung.primary; import org.springframework.context.annotation.AnnotationConfigApplicationContext; diff --git a/spring-core-2/src/main/java/com/baeldung/profiles/DatasourceConfig.java b/spring-core-2/src/main/java/com/baeldung/profiles/DatasourceConfig.java new file mode 100644 index 0000000000..9724477666 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/profiles/DatasourceConfig.java @@ -0,0 +1,5 @@ +package com.baeldung.profiles; + +public interface DatasourceConfig { + void setup(); +} diff --git a/spring-core-2/src/main/java/org/baeldung/profiles/DevDatasourceConfig.java b/spring-core-2/src/main/java/com/baeldung/profiles/DevDatasourceConfig.java similarity index 91% rename from spring-core-2/src/main/java/org/baeldung/profiles/DevDatasourceConfig.java rename to spring-core-2/src/main/java/com/baeldung/profiles/DevDatasourceConfig.java index e357280c43..b4b14eaf50 100644 --- a/spring-core-2/src/main/java/org/baeldung/profiles/DevDatasourceConfig.java +++ b/spring-core-2/src/main/java/com/baeldung/profiles/DevDatasourceConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.profiles; +package com.baeldung.profiles; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; diff --git a/spring-core-2/src/main/java/org/baeldung/profiles/ProductionDatasourceConfig.java b/spring-core-2/src/main/java/com/baeldung/profiles/ProductionDatasourceConfig.java similarity index 91% rename from spring-core-2/src/main/java/org/baeldung/profiles/ProductionDatasourceConfig.java rename to spring-core-2/src/main/java/com/baeldung/profiles/ProductionDatasourceConfig.java index f1adff9c96..57943d1b17 100644 --- a/spring-core-2/src/main/java/org/baeldung/profiles/ProductionDatasourceConfig.java +++ b/spring-core-2/src/main/java/com/baeldung/profiles/ProductionDatasourceConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.profiles; +package com.baeldung.profiles; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; diff --git a/spring-core-2/src/main/java/org/baeldung/profiles/ProfileManager.java b/spring-core-2/src/main/java/com/baeldung/profiles/ProfileManager.java similarity index 93% rename from spring-core-2/src/main/java/org/baeldung/profiles/ProfileManager.java rename to spring-core-2/src/main/java/com/baeldung/profiles/ProfileManager.java index b4cb10e690..81d4592782 100644 --- a/spring-core-2/src/main/java/org/baeldung/profiles/ProfileManager.java +++ b/spring-core-2/src/main/java/com/baeldung/profiles/ProfileManager.java @@ -1,4 +1,4 @@ -package org.baeldung.profiles; +package com.baeldung.profiles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; diff --git a/spring-core-2/src/main/java/org/baeldung/profiles/SpringProfilesConfig.java b/spring-core-2/src/main/java/com/baeldung/profiles/SpringProfilesConfig.java similarity index 80% rename from spring-core-2/src/main/java/org/baeldung/profiles/SpringProfilesConfig.java rename to spring-core-2/src/main/java/com/baeldung/profiles/SpringProfilesConfig.java index 2d1905ee9c..cdd96ad953 100644 --- a/spring-core-2/src/main/java/org/baeldung/profiles/SpringProfilesConfig.java +++ b/spring-core-2/src/main/java/com/baeldung/profiles/SpringProfilesConfig.java @@ -1,11 +1,11 @@ -package org.baeldung.profiles; +package com.baeldung.profiles; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration -@ComponentScan("org.baeldung.profiles") +@ComponentScan("com.baeldung.profiles") @PropertySource(value = "classpath:application.properties") public class SpringProfilesConfig { diff --git a/spring-core-2/src/main/java/com/baeldung/sample/Bar.java b/spring-core-2/src/main/java/com/baeldung/sample/Bar.java new file mode 100644 index 0000000000..42302b5563 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/sample/Bar.java @@ -0,0 +1,5 @@ +package com.baeldung.sample; + +public class Bar { + +} diff --git a/spring-core-2/src/main/java/com/baeldung/sample/Foo.java b/spring-core-2/src/main/java/com/baeldung/sample/Foo.java new file mode 100644 index 0000000000..b25c9ecfb5 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/sample/Foo.java @@ -0,0 +1,5 @@ +package com.baeldung.sample; + +public class Foo { + +} diff --git a/spring-core-2/src/main/java/org/baeldung/sampleabstract/BallService.java b/spring-core-2/src/main/java/com/baeldung/sampleabstract/BallService.java similarity index 94% rename from spring-core-2/src/main/java/org/baeldung/sampleabstract/BallService.java rename to spring-core-2/src/main/java/com/baeldung/sampleabstract/BallService.java index 9a75de7fa1..0d951aac8b 100644 --- a/spring-core-2/src/main/java/org/baeldung/sampleabstract/BallService.java +++ b/spring-core-2/src/main/java/com/baeldung/sampleabstract/BallService.java @@ -1,4 +1,4 @@ -package org.baeldung.sampleabstract; +package com.baeldung.sampleabstract; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-core-2/src/main/java/org/baeldung/sampleabstract/BasketballService.java b/spring-core-2/src/main/java/com/baeldung/sampleabstract/BasketballService.java similarity index 88% rename from spring-core-2/src/main/java/org/baeldung/sampleabstract/BasketballService.java rename to spring-core-2/src/main/java/com/baeldung/sampleabstract/BasketballService.java index c117231d3c..4d6345b069 100644 --- a/spring-core-2/src/main/java/org/baeldung/sampleabstract/BasketballService.java +++ b/spring-core-2/src/main/java/com/baeldung/sampleabstract/BasketballService.java @@ -1,4 +1,4 @@ -package org.baeldung.sampleabstract; +package com.baeldung.sampleabstract; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-core-2/src/main/java/org/baeldung/sampleabstract/DemoApp.java b/spring-core-2/src/main/java/com/baeldung/sampleabstract/DemoApp.java similarity index 82% rename from spring-core-2/src/main/java/org/baeldung/sampleabstract/DemoApp.java rename to spring-core-2/src/main/java/com/baeldung/sampleabstract/DemoApp.java index 615d354ecf..5a308b2671 100644 --- a/spring-core-2/src/main/java/org/baeldung/sampleabstract/DemoApp.java +++ b/spring-core-2/src/main/java/com/baeldung/sampleabstract/DemoApp.java @@ -1,4 +1,4 @@ -package org.baeldung.sampleabstract; +package com.baeldung.sampleabstract; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan(basePackages = "org.baeldung.sampleabstract") +@ComponentScan(basePackages = "com.baeldung.sampleabstract") public class DemoApp { diff --git a/spring-core-2/src/main/java/org/baeldung/sampleabstract/LogRepository.java b/spring-core-2/src/main/java/com/baeldung/sampleabstract/LogRepository.java similarity index 82% rename from spring-core-2/src/main/java/org/baeldung/sampleabstract/LogRepository.java rename to spring-core-2/src/main/java/com/baeldung/sampleabstract/LogRepository.java index 3a65671493..84979768b5 100644 --- a/spring-core-2/src/main/java/org/baeldung/sampleabstract/LogRepository.java +++ b/spring-core-2/src/main/java/com/baeldung/sampleabstract/LogRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.sampleabstract; +package com.baeldung.sampleabstract; import org.springframework.stereotype.Component; diff --git a/spring-core-2/src/main/java/org/baeldung/sampleabstract/RuleRepository.java b/spring-core-2/src/main/java/com/baeldung/sampleabstract/RuleRepository.java similarity index 82% rename from spring-core-2/src/main/java/org/baeldung/sampleabstract/RuleRepository.java rename to spring-core-2/src/main/java/com/baeldung/sampleabstract/RuleRepository.java index fd42178ab6..a1c5b5067f 100644 --- a/spring-core-2/src/main/java/org/baeldung/sampleabstract/RuleRepository.java +++ b/spring-core-2/src/main/java/com/baeldung/sampleabstract/RuleRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.sampleabstract; +package com.baeldung.sampleabstract; import org.springframework.stereotype.Component; diff --git a/spring-core-2/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java b/spring-core-2/src/main/java/com/baeldung/scopes/HelloMessageGenerator.java similarity index 88% rename from spring-core-2/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java rename to spring-core-2/src/main/java/com/baeldung/scopes/HelloMessageGenerator.java index 562069bc9a..9b912fc04e 100644 --- a/spring-core-2/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java +++ b/spring-core-2/src/main/java/com/baeldung/scopes/HelloMessageGenerator.java @@ -1,4 +1,4 @@ -package org.baeldung.scopes; +package com.baeldung.scopes; public class HelloMessageGenerator { diff --git a/spring-core-2/src/main/java/com/baeldung/scopes/Person.java b/spring-core-2/src/main/java/com/baeldung/scopes/Person.java new file mode 100644 index 0000000000..e2ea2ce1d7 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/scopes/Person.java @@ -0,0 +1,27 @@ +package com.baeldung.scopes; + +public class Person { + private String name; + private int age; + + public Person() { + } + + public Person(final String name, final int age) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + @Override + public String toString() { + return "Person [name=" + name + "]"; + } + +} diff --git a/spring-core-2/src/main/java/com/baeldung/scopes/ScopesConfig.java b/spring-core-2/src/main/java/com/baeldung/scopes/ScopesConfig.java new file mode 100644 index 0000000000..2291baa62d --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/scopes/ScopesConfig.java @@ -0,0 +1,49 @@ +package com.baeldung.scopes; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; +import org.springframework.context.annotation.ScopedProxyMode; +import org.springframework.web.context.annotation.ApplicationScope; +import org.springframework.web.context.annotation.RequestScope; +import org.springframework.web.context.annotation.SessionScope; + +@Configuration +public class ScopesConfig { + + @Bean + @Scope("singleton") + public Person personSingleton() { + return new Person(); + } + + @Bean + @Scope("prototype") + public Person personPrototype() { + return new Person(); + } + + @Bean + @RequestScope + public HelloMessageGenerator requestScopedBean() { + return new HelloMessageGenerator(); + } + + @Bean + @SessionScope + public HelloMessageGenerator sessionScopedBean() { + return new HelloMessageGenerator(); + } + + @Bean + @ApplicationScope + public HelloMessageGenerator applicationScopedBean() { + return new HelloMessageGenerator(); + } + + @Bean + @Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS) + public HelloMessageGenerator websocketScopedBean() { + return new HelloMessageGenerator(); + } +} diff --git a/spring-core-2/src/main/java/org/baeldung/scopes/ScopesController.java b/spring-core-2/src/main/java/com/baeldung/scopes/ScopesController.java similarity index 98% rename from spring-core-2/src/main/java/org/baeldung/scopes/ScopesController.java rename to spring-core-2/src/main/java/com/baeldung/scopes/ScopesController.java index 9257a3aa3a..1ca4dc4050 100644 --- a/spring-core-2/src/main/java/org/baeldung/scopes/ScopesController.java +++ b/spring-core-2/src/main/java/com/baeldung/scopes/ScopesController.java @@ -1,4 +1,4 @@ -package org.baeldung.scopes; +package com.baeldung.scopes; import javax.annotation.Resource; diff --git a/spring-core-2/src/main/java/org/baeldung/spring/config/CleanupBean.java b/spring-core-2/src/main/java/com/baeldung/spring/config/CleanupBean.java similarity index 95% rename from spring-core-2/src/main/java/org/baeldung/spring/config/CleanupBean.java rename to spring-core-2/src/main/java/com/baeldung/spring/config/CleanupBean.java index ac90319745..155b8af9c4 100644 --- a/spring-core-2/src/main/java/org/baeldung/spring/config/CleanupBean.java +++ b/spring-core-2/src/main/java/com/baeldung/spring/config/CleanupBean.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.config; +package com.baeldung.spring.config; import java.util.concurrent.ExecutorService; diff --git a/spring-core-2/src/main/java/com/baeldung/spring/config/CoreConfig.java b/spring-core-2/src/main/java/com/baeldung/spring/config/CoreConfig.java new file mode 100644 index 0000000000..35d245a17e --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/spring/config/CoreConfig.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.config; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +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.WebMvcConfigurer; + +@Configuration +@ComponentScan("com.baeldung.core") +public class CoreConfig implements WebMvcConfigurer { + + public CoreConfig() { + super(); + } + + // beans + + @Bean + public ExecutorService setupExecutor() { + final int coreThreads = 4; + final int maxThreads = 8; + final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(coreThreads, maxThreads, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue()); + threadPoolExecutor.allowCoreThreadTimeOut(true); + return threadPoolExecutor; + } + +} \ No newline at end of file diff --git a/spring-core-2/src/main/java/com/baeldung/spring/config/MvcConfig.java b/spring-core-2/src/main/java/com/baeldung/spring/config/MvcConfig.java new file mode 100644 index 0000000000..cd31cd1128 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/spring/config/MvcConfig.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.config; + +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.ViewControllerRegistry; +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 implements WebMvcConfigurer { + + public MvcConfig() { + super(); + } + + // API + + @Override + public void addViewControllers(final ViewControllerRegistry 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"); + + return bean; + } +} \ No newline at end of file diff --git a/spring-core-2/src/main/java/com/baeldung/spring/config/MyWebApplicationInitializer.java b/spring-core-2/src/main/java/com/baeldung/spring/config/MyWebApplicationInitializer.java new file mode 100644 index 0000000000..034386ade9 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/spring/config/MyWebApplicationInitializer.java @@ -0,0 +1,41 @@ +package com.baeldung.spring.config; + +import java.util.Set; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class MyWebApplicationInitializer implements WebApplicationInitializer +{ + + /** + * Register and configure all Servlet container components necessary to power the web application. + */ + @Override + public void onStartup(final ServletContext sc) throws ServletException { + System.out.println("MyWebApplicationInitializer.onStartup()"); + + // Create the 'root' Spring application context + final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); + root.scan("com.baeldung.spring.config"); + // root.getEnvironment().setDefaultProfiles("embedded"); + + sc.addListener(new ContextLoaderListener(root)); + + DispatcherServlet dv = new DispatcherServlet(root); + + final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc",dv); + appServlet.setLoadOnStartup(1); + 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-core-2/src/main/java/com/baeldung/spring/config/PersistenceConfig.java b/spring-core-2/src/main/java/com/baeldung/spring/config/PersistenceConfig.java new file mode 100644 index 0000000000..f27543af46 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/spring/config/PersistenceConfig.java @@ -0,0 +1,75 @@ +package com.baeldung.spring.config; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +// @Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-mysql.properties" }) +@ComponentScan({ "com.baeldung.persistence" }) +public class PersistenceConfig { + + @Autowired + private Environment env; + + public PersistenceConfig() { + super(); + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.spring.persistence.model" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public DataSource restDataSource() { + 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 HibernateTransactionManager transactionManager() { + final HibernateTransactionManager txManager = new HibernateTransactionManager(); + txManager.setSessionFactory(sessionFactory().getObject()); + + return txManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + +} \ No newline at end of file diff --git a/spring-core-2/src/main/java/com/baeldung/spring/config/ScopesConfig.java b/spring-core-2/src/main/java/com/baeldung/spring/config/ScopesConfig.java new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/asynchronous/AsynchronousSpringEventsConfig.java b/spring-core-2/src/main/java/com/baeldung/springevents/asynchronous/AsynchronousSpringEventsConfig.java similarity index 89% rename from spring-core-2/src/main/java/org/baeldung/springevents/asynchronous/AsynchronousSpringEventsConfig.java rename to spring-core-2/src/main/java/com/baeldung/springevents/asynchronous/AsynchronousSpringEventsConfig.java index 082a986974..085f3b0706 100644 --- a/spring-core-2/src/main/java/org/baeldung/springevents/asynchronous/AsynchronousSpringEventsConfig.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/asynchronous/AsynchronousSpringEventsConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.asynchronous; +package com.baeldung.springevents.asynchronous; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -8,7 +8,7 @@ import org.springframework.context.event.SimpleApplicationEventMulticaster; import org.springframework.core.task.SimpleAsyncTaskExecutor; @Configuration -@ComponentScan("org.baeldung.springevents.synchronous") +@ComponentScan("com.baeldung.springevents.synchronous") public class AsynchronousSpringEventsConfig { @Bean(name = "applicationEventMulticaster") diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/AnnotationDrivenEventListener.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/AnnotationDrivenEventListener.java similarity index 97% rename from spring-core-2/src/main/java/org/baeldung/springevents/synchronous/AnnotationDrivenEventListener.java rename to spring-core-2/src/main/java/com/baeldung/springevents/synchronous/AnnotationDrivenEventListener.java index f750c40a6e..bbb2b5f008 100644 --- a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/AnnotationDrivenEventListener.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/AnnotationDrivenEventListener.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; import org.springframework.context.event.ContextStartedEvent; import org.springframework.context.event.EventListener; diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/ContextRefreshedListener.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/ContextRefreshedListener.java similarity index 93% rename from spring-core-2/src/main/java/org/baeldung/springevents/synchronous/ContextRefreshedListener.java rename to spring-core-2/src/main/java/com/baeldung/springevents/synchronous/ContextRefreshedListener.java index 9f8b2e6e83..31a6c78d00 100644 --- a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/ContextRefreshedListener.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/ContextRefreshedListener.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/CustomSpringEvent.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEvent.java similarity index 89% rename from spring-core-2/src/main/java/org/baeldung/springevents/synchronous/CustomSpringEvent.java rename to spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEvent.java index 1631801ffe..3cf4980be3 100644 --- a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/CustomSpringEvent.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEvent.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; import org.springframework.context.ApplicationEvent; diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/CustomSpringEventListener.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventListener.java similarity index 88% rename from spring-core-2/src/main/java/org/baeldung/springevents/synchronous/CustomSpringEventListener.java rename to spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventListener.java index 69f96966ec..ff7ca7fe39 100644 --- a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/CustomSpringEventListener.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventListener.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/CustomSpringEventPublisher.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java similarity index 96% rename from spring-core-2/src/main/java/org/baeldung/springevents/synchronous/CustomSpringEventPublisher.java rename to spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java index 3182090d5d..e4d7fcdc99 100644 --- a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/CustomSpringEventPublisher.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericSpringAppEvent.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericSpringAppEvent.java similarity index 87% rename from spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericSpringAppEvent.java rename to spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericSpringAppEvent.java index 6804312189..8a50a55f31 100644 --- a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericSpringAppEvent.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericSpringAppEvent.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; import org.springframework.context.ApplicationEvent; diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericSpringEvent.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericSpringEvent.java similarity index 88% rename from spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericSpringEvent.java rename to spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericSpringEvent.java index ce2c223fec..86471221d2 100644 --- a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericSpringEvent.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericSpringEvent.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; public class GenericSpringEvent { diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericSpringEventListener.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericSpringEventListener.java similarity index 92% rename from spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericSpringEventListener.java rename to spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericSpringEventListener.java index 1f5e3e7068..7b0a9727e4 100644 --- a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericSpringEventListener.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericSpringEventListener.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; import org.springframework.context.ApplicationListener; import org.springframework.lang.NonNull; diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericStringSpringAppEvent.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericStringSpringAppEvent.java similarity index 80% rename from spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericStringSpringAppEvent.java rename to spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericStringSpringAppEvent.java index fd214696e7..74839b4708 100644 --- a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericStringSpringAppEvent.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericStringSpringAppEvent.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; class GenericStringSpringAppEvent extends GenericSpringAppEvent { diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericStringSpringEvent.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericStringSpringEvent.java similarity index 80% rename from spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericStringSpringEvent.java rename to spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericStringSpringEvent.java index dd4e4e3ed4..70dda99aa3 100644 --- a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/GenericStringSpringEvent.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/GenericStringSpringEvent.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; public class GenericStringSpringEvent extends GenericSpringEvent { diff --git a/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/SynchronousSpringEventsConfig.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/SynchronousSpringEventsConfig.java new file mode 100644 index 0000000000..58cb220ecb --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/SynchronousSpringEventsConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.springevents.synchronous; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.springevents.synchronous") +public class SynchronousSpringEventsConfig { + +} diff --git a/spring-core-2/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java similarity index 96% rename from spring-core-2/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java rename to spring-core-2/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java index f36b8703ea..e08309d474 100644 --- a/spring-core-2/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java +++ b/spring-core-2/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-core-2/src/main/java/org/baeldung/startup/EventListenerExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/EventListenerExampleBean.java similarity index 94% rename from spring-core-2/src/main/java/org/baeldung/startup/EventListenerExampleBean.java rename to spring-core-2/src/main/java/com/baeldung/startup/EventListenerExampleBean.java index 58e42337cc..a76fc6a2b2 100644 --- a/spring-core-2/src/main/java/org/baeldung/startup/EventListenerExampleBean.java +++ b/spring-core-2/src/main/java/com/baeldung/startup/EventListenerExampleBean.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-core-2/src/main/java/org/baeldung/startup/InitMethodExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/InitMethodExampleBean.java similarity index 95% rename from spring-core-2/src/main/java/org/baeldung/startup/InitMethodExampleBean.java rename to spring-core-2/src/main/java/com/baeldung/startup/InitMethodExampleBean.java index f3d30011f8..a3b12028d1 100644 --- a/spring-core-2/src/main/java/org/baeldung/startup/InitMethodExampleBean.java +++ b/spring-core-2/src/main/java/com/baeldung/startup/InitMethodExampleBean.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import java.util.Arrays; diff --git a/spring-core-2/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java similarity index 96% rename from spring-core-2/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java rename to spring-core-2/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java index 5d6f8c9d88..c625a172fd 100644 --- a/spring-core-2/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java +++ b/spring-core-2/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import java.util.Arrays; diff --git a/spring-core-2/src/main/java/org/baeldung/startup/InvalidInitExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java similarity index 93% rename from spring-core-2/src/main/java/org/baeldung/startup/InvalidInitExampleBean.java rename to spring-core-2/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java index 0b9c6f0c7d..d31aee8acd 100644 --- a/spring-core-2/src/main/java/org/baeldung/startup/InvalidInitExampleBean.java +++ b/spring-core-2/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; diff --git a/spring-core-2/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java similarity index 95% rename from spring-core-2/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java rename to spring-core-2/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java index d25a83942a..ade7573bbe 100644 --- a/spring-core-2/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java +++ b/spring-core-2/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import java.util.Arrays; diff --git a/spring-core-2/src/main/java/org/baeldung/startup/PostConstructExampleBean.java b/spring-core-2/src/main/java/com/baeldung/startup/PostConstructExampleBean.java similarity index 95% rename from spring-core-2/src/main/java/org/baeldung/startup/PostConstructExampleBean.java rename to spring-core-2/src/main/java/com/baeldung/startup/PostConstructExampleBean.java index 2397c3a0a2..1001043d86 100644 --- a/spring-core-2/src/main/java/org/baeldung/startup/PostConstructExampleBean.java +++ b/spring-core-2/src/main/java/com/baeldung/startup/PostConstructExampleBean.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import java.util.Arrays; diff --git a/spring-core-2/src/main/java/com/baeldung/startup/SpringStartupConfig.java b/spring-core-2/src/main/java/com/baeldung/startup/SpringStartupConfig.java new file mode 100644 index 0000000000..ad6492dadc --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/startup/SpringStartupConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.startup; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.startup") +public class SpringStartupConfig { +} \ No newline at end of file diff --git a/spring-core-2/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java b/spring-core-2/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java similarity index 95% rename from spring-core-2/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java rename to spring-core-2/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java index e02388dea3..2cc5e6abcb 100644 --- a/spring-core-2/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java +++ b/spring-core-2/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-core-2/src/main/java/org/baeldung/autowire/sample/App.java b/spring-core-2/src/main/java/org/baeldung/autowire/sample/App.java deleted file mode 100644 index ed0c90d5b1..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/autowire/sample/App.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.baeldung.autowire.sample; - -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -public class App { - public static void main(String[] args) { - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); - FooService fooService = ctx.getBean(FooService.class); - fooService.doStuff(); - } -} diff --git a/spring-core-2/src/main/java/org/baeldung/autowire/sample/AppConfig.java b/spring-core-2/src/main/java/org/baeldung/autowire/sample/AppConfig.java deleted file mode 100644 index 117dfe1027..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/autowire/sample/AppConfig.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.autowire.sample; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.autowire.sample") -public class AppConfig { - -} diff --git a/spring-core-2/src/main/java/org/baeldung/autowire/sample/FooDAO.java b/spring-core-2/src/main/java/org/baeldung/autowire/sample/FooDAO.java deleted file mode 100644 index 3d3deaa077..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/autowire/sample/FooDAO.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.autowire.sample; - -public class FooDAO { - -} diff --git a/spring-core-2/src/main/java/org/baeldung/autowire/sample/FooService.java b/spring-core-2/src/main/java/org/baeldung/autowire/sample/FooService.java deleted file mode 100644 index a3638960cc..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/autowire/sample/FooService.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.autowire.sample; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class FooService { - - @Autowired - @FormatterType("Foo") - private Formatter formatter; - - public String doStuff() { - return formatter.format(); - } - -} diff --git a/spring-core-2/src/main/java/org/baeldung/autowire/sample/Formatter.java b/spring-core-2/src/main/java/org/baeldung/autowire/sample/Formatter.java deleted file mode 100644 index 05cd5f1c26..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/autowire/sample/Formatter.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.baeldung.autowire.sample; - -public interface Formatter { - - String format(); - -} diff --git a/spring-core-2/src/main/java/org/baeldung/bean/config/ConstructorBasedShipConfig.java b/spring-core-2/src/main/java/org/baeldung/bean/config/ConstructorBasedShipConfig.java deleted file mode 100644 index f0e6e8868e..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/bean/config/ConstructorBasedShipConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung.bean.config; - -import org.baeldung.bean.injection.Helm; -import org.baeldung.bean.injection.Ship; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class ConstructorBasedShipConfig { - - @Bean - public Ship ship() { - return new Ship(helm()); - } - - @Bean - public Helm helm() { - return new Helm(); - } -} diff --git a/spring-core-2/src/main/java/org/baeldung/bean/config/SetterBasedShipConfig.java b/spring-core-2/src/main/java/org/baeldung/bean/config/SetterBasedShipConfig.java deleted file mode 100644 index 7cd6de1c74..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/bean/config/SetterBasedShipConfig.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.bean.config; - -import org.baeldung.bean.injection.Helm; -import org.baeldung.bean.injection.Ship; -import org.springframework.context.annotation.Bean; - -public class SetterBasedShipConfig { - - @Bean - public Ship ship() { - return new Ship(); - } - - @Bean - public Helm helm() { - return new Helm(); - } -} diff --git a/spring-core-2/src/main/java/org/baeldung/customannotation/CustomAnnotationConfiguration.java b/spring-core-2/src/main/java/org/baeldung/customannotation/CustomAnnotationConfiguration.java deleted file mode 100644 index b8f312d778..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/customannotation/CustomAnnotationConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.customannotation; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.customannotation") -public class CustomAnnotationConfiguration { -} diff --git a/spring-core-2/src/main/java/org/baeldung/nullibility/Person.java b/spring-core-2/src/main/java/org/baeldung/nullibility/Person.java deleted file mode 100644 index 08c77c9e9c..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/nullibility/Person.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.baeldung.nullibility; - -import org.springframework.lang.NonNull; -import org.springframework.lang.Nullable; - -public class Person { - @NonNull - private String fullName; - @Nullable - private String nickName; - - void setFullName(String fullName) { - if (fullName != null && fullName.isEmpty()) { - fullName = null; - } - this.fullName = fullName; - } - - void setNickName(String nickName) { - if (nickName != null && nickName.isEmpty()) { - nickName = null; - } - this.nickName = nickName; - } - - String getFullName() { - return fullName; - } - - String getNickName() { - return nickName; - } -} diff --git a/spring-core-2/src/main/java/org/baeldung/nullibility/package-info.java b/spring-core-2/src/main/java/org/baeldung/nullibility/package-info.java deleted file mode 100644 index 446f2e316e..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/nullibility/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -@NonNullApi -@NonNullFields -package org.baeldung.nullibility; - -import org.springframework.lang.NonNullApi; -import org.springframework.lang.NonNullFields; \ No newline at end of file diff --git a/spring-core-2/src/main/java/org/baeldung/order/Rating.java b/spring-core-2/src/main/java/org/baeldung/order/Rating.java deleted file mode 100644 index 10f2780522..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/order/Rating.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.baeldung.order; - -public interface Rating { - - int getRating(); -} diff --git a/spring-core-2/src/main/java/org/baeldung/persistence/Setup.java b/spring-core-2/src/main/java/org/baeldung/persistence/Setup.java deleted file mode 100644 index 5cba4e70fb..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/persistence/Setup.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.persistence; - -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.stereotype.Component; - -@Component -public class Setup implements ApplicationListener { - - private boolean setupDone; - - public Setup() { - super(); - } - - // - - @Override - public final void onApplicationEvent(final ContextRefreshedEvent event) { - if (!setupDone) { - System.out.println(); - setupDone = true; - } - } - -} diff --git a/spring-core-2/src/main/java/org/baeldung/primary/Config.java b/spring-core-2/src/main/java/org/baeldung/primary/Config.java deleted file mode 100644 index bdcfe019e6..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/primary/Config.java +++ /dev/null @@ -1,22 +0,0 @@ -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-core-2/src/main/java/org/baeldung/primary/Employee.java b/spring-core-2/src/main/java/org/baeldung/primary/Employee.java deleted file mode 100644 index 9168387613..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/primary/Employee.java +++ /dev/null @@ -1,20 +0,0 @@ -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-core-2/src/main/java/org/baeldung/profiles/DatasourceConfig.java b/spring-core-2/src/main/java/org/baeldung/profiles/DatasourceConfig.java deleted file mode 100644 index 8fde925fd8..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/profiles/DatasourceConfig.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.profiles; - -public interface DatasourceConfig { - void setup(); -} diff --git a/spring-core-2/src/main/java/org/baeldung/sample/Bar.java b/spring-core-2/src/main/java/org/baeldung/sample/Bar.java deleted file mode 100644 index 54e8d54418..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/sample/Bar.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.sample; - -public class Bar { - -} diff --git a/spring-core-2/src/main/java/org/baeldung/sample/Foo.java b/spring-core-2/src/main/java/org/baeldung/sample/Foo.java deleted file mode 100644 index 562a00121a..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/sample/Foo.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.sample; - -public class Foo { - -} diff --git a/spring-core-2/src/main/java/org/baeldung/scopes/Person.java b/spring-core-2/src/main/java/org/baeldung/scopes/Person.java deleted file mode 100644 index b070007a5c..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/scopes/Person.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.baeldung.scopes; - -public class Person { - private String name; - private int age; - - public Person() { - } - - public Person(final String name, final int age) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - @Override - public String toString() { - return "Person [name=" + name + "]"; - } - -} diff --git a/spring-core-2/src/main/java/org/baeldung/spring/config/CoreConfig.java b/spring-core-2/src/main/java/org/baeldung/spring/config/CoreConfig.java deleted file mode 100644 index 0d753dc447..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/spring/config/CoreConfig.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.baeldung.spring.config; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -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.WebMvcConfigurer; - -@Configuration -@ComponentScan("org.baeldung.core") -public class CoreConfig implements WebMvcConfigurer { - - public CoreConfig() { - super(); - } - - // beans - - @Bean - public ExecutorService setupExecutor() { - final int coreThreads = 4; - final int maxThreads = 8; - final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(coreThreads, maxThreads, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue()); - threadPoolExecutor.allowCoreThreadTimeOut(true); - return threadPoolExecutor; - } - -} \ No newline at end of file diff --git a/spring-core-2/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java b/spring-core-2/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java deleted file mode 100644 index 9f4b73f609..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.baeldung.spring.config; - -import java.util.Set; - -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 -{ - - /** - * Register and configure all Servlet container components necessary to power the web application. - */ - @Override - public void onStartup(final ServletContext sc) throws ServletException { - System.out.println("MainWebAppInitializer.onStartup()"); - - // Create the 'root' Spring application context - final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.scan("org.baeldung.spring.config"); - // root.getEnvironment().setDefaultProfiles("embedded"); - - sc.addListener(new ContextLoaderListener(root)); - - DispatcherServlet dv = new DispatcherServlet(root); - - final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc",dv); - appServlet.setLoadOnStartup(1); - 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-core-2/src/main/java/org/baeldung/spring/config/MvcConfig.java b/spring-core-2/src/main/java/org/baeldung/spring/config/MvcConfig.java deleted file mode 100644 index e550733c47..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/spring/config/MvcConfig.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.baeldung.spring.config; - -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.ViewControllerRegistry; -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 implements WebMvcConfigurer { - - public MvcConfig() { - super(); - } - - // API - - @Override - public void addViewControllers(final ViewControllerRegistry 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"); - - return bean; - } -} \ No newline at end of file diff --git a/spring-core-2/src/main/java/org/baeldung/spring/config/PersistenceConfig.java b/spring-core-2/src/main/java/org/baeldung/spring/config/PersistenceConfig.java deleted file mode 100644 index ffe88596fa..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/spring/config/PersistenceConfig.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.baeldung.spring.config; - -import java.util.Properties; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.hibernate5.HibernateTransactionManager; -import org.springframework.orm.hibernate5.LocalSessionFactoryBean; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.google.common.base.Preconditions; - -// @Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-mysql.properties" }) -@ComponentScan({ "org.baeldung.persistence" }) -public class PersistenceConfig { - - @Autowired - private Environment env; - - public PersistenceConfig() { - super(); - } - - @Bean - public LocalSessionFactoryBean sessionFactory() { - final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); - sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "org.baeldung.spring.persistence.model" }); - sessionFactory.setHibernateProperties(hibernateProperties()); - - return sessionFactory; - } - - @Bean - public DataSource restDataSource() { - 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 HibernateTransactionManager transactionManager() { - final HibernateTransactionManager txManager = new HibernateTransactionManager(); - txManager.setSessionFactory(sessionFactory().getObject()); - - return txManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - final Properties hibernateProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); - return hibernateProperties; - } - -} \ No newline at end of file diff --git a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/SynchronousSpringEventsConfig.java b/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/SynchronousSpringEventsConfig.java deleted file mode 100644 index fff8a7e4b5..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/springevents/synchronous/SynchronousSpringEventsConfig.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.springevents.synchronous; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.springevents.synchronous") -public class SynchronousSpringEventsConfig { - -} diff --git a/spring-core-2/src/main/java/org/baeldung/startup/SpringStartupConfig.java b/spring-core-2/src/main/java/org/baeldung/startup/SpringStartupConfig.java deleted file mode 100644 index 12854e1be5..0000000000 --- a/spring-core-2/src/main/java/org/baeldung/startup/SpringStartupConfig.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.startup; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.startup") -public class SpringStartupConfig { -} \ No newline at end of file diff --git a/spring-core-2/src/main/resources/beanInjection-constructor.xml b/spring-core-2/src/main/resources/beanInjection-constructor.xml index 5a2ffe767c..cbb8f98bb9 100644 --- a/spring-core-2/src/main/resources/beanInjection-constructor.xml +++ b/spring-core-2/src/main/resources/beanInjection-constructor.xml @@ -4,12 +4,12 @@ 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-core-2/src/main/resources/beanInjection-setter.xml b/spring-core-2/src/main/resources/beanInjection-setter.xml index 0e82e3be1c..1440df9702 100644 --- a/spring-core-2/src/main/resources/beanInjection-setter.xml +++ b/spring-core-2/src/main/resources/beanInjection-setter.xml @@ -4,11 +4,11 @@ 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-core-2/src/main/resources/jdbc/springJdbc-config.xml b/spring-core-2/src/main/resources/jdbc/springJdbc-config.xml index 5fd2699b41..e3d7452eb1 100644 --- a/spring-core-2/src/main/resources/jdbc/springJdbc-config.xml +++ b/spring-core-2/src/main/resources/jdbc/springJdbc-config.xml @@ -4,7 +4,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd" > - + diff --git a/spring-core-2/src/main/resources/scopes.xml b/spring-core-2/src/main/resources/scopes.xml index 8fdb186c28..f7b554ec49 100644 --- a/spring-core-2/src/main/resources/scopes.xml +++ b/spring-core-2/src/main/resources/scopes.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - + - + diff --git a/spring-core-2/src/main/resources/springProfiles-config.xml b/spring-core-2/src/main/resources/springProfiles-config.xml index 985ab6ba86..5eb6bfcd7f 100644 --- a/spring-core-2/src/main/resources/springProfiles-config.xml +++ b/spring-core-2/src/main/resources/springProfiles-config.xml @@ -6,10 +6,10 @@ > - + - + \ No newline at end of file diff --git a/spring-core-2/src/main/resources/startupConfig.xml b/spring-core-2/src/main/resources/startupConfig.xml index 8226665a90..d42e0f6c2b 100644 --- a/spring-core-2/src/main/resources/startupConfig.xml +++ b/spring-core-2/src/main/resources/startupConfig.xml @@ -4,13 +4,13 @@ http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> \ No newline at end of file diff --git a/spring-core-2/src/test/java/org/baeldung/autowire/sample/FooServiceIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.java similarity index 94% rename from spring-core-2/src/test/java/org/baeldung/autowire/sample/FooServiceIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.java index 941fc4baff..34ba7902ca 100644 --- a/spring-core-2/src/test/java/org/baeldung/autowire/sample/FooServiceIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.autowire.sample; +package com.baeldung.autowire.sample; import org.junit.Assert; import org.junit.Test; diff --git a/spring-core-2/src/test/java/org/baeldung/bean/injection/ConstructorBasedBeanInjectionWithJavaConfigIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/bean/injection/ConstructorBasedBeanInjectionWithJavaConfigIntegrationTest.java similarity index 87% rename from spring-core-2/src/test/java/org/baeldung/bean/injection/ConstructorBasedBeanInjectionWithJavaConfigIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/bean/injection/ConstructorBasedBeanInjectionWithJavaConfigIntegrationTest.java index 447a09d69e..fb3f973f29 100644 --- a/spring-core-2/src/test/java/org/baeldung/bean/injection/ConstructorBasedBeanInjectionWithJavaConfigIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/bean/injection/ConstructorBasedBeanInjectionWithJavaConfigIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.bean.injection; +package com.baeldung.bean.injection; -import org.baeldung.bean.config.ConstructorBasedShipConfig; +import com.baeldung.bean.config.ConstructorBasedShipConfig; import org.junit.Assert; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; diff --git a/spring-core-2/src/test/java/org/baeldung/bean/injection/ConstructorBasedBeanInjectionWithXMLConfigIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/bean/injection/ConstructorBasedBeanInjectionWithXMLConfigIntegrationTest.java similarity index 95% rename from spring-core-2/src/test/java/org/baeldung/bean/injection/ConstructorBasedBeanInjectionWithXMLConfigIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/bean/injection/ConstructorBasedBeanInjectionWithXMLConfigIntegrationTest.java index 9f6011d851..18ce5ce8ed 100644 --- a/spring-core-2/src/test/java/org/baeldung/bean/injection/ConstructorBasedBeanInjectionWithXMLConfigIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/bean/injection/ConstructorBasedBeanInjectionWithXMLConfigIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.bean.injection; +package com.baeldung.bean.injection; import org.junit.Assert; import org.junit.Test; diff --git a/spring-core-2/src/test/java/org/baeldung/bean/injection/SetterBasedBeanInjectionWithJavaConfigIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/bean/injection/SetterBasedBeanInjectionWithJavaConfigIntegrationTest.java similarity index 87% rename from spring-core-2/src/test/java/org/baeldung/bean/injection/SetterBasedBeanInjectionWithJavaConfigIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/bean/injection/SetterBasedBeanInjectionWithJavaConfigIntegrationTest.java index 1c15775093..1e2147d2bc 100644 --- a/spring-core-2/src/test/java/org/baeldung/bean/injection/SetterBasedBeanInjectionWithJavaConfigIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/bean/injection/SetterBasedBeanInjectionWithJavaConfigIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.bean.injection; +package com.baeldung.bean.injection; -import org.baeldung.bean.config.SetterBasedShipConfig; +import com.baeldung.bean.config.SetterBasedShipConfig; import org.junit.Assert; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; diff --git a/spring-core-2/src/test/java/org/baeldung/bean/injection/SetterBasedBeanInjectionWithXMLConfigIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/bean/injection/SetterBasedBeanInjectionWithXMLConfigIntegrationTest.java similarity index 94% rename from spring-core-2/src/test/java/org/baeldung/bean/injection/SetterBasedBeanInjectionWithXMLConfigIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/bean/injection/SetterBasedBeanInjectionWithXMLConfigIntegrationTest.java index bc17a08383..9c7526a7be 100644 --- a/spring-core-2/src/test/java/org/baeldung/bean/injection/SetterBasedBeanInjectionWithXMLConfigIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/bean/injection/SetterBasedBeanInjectionWithXMLConfigIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.bean.injection; +package com.baeldung.bean.injection; import org.junit.Assert; import org.junit.Test; diff --git a/spring-core-2/src/test/java/com/baeldung/customannotation/Account.java b/spring-core-2/src/test/java/com/baeldung/customannotation/Account.java new file mode 100644 index 0000000000..cfdd8815e4 --- /dev/null +++ b/spring-core-2/src/test/java/com/baeldung/customannotation/Account.java @@ -0,0 +1,40 @@ +package com.baeldung.customannotation; + +import java.io.Serializable; + +public class Account implements Serializable { + + private static final long serialVersionUID = 7857541629844398625L; + + private Long id; + private String email; + private Person person; + + public Account() { + } + + 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 Person getPerson() { + return person; + } + + public void setPerson(Person person) { + this.person = person; + } + +} diff --git a/spring-core-2/src/test/java/org/baeldung/customannotation/BeanWithGenericDAO.java b/spring-core-2/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java similarity index 89% rename from spring-core-2/src/test/java/org/baeldung/customannotation/BeanWithGenericDAO.java rename to spring-core-2/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java index 9ba915f296..a0707f263b 100644 --- a/spring-core-2/src/test/java/org/baeldung/customannotation/BeanWithGenericDAO.java +++ b/spring-core-2/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java @@ -1,4 +1,4 @@ -package org.baeldung.customannotation; +package com.baeldung.customannotation; import org.springframework.stereotype.Repository; diff --git a/spring-core-2/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java similarity index 98% rename from spring-core-2/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java index ae3d53fb9b..1baea4505b 100644 --- a/spring-core-2/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.customannotation; +package com.baeldung.customannotation; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; diff --git a/spring-core-2/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java similarity index 98% rename from spring-core-2/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java index bab2574cd2..bc7a5f7246 100644 --- a/spring-core-2/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.customannotation; +package com.baeldung.customannotation; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; diff --git a/spring-core-2/src/test/java/com/baeldung/customannotation/Person.java b/spring-core-2/src/test/java/com/baeldung/customannotation/Person.java new file mode 100644 index 0000000000..4fa70e51af --- /dev/null +++ b/spring-core-2/src/test/java/com/baeldung/customannotation/Person.java @@ -0,0 +1,31 @@ +package com.baeldung.customannotation; + +import java.io.Serializable; + +public class Person implements Serializable { + + private static final long serialVersionUID = 9005331414216374586L; + + private Long id; + private String name; + + public Person() { + } + + 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/spring-core-2/src/test/java/org/baeldung/customscope/TenantScopeIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java similarity index 96% rename from spring-core-2/src/test/java/org/baeldung/customscope/TenantScopeIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java index e873ac5065..1cd7357a09 100644 --- a/spring-core-2/src/test/java/org/baeldung/customscope/TenantScopeIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.customscope; +package com.baeldung.customscope; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; @@ -46,7 +46,7 @@ public class TenantScopeIntegrationTest { public final void whenComponentScan_thenContextContainsFooAndBar() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); try { - ctx.scan("org.baeldung.customscope"); + ctx.scan("com.baeldung.customscope"); ctx.refresh(); TenantBean foo = (TenantBean) ctx.getBean("foo", TenantBean.class); diff --git a/spring-core-2/src/test/java/org/baeldung/order/RatingRetrieverUnitTest.java b/spring-core-2/src/test/java/com/baeldung/order/RatingRetrieverUnitTest.java similarity index 93% rename from spring-core-2/src/test/java/org/baeldung/order/RatingRetrieverUnitTest.java rename to spring-core-2/src/test/java/com/baeldung/order/RatingRetrieverUnitTest.java index 96993ccd7c..342a4c5f05 100644 --- a/spring-core-2/src/test/java/org/baeldung/order/RatingRetrieverUnitTest.java +++ b/spring-core-2/src/test/java/com/baeldung/order/RatingRetrieverUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.order; +package com.baeldung.order; import static org.hamcrest.CoreMatchers.equalTo; @@ -21,7 +21,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; public class RatingRetrieverUnitTest { @Configuration - @ComponentScan(basePackages = {"org.baeldung.order"}) + @ComponentScan(basePackages = {"com.baeldung.order"}) static class ContextConfiguration {} @Autowired diff --git a/spring-core-2/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java similarity index 96% rename from spring-core-2/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java index cf5ca132e6..81b136f5ba 100644 --- a/spring-core-2/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.profiles; +package com.baeldung.profiles; import org.junit.Assert; import org.junit.Test; diff --git a/spring-core-2/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java similarity index 97% rename from spring-core-2/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java index 5bacaef07b..b863fe30c1 100644 --- a/spring-core-2/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.profiles; +package com.baeldung.profiles; import org.junit.Assert; import org.junit.Test; diff --git a/spring-core-2/src/test/java/org/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java similarity index 91% rename from spring-core-2/src/test/java/org/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java index 929d088a14..1380e34ebd 100644 --- a/spring-core-2/src/test/java/org/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.profiles; +package com.baeldung.profiles; import org.junit.Assert; import org.junit.Test; @@ -16,7 +16,7 @@ public class SpringProfilesWithMavenPropertiesIntegrationTest { DatasourceConfig datasourceConfig; @Test - public void testSpringProfiles() { + public void setupDatasource() { Assert.assertTrue(datasourceConfig instanceof DevDatasourceConfig); } } \ No newline at end of file diff --git a/spring-core-2/src/test/java/org/baeldung/profiles/SpringProfilesWithXMLIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithXMLIntegrationTest.java similarity index 98% rename from spring-core-2/src/test/java/org/baeldung/profiles/SpringProfilesWithXMLIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithXMLIntegrationTest.java index 2b46a50588..4fc90b2e7c 100644 --- a/spring-core-2/src/test/java/org/baeldung/profiles/SpringProfilesWithXMLIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithXMLIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.profiles; +package com.baeldung.profiles; import org.junit.Assert; import org.junit.Test; diff --git a/spring-core-2/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/scopes/ScopesIntegrationTest.java similarity index 98% rename from spring-core-2/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/scopes/ScopesIntegrationTest.java index 0ae99610f6..ae4df3b632 100644 --- a/spring-core-2/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/scopes/ScopesIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.scopes; +package com.baeldung.scopes; import org.junit.Assert; import org.junit.Test; diff --git a/spring-core-2/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java similarity index 88% rename from spring-core-2/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java index e12baed7e0..4f8035bcbe 100644 --- a/spring-core-2/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.springevents.asynchronous; +package com.baeldung.springevents.asynchronous; -import org.baeldung.springevents.synchronous.CustomSpringEventPublisher; +import com.baeldung.springevents.synchronous.CustomSpringEventPublisher; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-core-2/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java similarity index 87% rename from spring-core-2/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java index e8e6f91b06..0ba43cdcbb 100644 --- a/spring-core-2/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java @@ -1,6 +1,5 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; -import org.baeldung.springevents.synchronous.SynchronousSpringEventsConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-core-2/src/test/java/org/baeldung/springevents/synchronous/GenericAppEventListenerIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/GenericAppEventListenerIntegrationTest.java similarity index 95% rename from spring-core-2/src/test/java/org/baeldung/springevents/synchronous/GenericAppEventListenerIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/springevents/synchronous/GenericAppEventListenerIntegrationTest.java index f183314b6d..7f5314b420 100644 --- a/spring-core-2/src/test/java/org/baeldung/springevents/synchronous/GenericAppEventListenerIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/GenericAppEventListenerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-core-2/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java similarity index 97% rename from spring-core-2/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java index b169cfec36..1d624d2289 100644 --- a/spring-core-2/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.springevents.synchronous; +package com.baeldung.springevents.synchronous; import org.junit.Ignore; import org.junit.Test; diff --git a/spring-core-2/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java similarity index 98% rename from spring-core-2/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java index 6263482948..b58c093c31 100644 --- a/spring-core-2/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.assertj.core.api.Assertions; import org.junit.Test; diff --git a/spring-core-2/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java similarity index 96% rename from spring-core-2/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java rename to spring-core-2/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java index a46d24fa3b..3dfd4835df 100644 --- a/spring-core-2/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-core-2/src/test/java/org/baeldung/customannotation/Account.java b/spring-core-2/src/test/java/org/baeldung/customannotation/Account.java deleted file mode 100644 index 04545e5b83..0000000000 --- a/spring-core-2/src/test/java/org/baeldung/customannotation/Account.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.customannotation; - -import java.io.Serializable; - -public class Account implements Serializable { - - private static final long serialVersionUID = 7857541629844398625L; - - private Long id; - private String email; - private Person person; - - public Account() { - } - - 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 Person getPerson() { - return person; - } - - public void setPerson(Person person) { - this.person = person; - } - -} diff --git a/spring-core-2/src/test/java/org/baeldung/customannotation/Person.java b/spring-core-2/src/test/java/org/baeldung/customannotation/Person.java deleted file mode 100644 index 3babc8f0a2..0000000000 --- a/spring-core-2/src/test/java/org/baeldung/customannotation/Person.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.baeldung.customannotation; - -import java.io.Serializable; - -public class Person implements Serializable { - - private static final long serialVersionUID = 9005331414216374586L; - - private Long id; - private String name; - - public Person() { - } - - 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/spring-core-3/README.md b/spring-core-3/README.md index ae2d33c196..6c210b23ef 100644 --- a/spring-core-3/README.md +++ b/spring-core-3/README.md @@ -8,4 +8,7 @@ This module contains articles about core Spring functionality - [Guide to the Spring BeanFactory](https://www.baeldung.com/spring-beanfactory) - [How to use the Spring FactoryBean?](https://www.baeldung.com/spring-factorybean) - [Spring – Injecting Collections](https://www.baeldung.com/spring-injecting-collections) +- [Design Patterns in the Spring Framework](https://www.baeldung.com/spring-framework-design-patterns) +- [Injecting a Value in a Static Field in Spring](https://www.baeldung.com/spring-inject-static-field) +- [Difference Between BeanFactory and ApplicationContext](https://www.baeldung.com/spring-beanfactory-vs-applicationcontext) - More articles: [[<-- prev]](/spring-core-2) diff --git a/spring-core-3/pom.xml b/spring-core-3/pom.xml index cd82f23320..205259e8e4 100644 --- a/spring-core-3/pom.xml +++ b/spring-core-3/pom.xml @@ -1,72 +1,88 @@ - - - 4.0.0 - spring-core-3 - spring-core-3 - - - com.baeldung - parent-spring-5 - 0.0.1-SNAPSHOT - ../parent-spring-5 - - - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - org.springframework - spring-core - ${spring.version} - - - javax.annotation - javax.annotation-api - ${annotation-api.version} - - - org.springframework - spring-test - ${spring.version} - test - - - org.junit.jupiter - junit-jupiter-engine - ${junit-jupiter.version} - test - - - org.junit.jupiter - junit-jupiter-api - ${junit-jupiter.version} - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.surefire.version} - - - - - - 2.22.1 - 1.3.2 - - + + + 4.0.0 + spring-core-3 + spring-core-3 + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring.boot.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + javax.annotation + javax.annotation-api + ${annotation-api.version} + + + org.springframework + spring-test + ${spring.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven.surefire.version} + + + + + + 2.22.1 + 1.3.2 + 2.2.2.RELEASE + + \ No newline at end of file diff --git a/spring-core-3/src/main/java/com/baeldung/factorybean/README.md b/spring-core-3/src/main/java/com/baeldung/factorybean/README.md deleted file mode 100644 index 13f9f379e0..0000000000 --- a/spring-core-3/src/main/java/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/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java new file mode 100644 index 0000000000..65e249b15b --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java @@ -0,0 +1,21 @@ +package com.baeldung.ioccontainer.bean; + +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; + +public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor { + private static boolean isBeanFactoryPostProcessorRegistered = false; + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory){ + setBeanFactoryPostProcessorRegistered(true); + } + + public static boolean isBeanFactoryPostProcessorRegistered() { + return isBeanFactoryPostProcessorRegistered; + } + + public static void setBeanFactoryPostProcessorRegistered(boolean isBeanFactoryPostProcessorRegistered) { + CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered = isBeanFactoryPostProcessorRegistered; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java new file mode 100644 index 0000000000..6f99a5f0db --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java @@ -0,0 +1,21 @@ +package com.baeldung.ioccontainer.bean; + +import org.springframework.beans.factory.config.BeanPostProcessor; + +public class CustomBeanPostProcessor implements BeanPostProcessor { + private static boolean isBeanPostProcessorRegistered = false; + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName){ + setBeanPostProcessorRegistered(true); + return bean; + } + + public static boolean isBeanPostProcessorRegistered() { + return isBeanPostProcessorRegistered; + } + + public static void setBeanPostProcessorRegistered(boolean isBeanPostProcessorRegistered) { + CustomBeanPostProcessor.isBeanPostProcessorRegistered = isBeanPostProcessorRegistered; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java new file mode 100644 index 0000000000..404f323b66 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java @@ -0,0 +1,17 @@ +package com.baeldung.ioccontainer.bean; + +public class Student { + private static boolean isBeanInstantiated = false; + + public void postConstruct() { + setBeanInstantiated(true); + } + + public static boolean isBeanInstantiated() { + return isBeanInstantiated; + } + + public static void setBeanInstantiated(boolean isBeanInstantiated) { + Student.isBeanInstantiated = isBeanInstantiated; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/Application.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/Application.java new file mode 100644 index 0000000000..8f0134d83c --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/Application.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.patterns.factory; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class Application { + + @SuppressWarnings("resource") + public static void main(String[] args) { + + ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class); + + Foo foo = context.getBean(Foo.class); + Bar bar = context.getBean(Bar.class, "Some name"); + + System.out.println(foo); + System.out.println("Bar's name: " + bar.getName()); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/ApplicationConfig.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/ApplicationConfig.java new file mode 100644 index 0000000000..626947cfd5 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/ApplicationConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.patterns.factory; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackageClasses = ApplicationConfig.class) +public class ApplicationConfig { +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/Bar.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/Bar.java new file mode 100644 index 0000000000..8bd742c481 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/Bar.java @@ -0,0 +1,20 @@ +package com.baeldung.spring.patterns.factory; + +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class Bar { + + private String name; + + public Bar(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/Foo.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/Foo.java new file mode 100644 index 0000000000..5edba6c50d --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/factory/Foo.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.patterns.factory; + +import org.springframework.stereotype.Component; + +@Component +public class Foo { +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/Application.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/Application.java new file mode 100644 index 0000000000..d00f51ec96 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.patterns.proxy; + +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-core-3/src/main/java/com/baeldung/spring/patterns/proxy/Book.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/Book.java new file mode 100644 index 0000000000..112396e232 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/Book.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.patterns.proxy; + +public class Book { + + private String author; + + public Book(String author) { + this.author = author; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/BookController.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/BookController.java new file mode 100644 index 0000000000..ab192826b8 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/BookController.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.patterns.proxy; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class BookController { + + @Autowired + private BookManager manager; + + @PostMapping("/book") + public Book create(@RequestParam String author) { + return manager.create(author); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/BookManager.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/BookManager.java new file mode 100644 index 0000000000..d82218e404 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/BookManager.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.patterns.proxy; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class BookManager { + + @Autowired + private BookRepository repository; + + @Transactional + public Book create(String author) { + System.out.println(repository.getClass().getName()); + return repository.create(author); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/BookRepository.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/BookRepository.java new file mode 100644 index 0000000000..b100bc0a61 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/proxy/BookRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.patterns.proxy; + +import org.springframework.stereotype.Repository; + +@Repository +public class BookRepository { + + public Book create(String author) { + return new Book(author); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/Application.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/Application.java new file mode 100644 index 0000000000..5d7545790a --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.patterns.singleton; + +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-core-3/src/main/java/com/baeldung/spring/patterns/singleton/Book.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/Book.java new file mode 100644 index 0000000000..31d9d83683 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/Book.java @@ -0,0 +1,4 @@ +package com.baeldung.spring.patterns.singleton; + +public class Book { +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/BookController.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/BookController.java new file mode 100644 index 0000000000..aa4bdb8371 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/BookController.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.patterns.singleton; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class BookController { + + @Autowired + private BookRepository repository; + + @GetMapping("/book/{id}") + public Book findById(@PathVariable long id) { + System.out.println(repository); + return repository.findById(id).get(); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/BookRepository.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/BookRepository.java new file mode 100644 index 0000000000..3fde153f31 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/BookRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.patterns.singleton; + +import java.util.Optional; + +import org.springframework.stereotype.Repository; + +@Repository +public class BookRepository { + + public long count() { + return 1; + } + + public Optional findById(long id) { + return Optional.of(new Book()); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/LibraryController.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/LibraryController.java new file mode 100644 index 0000000000..76e273e2fb --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/singleton/LibraryController.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.patterns.singleton; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class LibraryController { + + @Autowired + private BookRepository repository; + + @GetMapping("/count") + public Long findCount() { + System.out.println(repository); + return repository.count(); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/template/Book.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/template/Book.java new file mode 100644 index 0000000000..d601f01c67 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/template/Book.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.patterns.template; + +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; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/spring/patterns/template/BookRowMapper.java b/spring-core-3/src/main/java/com/baeldung/spring/patterns/template/BookRowMapper.java new file mode 100644 index 0000000000..3fe7bb8e59 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/spring/patterns/template/BookRowMapper.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.patterns.template; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.springframework.jdbc.core.RowMapper; + +public class BookRowMapper implements RowMapper { + + @Override + public Book mapRow(ResultSet rs, int rowNum) throws SQLException { + + Book book = new Book(); + + book.setId(rs.getLong("id")); + book.setTitle(rs.getString("title")); + book.setAuthor(rs.getString("author")); + + return book; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/Application.java b/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/Application.java new file mode 100644 index 0000000000..45c47c955f --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/Application.java @@ -0,0 +1,16 @@ +package com.baeldung.staticvalue.injection; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@PropertySource("/application.properties") + +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/PropertyController.java b/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/PropertyController.java new file mode 100644 index 0000000000..f5910ea4f8 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/staticvalue/injection/PropertyController.java @@ -0,0 +1,30 @@ +package com.baeldung.staticvalue.injection; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Arrays; +import java.util.List; + +@RestController +public class PropertyController { + + @Value("${name}") + private String name; + + @Value("${name}") + private static String NAME_NULL; + + private static String NAME_STATIC; + + @Value("${name}") + public void setNameStatic(String name){ + PropertyController.NAME_STATIC = name; + } + + @GetMapping("/properties") + public List getProperties(){ + return Arrays.asList(this.name, NAME_STATIC, NAME_NULL) ; + } +} diff --git a/spring-core-3/src/main/resources/application.properties b/spring-core-3/src/main/resources/application.properties new file mode 100644 index 0000000000..828fa9cd2a --- /dev/null +++ b/spring-core-3/src/main/resources/application.properties @@ -0,0 +1 @@ +name = Inject a value to a static field diff --git a/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java new file mode 100644 index 0000000000..e9b491813e --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung.ioccontainer; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import com.baeldung.ioccontainer.bean.CustomBeanFactoryPostProcessor; +import com.baeldung.ioccontainer.bean.CustomBeanPostProcessor; +import com.baeldung.ioccontainer.bean.Student; + +public class IOCContainerAppUnitTest { + + @BeforeEach + @AfterEach + public void resetInstantiationFlag() { + Student.setBeanInstantiated(false); + CustomBeanPostProcessor.setBeanPostProcessorRegistered(false); + CustomBeanFactoryPostProcessor.setBeanFactoryPostProcessorRegistered(false); + } + + @Test + public void whenBFInitialized_thenStudentNotInitialized() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + BeanFactory factory = new XmlBeanFactory(res); + + assertFalse(Student.isBeanInstantiated()); + } + + @Test + public void whenBFInitialized_thenStudentInitialized() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + BeanFactory factory = new XmlBeanFactory(res); + Student student = (Student) factory.getBean("student"); + + assertTrue(Student.isBeanInstantiated()); + } + + @Test + public void whenAppContInitialized_thenStudentInitialized() { + ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); + + assertTrue(Student.isBeanInstantiated()); + } + + @Test + public void whenBFInitialized_thenBFPProcessorAndBPProcessorNotRegAutomatically() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + ConfigurableListableBeanFactory factory = new XmlBeanFactory(res); + + assertFalse(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); + assertFalse(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); + } + + @Test + public void whenBFPostProcessorAndBPProcessorRegisteredManually_thenReturnTrue() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + ConfigurableListableBeanFactory factory = new XmlBeanFactory(res); + + CustomBeanFactoryPostProcessor beanFactoryPostProcessor = new CustomBeanFactoryPostProcessor(); + beanFactoryPostProcessor.postProcessBeanFactory(factory); + assertTrue(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); + + CustomBeanPostProcessor beanPostProcessor = new CustomBeanPostProcessor(); + factory.addBeanPostProcessor(beanPostProcessor); + Student student = (Student) factory.getBean("student"); + assertTrue(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); + } + + @Test + public void whenAppContInitialized_thenBFPostProcessorAndBPostProcessorRegisteredAutomatically() { + ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); + + assertTrue(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); + assertTrue(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/AnnotationConfigApplicationContextUnitTest.java b/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/AnnotationConfigApplicationContextUnitTest.java new file mode 100644 index 0000000000..66e01f261f --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/AnnotationConfigApplicationContextUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.spring.patterns.factory; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class AnnotationConfigApplicationContextUnitTest { + + @Test + @SuppressWarnings("resource") + public void whenGetSimpleBean_thenReturnConstructedBean() { + + ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class); + + Foo foo = context.getBean(Foo.class); + + assertNotNull(foo); + } + + @Test + @SuppressWarnings("resource") + public void whenGetPrototypeBean_thenReturnConstructedBean() { + + String expectedName = "Some name"; + ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class); + + Bar bar = context.getBean(Bar.class, expectedName); + + assertNotNull(bar); + assertThat(bar.getName(), is(expectedName)); + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/ApplicationConfig.java b/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/ApplicationConfig.java new file mode 100644 index 0000000000..626947cfd5 --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/ApplicationConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.patterns.factory; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackageClasses = ApplicationConfig.class) +public class ApplicationConfig { +} diff --git a/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/Bar.java b/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/Bar.java new file mode 100644 index 0000000000..e2f825aab3 --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/Bar.java @@ -0,0 +1,20 @@ +package com.baeldung.spring.patterns.factory; + +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class Bar { + + private String name; + + public Bar(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} \ No newline at end of file diff --git a/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/ClassPathXmlApplicationContextUnitTest.java b/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/ClassPathXmlApplicationContextUnitTest.java new file mode 100644 index 0000000000..bb9988317e --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/ClassPathXmlApplicationContextUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.spring.patterns.factory; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class ClassPathXmlApplicationContextUnitTest { + + @Test + @SuppressWarnings("resource") + public void givenXmlConfiguration_whenGetSimpleBean_thenReturnConstructedBean() { + + ApplicationContext context = new ClassPathXmlApplicationContext("patterns-context.xml"); + + Foo foo = context.getBean(Foo.class); + + assertNotNull(foo); + } + + @Test + @SuppressWarnings("resource") + public void givenXmlConfiguration_whenGetPrototypeBean_thenReturnConstructedBean() { + + String expectedName = "Some name"; + ApplicationContext context = new ClassPathXmlApplicationContext("patterns-context.xml"); + + Bar bar = context.getBean(Bar.class, expectedName); + + assertNotNull(bar); + assertThat(bar.getName(), is(expectedName)); + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/Foo.java b/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/Foo.java new file mode 100644 index 0000000000..5edba6c50d --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/spring/patterns/factory/Foo.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.patterns.factory; + +import org.springframework.stereotype.Component; + +@Component +public class Foo { +} diff --git a/spring-core-3/src/test/resources/ioc-container-difference-example.xml b/spring-core-3/src/test/resources/ioc-container-difference-example.xml new file mode 100644 index 0000000000..e53dc11f89 --- /dev/null +++ b/spring-core-3/src/test/resources/ioc-container-difference-example.xml @@ -0,0 +1,10 @@ + + + + + + + \ No newline at end of file diff --git a/spring-core-3/src/test/resources/patterns-context.xml b/spring-core-3/src/test/resources/patterns-context.xml new file mode 100644 index 0000000000..106cde79a0 --- /dev/null +++ b/spring-core-3/src/test/resources/patterns-context.xml @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git a/spring-core-4/README.md b/spring-core-4/README.md new file mode 100644 index 0000000000..f882c77179 --- /dev/null +++ b/spring-core-4/README.md @@ -0,0 +1,7 @@ +## Spring Core + +This module contains articles about core Spring functionality + +## Relevant Articles: + +- More articles: [[<-- prev]](/spring-core-3) diff --git a/spring-core-4/pom.xml b/spring-core-4/pom.xml new file mode 100644 index 0000000000..53f7ca6912 --- /dev/null +++ b/spring-core-4/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + spring-core-4 + spring-core-4 + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-test + ${spring.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven.surefire.version} + + + + + + 2.22.1 + 1.3.2 + 2.2.2.RELEASE + + + \ No newline at end of file diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java new file mode 100644 index 0000000000..4ad4420489 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java @@ -0,0 +1,27 @@ +package com.baeldung.dynamic.autowire; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class BeanFactoryDynamicAutowireService { + private static final String SERVICE_NAME_SUFFIX = "regionService"; + private final BeanFactory beanFactory; + + @Autowired + public BeanFactoryDynamicAutowireService(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + public boolean isServerActive(String isoCountryCode, int serverId) { + RegionService service = beanFactory.getBean(getRegionServiceBeanName(isoCountryCode), RegionService.class); + + return service.isServerActive(serverId); + } + + private String getRegionServiceBeanName(String isoCountryCode) { + return isoCountryCode + SERVICE_NAME_SUFFIX; + } + +} diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/CustomMapFromListDynamicAutowireService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/CustomMapFromListDynamicAutowireService.java new file mode 100644 index 0000000000..e04c345d51 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/CustomMapFromListDynamicAutowireService.java @@ -0,0 +1,26 @@ +package com.baeldung.dynamic.autowire; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +public class CustomMapFromListDynamicAutowireService { + private final Map servicesByCountryCode; + + @Autowired + public CustomMapFromListDynamicAutowireService(List regionServices) { + servicesByCountryCode = regionServices.stream() + .collect(Collectors.toMap(RegionService::getISOCountryCode, Function.identity())); + } + + public boolean isServerActive(String isoCountryCode, int serverId) { + RegionService service = servicesByCountryCode.get(isoCountryCode); + + return service.isServerActive(serverId); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/DynamicAutowireConfig.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/DynamicAutowireConfig.java new file mode 100644 index 0000000000..256bd9b495 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/DynamicAutowireConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.dynamic.autowire; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.dynamic.autowire") +public class DynamicAutowireConfig { +} diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/GBRegionService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/GBRegionService.java new file mode 100644 index 0000000000..8c6a1372d4 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/GBRegionService.java @@ -0,0 +1,16 @@ +package com.baeldung.dynamic.autowire; + +import org.springframework.stereotype.Service; + +@Service("GBregionService") +public class GBRegionService implements RegionService { + @Override + public boolean isServerActive(int serverId) { + return false; + } + + @Override + public String getISOCountryCode() { + return "GB"; + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/RegionService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/RegionService.java new file mode 100644 index 0000000000..a2caf38ab3 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/RegionService.java @@ -0,0 +1,7 @@ +package com.baeldung.dynamic.autowire; + +public interface RegionService { + boolean isServerActive(int serverId); + + String getISOCountryCode(); +} diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USRegionService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USRegionService.java new file mode 100644 index 0000000000..a2d5f47553 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USRegionService.java @@ -0,0 +1,16 @@ +package com.baeldung.dynamic.autowire; + +import org.springframework.stereotype.Service; + +@Service("USregionService") +public class USRegionService implements RegionService { + @Override + public boolean isServerActive(int serverId) { + return true; + } + + @Override + public String getISOCountryCode() { + return "US"; + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/Bar.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/Bar.java new file mode 100644 index 0000000000..22ef5b3429 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/Bar.java @@ -0,0 +1,18 @@ +package com.baeldung.factorymethod; + +public class Bar { + + private String name; + + public Bar(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/Foo.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/Foo.java new file mode 100644 index 0000000000..54bd0c9ff4 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/Foo.java @@ -0,0 +1,5 @@ +package com.baeldung.factorymethod; + +public class Foo { + +} diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java new file mode 100644 index 0000000000..f834b82aee --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java @@ -0,0 +1,8 @@ +package com.baeldung.factorymethod; + +public class InstanceBarFactory { + + public Bar createInstance(String name) { + return new Bar(name); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java new file mode 100644 index 0000000000..c3125d3339 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java @@ -0,0 +1,8 @@ +package com.baeldung.factorymethod; + +public class InstanceFooFactory { + + public Foo createInstance() { + return new Foo(); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java new file mode 100644 index 0000000000..93802819b1 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java @@ -0,0 +1,11 @@ +package com.baeldung.factorymethod; + +public class SingletonBarFactory { + + private static final Bar INSTANCE = new Bar("unnamed"); + + public static Bar createInstance(String name) { + INSTANCE.setName(name); + return INSTANCE; + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java new file mode 100644 index 0000000000..77d56cc7f6 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java @@ -0,0 +1,10 @@ +package com.baeldung.factorymethod; + +public class SingletonFooFactory { + + private static final Foo INSTANCE = new Foo(); + + public static Foo createInstance() { + return INSTANCE; + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java new file mode 100644 index 0000000000..56582ecb66 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.dynamic.autowire; + +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 static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = DynamicAutowireConfig.class) +public class DynamicAutowireIntegrationTest { + + @Autowired + private BeanFactoryDynamicAutowireService beanFactoryDynamicAutowireService; + + @Autowired + private CustomMapFromListDynamicAutowireService customMapFromListDynamicAutowireService; + + @Test + public void givenDynamicallyAutowiredBean_whenCheckingServerInGB_thenServerIsNotActive() { + assertThat(beanFactoryDynamicAutowireService.isServerActive("GB", 101), is(false)); + assertThat(customMapFromListDynamicAutowireService.isServerActive("GB", 101), is(false)); + } + + @Test + public void givenDynamicallyAutowiredBean_whenCheckingServerInUS_thenServerIsActive() { + assertThat(beanFactoryDynamicAutowireService.isServerActive("US", 101), is(true)); + assertThat(customMapFromListDynamicAutowireService.isServerActive("US", 101), is(true)); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java new file mode 100644 index 0000000000..b5728316e7 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.factorymethod; + +import static org.junit.Assert.assertEquals; +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.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/instance-bar-config.xml") +public class InstanceBarFactoryIntegrationTest { + + @Autowired + private Bar instance; + + @Test + public void givenValidInstanceFactoryConfig_whenCreateInstance_thenNameIsCorrect() { + assertNotNull(instance); + assertEquals("someName", instance.getName()); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java new file mode 100644 index 0000000000..6b1857c2f2 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.factorymethod; + +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.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/instance-foo-config.xml") +public class InstanceFooFactoryIntegrationTest { + + @Autowired + private Foo foo; + + @Test + public void givenValidInstanceFactoryConfig_whenCreateFooInstance_thenInstanceIsNotNull() { + assertNotNull(foo); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java new file mode 100644 index 0000000000..403b46156b --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.factorymethod; + +import static org.junit.Assert.assertEquals; +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.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/static-bar-config.xml") +public class SingletonBarFactoryIntegrationTest { + + @Autowired + private Bar instance; + + @Test + public void givenValidStaticFactoryConfig_whenCreateInstance_thenNameIsCorrect() { + assertNotNull(instance); + assertEquals("someName", instance.getName()); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java new file mode 100644 index 0000000000..52154b81ab --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.factorymethod; + +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.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/static-foo-config.xml") +public class SingletonFooFactoryIntegrationTest { + + @Autowired + private Foo singleton; + + @Test + public void givenValidStaticFactoryConfig_whenCreateInstance_thenInstanceIsNotNull() { + assertNotNull(singleton); + } +} diff --git a/spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml b/spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml new file mode 100644 index 0000000000..a4281aee4e --- /dev/null +++ b/spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml @@ -0,0 +1,20 @@ + + + + + + + + + + \ No newline at end of file diff --git a/spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml b/spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml new file mode 100644 index 0000000000..0f21f06f5a --- /dev/null +++ b/spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml @@ -0,0 +1,18 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml b/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml new file mode 100644 index 0000000000..2cacc293bc --- /dev/null +++ b/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml @@ -0,0 +1,17 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-core-4/src/test/resources/factorymethod/static-foo-config.xml b/spring-core-4/src/test/resources/factorymethod/static-foo-config.xml new file mode 100644 index 0000000000..ffe1480638 --- /dev/null +++ b/spring-core-4/src/test/resources/factorymethod/static-foo-config.xml @@ -0,0 +1,15 @@ + + + + + + \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/SpringContextTest.java b/spring-cucumber/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3226da4bdc --- /dev/null +++ b/spring-cucumber/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.SpringDemoApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDemoApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java b/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 7b8fa74fc9..0000000000 --- a/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.SpringDemoApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringDemoApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-data-rest-querydsl/pom.xml b/spring-data-rest-querydsl/pom.xml index 9f53f6b55f..c0ad43fe0b 100644 --- a/spring-data-rest-querydsl/pom.xml +++ b/spring-data-rest-querydsl/pom.xml @@ -72,8 +72,8 @@ org.apache.maven.plugins maven-compiler-plugin - 1.8 - 1.8 + ${maven.source} + ${maven.target} -verbose -parameters @@ -83,7 +83,7 @@ com.mysema.maven apt-maven-plugin - 1.1.3 + ${mysema.version} generate-sources @@ -99,5 +99,10 @@ + + 1.8 + 1.8 + 1.1.3 + diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml index 05f2ccbbae..bb592c08d5 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -66,7 +66,7 @@ com.mysema.maven maven-apt-plugin - 1.0 + ${maven.version} generate-sources @@ -90,6 +90,7 @@ UTF-8 com.baeldung.books.SpringDataRestApplication + 1.0
\ No newline at end of file diff --git a/spring-data-rest/src/test/java/com/baeldung/SpringContextTest.java b/spring-data-rest/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8fa0a4c239 --- /dev/null +++ b/spring-data-rest/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.books.SpringDataRestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataRestApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java b/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 7e7fccadef..0000000000 --- a/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.books.SpringDataRestApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringDataRestApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-di/src/main/java/com/baeldung/store/AppConfig.java b/spring-di/src/main/java/com/baeldung/store/AppConfig.java new file mode 100644 index 0000000000..0debecfc47 --- /dev/null +++ b/spring-di/src/main/java/com/baeldung/store/AppConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.store; + +import org.springframework.context.annotation.Bean; + +public class AppConfig { + + @Bean + public Item item1() { + return new ItemImpl1(); + } + + @Bean + public Store storeThroughConstructorInjection() { + return new Store(item1()); + } + + @Bean + public Store storeThroughSetterInjection() { + Store store = new Store(); + store.setItem(item1()); + return store; + } +} diff --git a/spring-di/src/main/java/com/baeldung/store/Item.java b/spring-di/src/main/java/com/baeldung/store/Item.java new file mode 100644 index 0000000000..8598c2e1b3 --- /dev/null +++ b/spring-di/src/main/java/com/baeldung/store/Item.java @@ -0,0 +1,5 @@ +package com.baeldung.store; + +public interface Item { + +} diff --git a/spring-di/src/main/java/com/baeldung/store/ItemImpl1.java b/spring-di/src/main/java/com/baeldung/store/ItemImpl1.java new file mode 100644 index 0000000000..516882c99f --- /dev/null +++ b/spring-di/src/main/java/com/baeldung/store/ItemImpl1.java @@ -0,0 +1,5 @@ +package com.baeldung.store; + +public class ItemImpl1 implements Item { + +} diff --git a/spring-di/src/main/java/org/baeldung/store/Store.java b/spring-di/src/main/java/com/baeldung/store/Store.java similarity index 92% rename from spring-di/src/main/java/org/baeldung/store/Store.java rename to spring-di/src/main/java/com/baeldung/store/Store.java index dcc2c3be48..cc40f74306 100644 --- a/spring-di/src/main/java/org/baeldung/store/Store.java +++ b/spring-di/src/main/java/com/baeldung/store/Store.java @@ -1,4 +1,4 @@ -package org.baeldung.store; +package com.baeldung.store; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-di/src/main/java/org/baeldung/store/AppConfig.java b/spring-di/src/main/java/org/baeldung/store/AppConfig.java deleted file mode 100644 index 80b6733dff..0000000000 --- a/spring-di/src/main/java/org/baeldung/store/AppConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.store; - -import org.springframework.context.annotation.Bean; - -public class AppConfig { - - @Bean - public Item item1() { - return new ItemImpl1(); - } - - @Bean - public Store storeThroughConstructorInjection() { - return new Store(item1()); - } - - @Bean - public Store storeThroughSetterInjection() { - Store store = new Store(); - store.setItem(item1()); - return store; - } -} diff --git a/spring-di/src/main/java/org/baeldung/store/Item.java b/spring-di/src/main/java/org/baeldung/store/Item.java deleted file mode 100644 index 1d7292fc35..0000000000 --- a/spring-di/src/main/java/org/baeldung/store/Item.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.store; - -public interface Item { - -} diff --git a/spring-di/src/main/java/org/baeldung/store/ItemImpl1.java b/spring-di/src/main/java/org/baeldung/store/ItemImpl1.java deleted file mode 100644 index 8bda9f24c9..0000000000 --- a/spring-di/src/main/java/org/baeldung/store/ItemImpl1.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.store; - -public class ItemImpl1 implements Item { - -} diff --git a/spring-di/src/main/resources/ioc-context-by-type.xml b/spring-di/src/main/resources/ioc-context-by-type.xml index 1249ce51af..cba8b17a30 100644 --- a/spring-di/src/main/resources/ioc-context-by-type.xml +++ b/spring-di/src/main/resources/ioc-context-by-type.xml @@ -6,9 +6,9 @@ - + - + \ No newline at end of file diff --git a/spring-di/src/main/resources/ioc-context.xml b/spring-di/src/main/resources/ioc-context.xml index 0e1d0ac29c..64b1bc5443 100644 --- a/spring-di/src/main/resources/ioc-context.xml +++ b/spring-di/src/main/resources/ioc-context.xml @@ -6,28 +6,28 @@ - - + + - + - + - + - - + + diff --git a/spring-di/src/test/java/org/baeldung/store/AppConfigUnitTest.java b/spring-di/src/test/java/com/baeldung/store/AppConfigUnitTest.java similarity index 94% rename from spring-di/src/test/java/org/baeldung/store/AppConfigUnitTest.java rename to spring-di/src/test/java/com/baeldung/store/AppConfigUnitTest.java index 3260114679..d433ac6bf0 100644 --- a/spring-di/src/test/java/org/baeldung/store/AppConfigUnitTest.java +++ b/spring-di/src/test/java/com/baeldung/store/AppConfigUnitTest.java @@ -1,35 +1,35 @@ -package org.baeldung.store; - -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.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = AppConfig.class) -public class AppConfigUnitTest { - - @Autowired - @Qualifier("storeThroughConstructorInjection") - private Store storeByConstructorInjection; - - @Autowired - @Qualifier("storeThroughSetterInjection") - private Store storeBySetterInjection; - - @Test - public void givenValidXmlConfig_WhenInjectStoreByConstructorInjection_ThenBeanIsNotNull() { - assertNotNull(storeByConstructorInjection); - assertNotNull(storeByConstructorInjection.getItem()); - } - - @Test - public void givenValidXmlConfig_WhenInjectStoreBySetterInjection_ThenBeanIsNotNull() { - assertNotNull(storeBySetterInjection); - assertNotNull(storeByConstructorInjection.getItem()); - } -} +package com.baeldung.store; + +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.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +public class AppConfigUnitTest { + + @Autowired + @Qualifier("storeThroughConstructorInjection") + private Store storeByConstructorInjection; + + @Autowired + @Qualifier("storeThroughSetterInjection") + private Store storeBySetterInjection; + + @Test + public void givenValidXmlConfig_WhenInjectStoreByConstructorInjection_ThenBeanIsNotNull() { + assertNotNull(storeByConstructorInjection); + assertNotNull(storeByConstructorInjection.getItem()); + } + + @Test + public void givenValidXmlConfig_WhenInjectStoreBySetterInjection_ThenBeanIsNotNull() { + assertNotNull(storeBySetterInjection); + assertNotNull(storeByConstructorInjection.getItem()); + } +} diff --git a/spring-di/src/test/java/org/baeldung/store/XmlAppConfigByTypeUnitTest.java b/spring-di/src/test/java/com/baeldung/store/XmlAppConfigByTypeUnitTest.java similarity index 97% rename from spring-di/src/test/java/org/baeldung/store/XmlAppConfigByTypeUnitTest.java rename to spring-di/src/test/java/com/baeldung/store/XmlAppConfigByTypeUnitTest.java index 036399e537..dbed822e46 100644 --- a/spring-di/src/test/java/org/baeldung/store/XmlAppConfigByTypeUnitTest.java +++ b/spring-di/src/test/java/com/baeldung/store/XmlAppConfigByTypeUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.store; +package com.baeldung.store; import static org.junit.Assert.assertNotNull; diff --git a/spring-di/src/test/java/org/baeldung/store/XmlAppConfigUnitTest.java b/spring-di/src/test/java/com/baeldung/store/XmlAppConfigUnitTest.java similarity index 98% rename from spring-di/src/test/java/org/baeldung/store/XmlAppConfigUnitTest.java rename to spring-di/src/test/java/com/baeldung/store/XmlAppConfigUnitTest.java index 2dd4d6ccd6..90c55c263c 100644 --- a/spring-di/src/test/java/org/baeldung/store/XmlAppConfigUnitTest.java +++ b/spring-di/src/test/java/com/baeldung/store/XmlAppConfigUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.store; +package com.baeldung.store; import static org.junit.Assert.assertNotNull; diff --git a/spring-dispatcher-servlet/src/test/java/com/baeldung/SpringContextTest.java b/spring-dispatcher-servlet/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ba8040f81d --- /dev/null +++ b/spring-dispatcher-servlet/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.springdispatcherservlet.configuration.AppConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java b/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index d1de77b1e6..0000000000 --- a/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -import com.baeldung.springdispatcherservlet.configuration.AppConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = AppConfig.class) -@WebAppConfiguration -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-drools/src/test/java/com/baeldung/SpringContextTest.java b/spring-drools/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..fdaf0b17d0 --- /dev/null +++ b/spring-drools/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.drools.service.TaxiFareConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TaxiFareConfiguration.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-drools/src/test/java/org/baeldung/SpringContextTest.java b/spring-drools/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 9a36a521f1..0000000000 --- a/spring-drools/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.spring.drools.service.TaxiFareConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = TaxiFareConfiguration.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-ejb/README.md b/spring-ejb/README.md index 423d55ea22..8f6522266c 100644 --- a/spring-ejb/README.md +++ b/spring-ejb/README.md @@ -8,5 +8,5 @@ This module contains articles about Spring with EJB - [Java EE Session Beans](https://www.baeldung.com/ejb-session-beans) - [A Guide to Message Driven Beans in EJB](https://www.baeldung.com/ejb-message-driven-beans) - [Integration Guide for Spring and EJB](https://www.baeldung.com/spring-ejb) -- [Singleton Session Bean in Java EE](https://www.baeldung.com/java-ee-singleton-session-bean) +- [Singleton Session Bean in Jakarta EE](https://www.baeldung.com/java-ee-singleton-session-bean) diff --git a/spring-ejb/ejb-beans/README.md b/spring-ejb/ejb-beans/README.md new file mode 100644 index 0000000000..f1af5a3a87 --- /dev/null +++ b/spring-ejb/ejb-beans/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Spring Bean vs. EJB – A Feature Comparison](https://www.baeldung.com/spring-bean-vs-ejb) diff --git a/spring-ejb/ejb-beans/pom.xml b/spring-ejb/ejb-beans/pom.xml index b8978a0cc3..c9edfc21f8 100644 --- a/spring-ejb/ejb-beans/pom.xml +++ b/spring-ejb/ejb-beans/pom.xml @@ -37,6 +37,42 @@ tomee-embedded ${tomee-embedded.version} + + org.springframework + spring-context + ${springframework.version} + + + + javax.ejb + javax.ejb-api + ${javax.ejb-api.version} + provided + + + + org.springframework + spring-jms + ${springframework.version} + + + commons-logging + commons-logging + + + + + + org.apache.activemq + activemq-broker + ${activemq.broker.version} + + + org.apache.activemq.tooling + activemq-junit + ${activemq.junit.version} + test + org.jboss.arquillian.junit arquillian-junit-container @@ -81,6 +117,12 @@ 1.7.5 3.1.2 1.0.0.CR4 + 3.2 + 5.2.3.RELEASE + 5.10.2 + 5.13.1 + 2.21.0 + 1.8.5
diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/messagedriven/RecieverMDB.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/messagedriven/RecieverMDB.java new file mode 100644 index 0000000000..f7f43244d5 --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/messagedriven/RecieverMDB.java @@ -0,0 +1,63 @@ +package com.baeldung.ejbspringcomparison.ejb.messagedriven; + +import javax.annotation.Resource; +import javax.ejb.ActivationConfigProperty; +import javax.ejb.MessageDriven; +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.DeliveryMode; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.TextMessage; + +@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destination", propertyValue = "myQueue"), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") }) +public class RecieverMDB implements MessageListener { + + @Resource + private ConnectionFactory connectionFactory; + + @Resource(name = "ackQueue") + private Queue ackQueue; + + public void onMessage(Message message) { + try { + + TextMessage textMessage = (TextMessage) message; + String producerPing = textMessage.getText(); + + if (producerPing.equals("marco")) { + acknowledge("polo"); + } + } catch (JMSException e) { + throw new IllegalStateException(e); + } + } + + private void acknowledge(String text) throws JMSException { + + Connection connection = null; + Session session = null; + + try { + connection = connectionFactory.createConnection(); + connection.start(); + + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + MessageProducer ackSender = session.createProducer(ackQueue); + ackSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + + TextMessage message = session.createTextMessage(text); + + ackSender.send(message); + } finally { + session.close(); + connection.close(); + } + } + +} diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/singleton/CounterEJB.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/singleton/CounterEJB.java new file mode 100644 index 0000000000..6873a717a9 --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/singleton/CounterEJB.java @@ -0,0 +1,23 @@ +package com.baeldung.ejbspringcomparison.ejb.singleton; + +import javax.ejb.Singleton; + +@Singleton +public class CounterEJB implements CounterEJBRemote { + + private int count = 1; + private String name; + + public int count() { + return count++; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} \ No newline at end of file diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/singleton/CounterEJBRemote.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/singleton/CounterEJBRemote.java new file mode 100644 index 0000000000..ed02cfed4c --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/singleton/CounterEJBRemote.java @@ -0,0 +1,10 @@ +package com.baeldung.ejbspringcomparison.ejb.singleton; + +import javax.ejb.Remote; + +@Remote +public interface CounterEJBRemote { + int count(); + String getName(); + void setName(String name); +} diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateful/ShoppingCartEJB.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateful/ShoppingCartEJB.java new file mode 100644 index 0000000000..e01e53add1 --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateful/ShoppingCartEJB.java @@ -0,0 +1,32 @@ +package com.baeldung.ejbspringcomparison.ejb.stateful; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Stateful; + +@Stateful +public class ShoppingCartEJB implements ShoppingCartEJBRemote { + private String name; + private List shoppingCart; + + public ShoppingCartEJB() { + shoppingCart = new ArrayList(); + } + + public void addItem(String item) { + shoppingCart.add(item); + } + + public List getItems() { + return shoppingCart; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateful/ShoppingCartEJBRemote.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateful/ShoppingCartEJBRemote.java new file mode 100644 index 0000000000..cea9cc3ad9 --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateful/ShoppingCartEJBRemote.java @@ -0,0 +1,17 @@ +package com.baeldung.ejbspringcomparison.ejb.stateful; + +import java.util.List; + +import javax.ejb.Remote; + +@Remote +public interface ShoppingCartEJBRemote { + + void addItem(String item); + + List getItems(); + + void setName(String name); + + String getName(); +} diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateless/FinderEJB.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateless/FinderEJB.java new file mode 100644 index 0000000000..7609b17675 --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateless/FinderEJB.java @@ -0,0 +1,25 @@ +package com.baeldung.ejbspringcomparison.ejb.stateless; + +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Stateless; + +@Stateless +public class FinderEJB implements FinderEJBRemote { + + private Map alphabet; + + public FinderEJB() { + alphabet = new HashMap(); + alphabet.put("A", "Apple"); + alphabet.put("B", "Ball"); + alphabet.put("C", "Cat"); + alphabet.put("D", "Dog"); + } + + public String search(String keyword) { + return alphabet.get(keyword); + } + +} diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateless/FinderEJBRemote.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateless/FinderEJBRemote.java new file mode 100644 index 0000000000..0354eff2b8 --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/ejb/stateless/FinderEJBRemote.java @@ -0,0 +1,9 @@ +package com.baeldung.ejbspringcomparison.ejb.stateless; + +import javax.ejb.Remote; + +@Remote +public interface FinderEJBRemote { + + String search(String keyword); +} diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/config/ApplicationConfig.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/config/ApplicationConfig.java new file mode 100644 index 0000000000..8d6114d1c5 --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/config/ApplicationConfig.java @@ -0,0 +1,36 @@ +package com.baeldung.ejbspringcomparison.spring.config; + +import javax.jms.ConnectionFactory; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.jms.annotation.EnableJms; +import org.springframework.jms.config.DefaultJmsListenerContainerFactory; +import org.springframework.jms.core.JmsTemplate; + +@Configuration +@ComponentScan(basePackages = "com.baeldung.ejbspringcomparison.spring") +@EnableJms +public class ApplicationConfig { + + @Bean + public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() { + DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); + factory.setConnectionFactory(connectionFactory()); + return factory; + } + + @Bean + public ConnectionFactory connectionFactory() { + return new ActiveMQConnectionFactory("tcp://localhost:61616"); + } + + @Bean + public JmsTemplate jmsTemplate() { + JmsTemplate template = new JmsTemplate(connectionFactory()); + template.setConnectionFactory(connectionFactory()); + return template; + } +} diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/messagedriven/Producer.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/messagedriven/Producer.java new file mode 100644 index 0000000000..683ae7f51b --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/messagedriven/Producer.java @@ -0,0 +1,19 @@ +package com.baeldung.ejbspringcomparison.spring.messagedriven; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jms.core.JmsTemplate; +import org.springframework.stereotype.Component; + +@Component +public class Producer { + @Autowired + private JmsTemplate jmsTemplate; + + public void sendMessageToDefaultDestination(final String message) { + jmsTemplate.convertAndSend("myQueue", message); + } + + public String receiveAck() { + return (String) jmsTemplate.receiveAndConvert("ackQueue"); + } +} \ No newline at end of file diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/messagedriven/Receiver.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/messagedriven/Receiver.java new file mode 100644 index 0000000000..9a483e23c9 --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/messagedriven/Receiver.java @@ -0,0 +1,22 @@ +package com.baeldung.ejbspringcomparison.spring.messagedriven; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jms.annotation.JmsListener; +import org.springframework.jms.core.JmsTemplate; +import org.springframework.stereotype.Component; + +@Component +public class Receiver { + @Autowired + private JmsTemplate jmsTemplate; + + @JmsListener(destination = "myQueue") + public void receiveMessage(String msg) { + sendAck(); + } + + private void sendAck() { + jmsTemplate.convertAndSend("ackQueue", "polo"); + } + +} \ No newline at end of file diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/singleton/CounterBean.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/singleton/CounterBean.java new file mode 100644 index 0000000000..6b2b57582d --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/singleton/CounterBean.java @@ -0,0 +1,22 @@ +package com.baeldung.ejbspringcomparison.spring.singleton; + +import org.springframework.stereotype.Component; + +@Component +public class CounterBean { + private int count = 1; + private String name; + + public int count() { + return count++; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/stateful/ShoppingCartBean.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/stateful/ShoppingCartBean.java new file mode 100644 index 0000000000..e6e026f52a --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/ejbspringcomparison/spring/stateful/ShoppingCartBean.java @@ -0,0 +1,36 @@ +package com.baeldung.ejbspringcomparison.spring.stateful; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ShoppingCartBean { + + private String name; + private List shoppingCart; + + public ShoppingCartBean() { + shoppingCart = new ArrayList(); + } + + public void addItem(String item) { + shoppingCart.add(item); + } + + public List getItems() { + return shoppingCart; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/spring-ejb/ejb-beans/src/test/java/com/baeldung/ejbspringcomparison/ejb/EJBUnitTest.java b/spring-ejb/ejb-beans/src/test/java/com/baeldung/ejbspringcomparison/ejb/EJBUnitTest.java new file mode 100644 index 0000000000..069028253e --- /dev/null +++ b/spring-ejb/ejb-beans/src/test/java/com/baeldung/ejbspringcomparison/ejb/EJBUnitTest.java @@ -0,0 +1,140 @@ +package com.baeldung.ejbspringcomparison.ejb; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import javax.annotation.Resource; +import javax.ejb.EJB; +import javax.ejb.embeddable.EJBContainer; +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.JMSException; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.TextMessage; +import javax.naming.Context; +import javax.naming.NamingException; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.ejbspringcomparison.ejb.singleton.CounterEJBRemote; +import com.baeldung.ejbspringcomparison.ejb.stateful.ShoppingCartEJBRemote; +import com.baeldung.ejbspringcomparison.ejb.stateless.FinderEJBRemote; + +public class EJBUnitTest { + + private static EJBContainer ejbContainer = null; + + private static Context context = null; + + @Resource + private ConnectionFactory connectionFactory; + + @EJB + private FinderEJBRemote alphabetFinder; + + @Resource(name = "myQueue") + private Queue myQueue; + + @Resource(name = "ackQueue") + private Queue ackQueue; + + @BeforeClass + public static void start() throws NamingException { + ejbContainer = EJBContainer.createEJBContainer(); + } + + @Before + public void initializeContext() throws NamingException { + context = ejbContainer.getContext(); + context.bind("inject", this); + } + + @Test + public void givenSingletonBean_whenCounterInvoked_thenCountIsIncremented() throws NamingException { + + int count = 0; + CounterEJBRemote firstCounter = (CounterEJBRemote) context.lookup("java:global/ejb-beans/CounterEJB"); + firstCounter.setName("first"); + + for (int i = 0; i < 10; i++) { + count = firstCounter.count(); + } + + assertEquals(10, count); + assertEquals("first", firstCounter.getName()); + + CounterEJBRemote secondCounter = (CounterEJBRemote) context.lookup("java:global/ejb-beans/CounterEJB"); + + int count2 = 0; + for (int i = 0; i < 10; i++) { + count2 = secondCounter.count(); + } + + assertEquals(20, count2); + assertEquals("first", secondCounter.getName()); + + } + + @Test + public void givenStatefulBean_whenBathingCartWithThreeItemsAdded_thenItemsSizeIsThree() throws NamingException { + ShoppingCartEJBRemote bathingCart = (ShoppingCartEJBRemote) context.lookup("java:global/ejb-beans/ShoppingCartEJB"); + + bathingCart.setName("bathingCart"); + + bathingCart.addItem("soap"); + bathingCart.addItem("shampoo"); + bathingCart.addItem("oil"); + + assertEquals(3, bathingCart.getItems() + .size()); + assertEquals("bathingCart", bathingCart.getName()); + + ShoppingCartEJBRemote fruitCart = (ShoppingCartEJBRemote) context.lookup("java:global/ejb-beans/ShoppingCartEJB"); + + fruitCart.addItem("apples"); + fruitCart.addItem("oranges"); + + assertEquals(2, fruitCart.getItems() + .size()); + assertNull(fruitCart.getName()); + } + + @Test + public void givenStatelessBean_whenSearchForA_thenApple() throws NamingException { + + assertEquals("Apple", alphabetFinder.search("A")); + } + + @Test + public void givenMDB_whenMessageSent_thenAcknowledgementReceived() throws InterruptedException, JMSException, NamingException { + + Connection connection = connectionFactory.createConnection(); + connection.start(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(myQueue); + producer.send(session.createTextMessage("marco")); + MessageConsumer response = session.createConsumer(ackQueue); + + assertEquals("polo", ((TextMessage) response.receive(1000)).getText()); + + } + + @After + public void reset() throws NamingException { + context.unbind("inject"); + } + + @AfterClass + public static void closeContext() throws NamingException { + context.close(); + ejbContainer.close(); + } + +} diff --git a/spring-ejb/ejb-beans/src/test/java/com/baeldung/ejbspringcomparison/spring/SpringUnitTest.java b/spring-ejb/ejb-beans/src/test/java/com/baeldung/ejbspringcomparison/spring/SpringUnitTest.java new file mode 100644 index 0000000000..e0b397befe --- /dev/null +++ b/spring-ejb/ejb-beans/src/test/java/com/baeldung/ejbspringcomparison/spring/SpringUnitTest.java @@ -0,0 +1,108 @@ +package com.baeldung.ejbspringcomparison.spring; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import javax.naming.NamingException; + +import org.apache.activemq.junit.EmbeddedActiveMQBroker; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import com.baeldung.ejbspringcomparison.spring.config.ApplicationConfig; +import com.baeldung.ejbspringcomparison.spring.messagedriven.Producer; +import com.baeldung.ejbspringcomparison.spring.singleton.CounterBean; +import com.baeldung.ejbspringcomparison.spring.stateful.ShoppingCartBean; + +public class SpringUnitTest { + + private static AnnotationConfigApplicationContext context = null; + + @ClassRule + public static EmbeddedActiveMQBroker broker = new EmbeddedActiveMQBroker() { + @Override + protected void configure() { + this.getBrokerService() + .setUseJmx(true); + try { + this.getBrokerService() + .addConnector("tcp://localhost:61616"); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } + } + }; + + @BeforeClass + public static void init() { + context = new AnnotationConfigApplicationContext(ApplicationConfig.class); + } + + @Test + public void whenCounterInvoked_thenCountIsIncremented() throws NamingException { + + CounterBean firstCounter = context.getBean(CounterBean.class); + firstCounter.setName("first"); + int count = 0; + for (int i = 0; i < 10; i++) { + count = firstCounter.count(); + } + + assertEquals(10, count); + assertEquals("first", firstCounter.getName()); + + CounterBean secondCounter = context.getBean(CounterBean.class); + + int count2 = 0; + for (int i = 0; i < 10; i++) { + count2 = secondCounter.count(); + } + + assertEquals(20, count2); + assertEquals("first", secondCounter.getName()); + + } + + @Test + public void whenBathingCartWithThreeItemsAdded_thenItemsSizeIsThree() throws NamingException { + ShoppingCartBean bathingCart = context.getBean(ShoppingCartBean.class); + + bathingCart.setName("bathingCart"); + + bathingCart.addItem("soap"); + bathingCart.addItem("shampoo"); + bathingCart.addItem("oil"); + + assertEquals(3, bathingCart.getItems() + .size()); + + assertEquals("bathingCart", bathingCart.getName()); + + ShoppingCartBean fruitCart = context.getBean(ShoppingCartBean.class); + + fruitCart.addItem("apples"); + fruitCart.addItem("oranges"); + + assertEquals(2, fruitCart.getItems() + .size()); + assertNull(fruitCart.getName()); + } + + @Test + public void givenJMSBean_whenMessageSent_thenAcknowledgementReceived() throws NamingException { + Producer producer = context.getBean(Producer.class); + producer.sendMessageToDefaultDestination("marco"); + + assertEquals("polo", producer.receiveAck()); + } + + @AfterClass + public static void closeContext() throws NamingException { + context.close(); + } + +} diff --git a/spring-ejb/wildfly/wildfly-ear/pom.xml b/spring-ejb/wildfly/wildfly-ear/pom.xml index 9393820b12..07f53358bf 100644 --- a/spring-ejb/wildfly/wildfly-ear/pom.xml +++ b/spring-ejb/wildfly/wildfly-ear/pom.xml @@ -45,7 +45,7 @@ ${maven-ear-plugin.version} lib/ - 7 + ${defaultLibBundleDir.version} com.baeldung.wildfly @@ -66,6 +66,7 @@ 2.10.1 1.2.0.Final + 7
\ No newline at end of file diff --git a/spring-exceptions/README.md b/spring-exceptions/README.md index f8c7553f05..2136402d49 100644 --- a/spring-exceptions/README.md +++ b/spring-exceptions/README.md @@ -1,4 +1,4 @@ -## Spring `Exception`s +## Spring Exceptions This module contains articles about Spring `Exception`s diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause1/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause1/BeanA.java new file mode 100644 index 0000000000..735b6936fe --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause1/BeanA.java @@ -0,0 +1,12 @@ +package com.baeldung.ex.beancreationexception.cause1; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class BeanA { + + @Autowired + private BeanB dependency; + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause1/BeanB.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause1/BeanB.java new file mode 100644 index 0000000000..666389bb01 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause1/BeanB.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.beancreationexception.cause1; + +public class BeanB { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/BeanA.java new file mode 100644 index 0000000000..ba139118b7 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/BeanA.java @@ -0,0 +1,12 @@ +package com.baeldung.ex.beancreationexception.cause2; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class BeanA { + + @Autowired + private IBeanB dependency; + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/BeanB1.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/BeanB1.java new file mode 100644 index 0000000000..b36dd1152f --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/BeanB1.java @@ -0,0 +1,8 @@ +package com.baeldung.ex.beancreationexception.cause2; + +import org.springframework.stereotype.Component; + +@Component +public class BeanB1 implements IBeanB { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/BeanB2.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/BeanB2.java new file mode 100644 index 0000000000..4dc5a9a7f6 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/BeanB2.java @@ -0,0 +1,8 @@ +package com.baeldung.ex.beancreationexception.cause2; + +import org.springframework.stereotype.Component; + +@Component +public class BeanB2 implements IBeanB { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/IBeanB.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/IBeanB.java new file mode 100644 index 0000000000..f469af842c --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause2/IBeanB.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.beancreationexception.cause2; + +public interface IBeanB { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause3/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause3/BeanA.java new file mode 100644 index 0000000000..e169a267b6 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause3/BeanA.java @@ -0,0 +1,12 @@ +package com.baeldung.ex.beancreationexception.cause3; + +import org.springframework.stereotype.Component; + +@Component +public class BeanA { + + public BeanA() { + super(); + throw new NullPointerException(); + } +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause4/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause4/BeanA.java new file mode 100644 index 0000000000..d1e7b157ee --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause4/BeanA.java @@ -0,0 +1,8 @@ +package com.baeldung.ex.beancreationexception.cause4; + +import org.springframework.stereotype.Component; + +@Component +public abstract class BeanA implements IBeanA { + // +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause4/IBeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause4/IBeanA.java new file mode 100644 index 0000000000..495dec9180 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause4/IBeanA.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.beancreationexception.cause4; + +public interface IBeanA { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause5/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause5/BeanA.java new file mode 100644 index 0000000000..85dc2a4c60 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause5/BeanA.java @@ -0,0 +1,13 @@ +package com.baeldung.ex.beancreationexception.cause5; + +import org.springframework.stereotype.Component; + +@Component +public class BeanA implements IBeanA { + + public BeanA(final String name) { + super(); + System.out.println(name); + } + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause5/IBeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause5/IBeanA.java new file mode 100644 index 0000000000..8429f7d5d7 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause5/IBeanA.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.beancreationexception.cause5; + +public interface IBeanA { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause6/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause6/BeanA.java new file mode 100644 index 0000000000..82dcb6faf2 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause6/BeanA.java @@ -0,0 +1,8 @@ +package com.baeldung.ex.beancreationexception.cause6; + +import org.springframework.stereotype.Component; + +@Component +public class BeanA { + private IBeanB dependency; +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause6/BeanB.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause6/BeanB.java new file mode 100644 index 0000000000..f37cc6f50d --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause6/BeanB.java @@ -0,0 +1,8 @@ +package com.baeldung.ex.beancreationexception.cause6; + +import org.springframework.stereotype.Component; + +@Component +public class BeanB implements IBeanB { + // +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause6/IBeanB.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause6/IBeanB.java new file mode 100644 index 0000000000..6515c7b467 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause6/IBeanB.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.beancreationexception.cause6; + +public interface IBeanB { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/BeanA.java new file mode 100644 index 0000000000..e301a1f13c --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/BeanA.java @@ -0,0 +1,16 @@ +package com.baeldung.ex.beancreationexception.cause8; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class BeanA implements IBeanA { + private IBeanB beanB; + + @Autowired + public BeanA(final IBeanB beanB) { + super(); + this.beanB = beanB; + } + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/BeanB.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/BeanB.java new file mode 100644 index 0000000000..3c3bd9f106 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/BeanB.java @@ -0,0 +1,15 @@ +package com.baeldung.ex.beancreationexception.cause8; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class BeanB implements IBeanB { + final IBeanA beanA; + + @Autowired + public BeanB(final IBeanA beanA) { + super(); + this.beanA = beanA; + } +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/IBeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/IBeanA.java new file mode 100644 index 0000000000..42b4c7390c --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/IBeanA.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.beancreationexception.cause8; + +public interface IBeanA { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/IBeanB.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/IBeanB.java new file mode 100644 index 0000000000..6ecbddf617 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause8/IBeanB.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.beancreationexception.cause8; + +public interface IBeanB { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/BeanA.java new file mode 100644 index 0000000000..814c4f84ff --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/BeanA.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.beancreationexception.cause9; + +public abstract class BeanA implements IBeanA { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/BeanB.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/BeanB.java new file mode 100644 index 0000000000..327bbfd10e --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/BeanB.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.beancreationexception.cause9; + +public class BeanB { + // +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/IBeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/IBeanA.java new file mode 100644 index 0000000000..a8abfd5ae0 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/IBeanA.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.beancreationexception.cause9; + +public interface IBeanA { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause1ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause1ContextWithJavaConfig.java new file mode 100644 index 0000000000..fcc501f7e3 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause1ContextWithJavaConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.ex.beancreationexception.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.ex.beancreationexception.cause1") +public class Cause1ContextWithJavaConfig { + + public Cause1ContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause2ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause2ContextWithJavaConfig.java new file mode 100644 index 0000000000..cd8b36f2db --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause2ContextWithJavaConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.ex.beancreationexception.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.ex.beancreationexception.cause2") +public class Cause2ContextWithJavaConfig { + + public Cause2ContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause3ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause3ContextWithJavaConfig.java new file mode 100644 index 0000000000..205a9b6553 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause3ContextWithJavaConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.ex.beancreationexception.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.ex.beancreationexception.cause3") +public class Cause3ContextWithJavaConfig { + + public Cause3ContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause4ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause4ContextWithJavaConfig.java similarity index 76% rename from spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause4ContextWithJavaConfig.java rename to spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause4ContextWithJavaConfig.java index b661ba4650..f2fb2b9a6d 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause4ContextWithJavaConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause4ContextWithJavaConfig.java @@ -1,11 +1,11 @@ -package org.baeldung.ex.beancreationexception.spring; +package com.baeldung.ex.beancreationexception.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration -@ComponentScan("org.baeldung.ex.beancreationexception.cause4") +@ComponentScan("com.baeldung.ex.beancreationexception.cause4") @ImportResource("classpath:beancreationexception_cause4.xml") public class Cause4ContextWithJavaConfig { diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause5ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause5ContextWithJavaConfig.java new file mode 100644 index 0000000000..3d45bd6896 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause5ContextWithJavaConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.ex.beancreationexception.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.ex.beancreationexception.cause5") +public class Cause5ContextWithJavaConfig { + + public Cause5ContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause6ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause6ContextWithJavaConfig.java similarity index 76% rename from spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause6ContextWithJavaConfig.java rename to spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause6ContextWithJavaConfig.java index c76e34deec..ab4c590804 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause6ContextWithJavaConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause6ContextWithJavaConfig.java @@ -1,11 +1,11 @@ -package org.baeldung.ex.beancreationexception.spring; +package com.baeldung.ex.beancreationexception.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration -@ComponentScan("org.baeldung.ex.beancreationexception.cause6") +@ComponentScan("com.baeldung.ex.beancreationexception.cause6") @ImportResource("classpath:beancreationexception_cause6.xml") public class Cause6ContextWithJavaConfig { diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause7ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause7ContextWithJavaConfig.java similarity index 76% rename from spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause7ContextWithJavaConfig.java rename to spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause7ContextWithJavaConfig.java index 6b56519c1a..63f9826d25 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause7ContextWithJavaConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause7ContextWithJavaConfig.java @@ -1,11 +1,11 @@ -package org.baeldung.ex.beancreationexception.spring; +package com.baeldung.ex.beancreationexception.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration -@ComponentScan("org.baeldung.ex.beancreationexception.cause7") +@ComponentScan("com.baeldung.ex.beancreationexception.cause7") @ImportResource("classpath:beancreationexception_cause7.xml") public class Cause7ContextWithJavaConfig { diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause8ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause8ContextWithJavaConfig.java new file mode 100644 index 0000000000..c6a591df2b --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause8ContextWithJavaConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.ex.beancreationexception.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.ex.beancreationexception.cause8") +public class Cause8ContextWithJavaConfig { + + public Cause8ContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause9ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause9ContextWithJavaConfig.java similarity index 80% rename from spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause9ContextWithJavaConfig.java rename to spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause9ContextWithJavaConfig.java index d64ec9ab3d..b9e3f4befd 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause9ContextWithJavaConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/spring/Cause9ContextWithJavaConfig.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beancreationexception.spring; +package com.baeldung.ex.beancreationexception.spring; -import org.baeldung.ex.beancreationexception.cause9.BeanB; +import com.baeldung.ex.beancreationexception.cause9.BeanB; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -9,7 +9,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration -@ComponentScan("org.baeldung.ex.beancreationexception.cause9") +@ComponentScan("com.baeldung.ex.beancreationexception.cause9") @ImportResource("classpath:beancreationexception_cause9.xml") public class Cause9ContextWithJavaConfig { @Autowired diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/cause2/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/cause2/BeanA.java new file mode 100644 index 0000000000..7de8a98f3b --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/cause2/BeanA.java @@ -0,0 +1,12 @@ +package com.baeldung.ex.beandefinitionstoreexception.cause2; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class BeanA { + + @Value("${some.property2}") + private String someProperty2; + +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/spring/Cause1ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/spring/Cause1ContextWithJavaConfig.java new file mode 100644 index 0000000000..6684686b9a --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/spring/Cause1ContextWithJavaConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.ex.beandefinitionstoreexception.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +@Configuration +@ComponentScan("com.baeldung.ex.beandefinitionstoreexception.cause1") +@ImportResource("beans.xml") +public class Cause1ContextWithJavaConfig { + + public Cause1ContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/spring/Cause2ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/spring/Cause2ContextWithJavaConfig.java new file mode 100644 index 0000000000..35f69d3321 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/spring/Cause2ContextWithJavaConfig.java @@ -0,0 +1,27 @@ +package com.baeldung.ex.beandefinitionstoreexception.spring; + +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.support.PropertySourcesPlaceholderConfigurer; + +@Configuration +@ComponentScan("com.baeldung.ex.beandefinitionstoreexception.cause2") +public class Cause2ContextWithJavaConfig { + + @Value("${some.property}") + private String someProperty; + + public Cause2ContextWithJavaConfig() { + super(); + } + + // beans + + @Bean + public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/spring/Cause3ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/spring/Cause3ContextWithJavaConfig.java new file mode 100644 index 0000000000..15a113ba79 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beandefinitionstoreexception/spring/Cause3ContextWithJavaConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.ex.beandefinitionstoreexception.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.ex.beandefinitionstoreexception.cause3") +public class Cause3ContextWithJavaConfig { + + public Cause3ContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/dataintegrityviolationexception/spring/Cause1DataContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/dataintegrityviolationexception/spring/Cause1DataContextWithJavaConfig.java similarity index 78% rename from spring-exceptions/src/main/java/org/baeldung/ex/dataintegrityviolationexception/spring/Cause1DataContextWithJavaConfig.java rename to spring-exceptions/src/main/java/com/baeldung/ex/dataintegrityviolationexception/spring/Cause1DataContextWithJavaConfig.java index c4d98176c5..4034b45b24 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/dataintegrityviolationexception/spring/Cause1DataContextWithJavaConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/dataintegrityviolationexception/spring/Cause1DataContextWithJavaConfig.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.dataintegrityviolationexception.spring; +package com.baeldung.ex.dataintegrityviolationexception.spring; -import org.baeldung.spring.config.PersistenceConfig; +import com.baeldung.spring.config.PersistenceConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -8,7 +8,7 @@ import org.springframework.context.annotation.Import; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; @Configuration -@ComponentScan("org.baeldung.ex.dataIntegrityviolationexception.cause1") +@ComponentScan("com.baeldung.ex.dataIntegrityviolationexception.cause1") @Import(PersistenceConfig.class) public class Cause1DataContextWithJavaConfig { diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/dataintegrityviolationexception/spring/Cause2DataContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/dataintegrityviolationexception/spring/Cause2DataContextWithJavaConfig.java new file mode 100644 index 0000000000..c4c0c4570d --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/dataintegrityviolationexception/spring/Cause2DataContextWithJavaConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.ex.dataintegrityviolationexception.spring; + +import com.baeldung.spring.config.PersistenceConfig; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +@Configuration +@ComponentScan("com.baeldung.ex.dataIntegrityviolationexception.cause2") +@Import(PersistenceConfig.class) +public class Cause2DataContextWithJavaConfig { + + public Cause2DataContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/dataintegrityviolationexception/spring/Cause3DataContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/dataintegrityviolationexception/spring/Cause3DataContextWithJavaConfig.java new file mode 100644 index 0000000000..b4426c9224 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/dataintegrityviolationexception/spring/Cause3DataContextWithJavaConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.ex.dataintegrityviolationexception.spring; + +import com.baeldung.spring.config.PersistenceConfig; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +@Configuration +@ComponentScan("com.baeldung.ex.dataIntegrityviolationexception.cause3") +@Import(PersistenceConfig.class) +public class Cause3DataContextWithJavaConfig { + + public Cause3DataContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause1/persistence/model/Foo.java b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause1/persistence/model/Foo.java new file mode 100644 index 0000000000..0eda0e7236 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause1/persistence/model/Foo.java @@ -0,0 +1,29 @@ +package com.baeldung.ex.mappingexception.cause1.persistence.model; + +import java.io.Serializable; + +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + public Foo() { + super(); + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause2/persistence/model/Foo.java b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause2/persistence/model/Foo.java new file mode 100644 index 0000000000..602a8340df --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause2/persistence/model/Foo.java @@ -0,0 +1,31 @@ +package com.baeldung.ex.mappingexception.cause2.persistence.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + public Foo() { + super(); + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause3/persistence/model/Foo.java b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause3/persistence/model/Foo.java new file mode 100644 index 0000000000..58e80d3b51 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause3/persistence/model/Foo.java @@ -0,0 +1,31 @@ +package com.baeldung.ex.mappingexception.cause3.persistence.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + public Foo() { + super(); + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause4/persistence/model/Foo.java b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause4/persistence/model/Foo.java new file mode 100644 index 0000000000..82674514fc --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/cause4/persistence/model/Foo.java @@ -0,0 +1,31 @@ +package com.baeldung.ex.mappingexception.cause4.persistence.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + public Foo() { + super(); + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + +} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/spring/Cause1PersistenceConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause1PersistenceConfig.java similarity index 94% rename from spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/spring/Cause1PersistenceConfig.java rename to spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause1PersistenceConfig.java index 11dff24e48..d2929e3d91 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/spring/Cause1PersistenceConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause1PersistenceConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.ex.mappingexception.spring; +package com.baeldung.ex.mappingexception.spring; import java.util.Properties; @@ -21,7 +21,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-mysql.properties" }) -@ComponentScan({ "org.baeldung.ex.mappingexception.cause1.persistence" }) +@ComponentScan({ "com.baeldung.ex.mappingexception.cause1.persistence" }) public class Cause1PersistenceConfig { @Autowired @@ -35,7 +35,7 @@ public class Cause1PersistenceConfig { public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "org.baeldung.ex.mappingexception.cause1.persistence.model" }); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.ex.mappingexception.cause1.persistence.model" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/spring/Cause2PersistenceConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause2PersistenceConfig.java similarity index 94% rename from spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/spring/Cause2PersistenceConfig.java rename to spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause2PersistenceConfig.java index d1d6408934..399238073c 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/spring/Cause2PersistenceConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause2PersistenceConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.ex.mappingexception.spring; +package com.baeldung.ex.mappingexception.spring; import java.util.Properties; @@ -21,7 +21,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-mysql.properties" }) -@ComponentScan({ "org.baeldung.ex.mappingexception.cause2.persistence" }) +@ComponentScan({ "com.baeldung.ex.mappingexception.cause2.persistence" }) public class Cause2PersistenceConfig { @Autowired @@ -37,7 +37,7 @@ public class Cause2PersistenceConfig { sessionFactory.setDataSource(restDataSource()); sessionFactory.setHibernateProperties(hibernateProperties()); - // sessionFactory.setPackagesToScan(new String[] { "org.baeldung.ex.mappingexception.cause2.persistence.model" }); + // sessionFactory.setPackagesToScan(new String[] { "com.baeldung.ex.mappingexception.cause2.persistence.model" }); // sessionFactory.setAnnotatedClasses(new Class[] { Foo.class }); return sessionFactory; diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/spring/Cause3PersistenceConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause3PersistenceConfig.java similarity index 92% rename from spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/spring/Cause3PersistenceConfig.java rename to spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause3PersistenceConfig.java index d4245e8e45..f5191d52f2 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/spring/Cause3PersistenceConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause3PersistenceConfig.java @@ -1,11 +1,11 @@ -package org.baeldung.ex.mappingexception.spring; +package com.baeldung.ex.mappingexception.spring; import java.util.Properties; import javax.sql.DataSource; import org.apache.tomcat.dbcp.dbcp.BasicDataSource; -import org.baeldung.ex.mappingexception.cause3.persistence.model.Foo; +import com.baeldung.ex.mappingexception.cause3.persistence.model.Foo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -22,7 +22,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-mysql.properties" }) -@ComponentScan({ "org.baeldung.ex.mappingexception.cause2.persistence" }) +@ComponentScan({ "com.baeldung.ex.mappingexception.cause2.persistence" }) public class Cause3PersistenceConfig { @Autowired @@ -38,7 +38,7 @@ public class Cause3PersistenceConfig { sessionFactory.setDataSource(restDataSource()); sessionFactory.setHibernateProperties(hibernateProperties()); - // sessionFactory.setPackagesToScan(new String[] { "org.baeldung.ex.mappingexception.cause2.persistence.model" }); + // sessionFactory.setPackagesToScan(new String[] { "com.baeldung.ex.mappingexception.cause2.persistence.model" }); sessionFactory.setAnnotatedClasses(new Class[] { Foo.class }); return sessionFactory; diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java similarity index 94% rename from spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java rename to spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java index 3337e4796d..118cb5da90 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.ex.nontransientexception.cause; +package com.baeldung.ex.nontransientexception.cause; import java.util.Properties; @@ -21,7 +21,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-derby.properties" }) -@ComponentScan({ "org.baeldung.persistence" }) +@ComponentScan({ "com.baeldung.persistence" }) public class Cause1NonTransientConfig { @Autowired @@ -35,7 +35,7 @@ public class Cause1NonTransientConfig { public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java similarity index 94% rename from spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java rename to spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java index 3543526f37..e79266e9ee 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.ex.nontransientexception.cause; +package com.baeldung.ex.nontransientexception.cause; import java.util.Properties; @@ -21,7 +21,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-derby.properties" }) -@ComponentScan({ "org.baeldung.persistence" }) +@ComponentScan({ "com.baeldung.persistence" }) public class Cause4NonTransientConfig { @Autowired @@ -35,7 +35,7 @@ public class Cause4NonTransientConfig { public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java similarity index 94% rename from spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java rename to spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java index 6d5d998c5b..784b36afbf 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.ex.nontransientexception.cause; +package com.baeldung.ex.nontransientexception.cause; import java.util.Properties; @@ -21,7 +21,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-mysql-incorrect.properties" }) -@ComponentScan({ "org.baeldung.persistence" }) +@ComponentScan({ "com.baeldung.persistence" }) public class Cause5NonTransientConfig { @Autowired @@ -35,7 +35,7 @@ public class Cause5NonTransientConfig { public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanA.java new file mode 100644 index 0000000000..3832d6e61a --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanA.java @@ -0,0 +1,12 @@ +package com.baeldung.ex.nosuchbeandefinitionexception.cause1; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class BeanA { + + @Autowired + private BeanB dependency; + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanB.java b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanB.java new file mode 100644 index 0000000000..49915c37d7 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanB.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.nosuchbeandefinitionexception.cause1; + +public class BeanB { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanA.java new file mode 100644 index 0000000000..19409820ea --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanA.java @@ -0,0 +1,12 @@ +package com.baeldung.ex.nosuchbeandefinitionexception.cause2; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class BeanA { + + @Autowired + private IBeanB dependency; + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB1.java b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB1.java new file mode 100644 index 0000000000..6b5fbb7c3e --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB1.java @@ -0,0 +1,8 @@ +package com.baeldung.ex.nosuchbeandefinitionexception.cause2; + +import org.springframework.stereotype.Component; + +@Component +public class BeanB1 implements IBeanB { + // +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB2.java b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB2.java new file mode 100644 index 0000000000..0f0bcb8f7d --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB2.java @@ -0,0 +1,8 @@ +package com.baeldung.ex.nosuchbeandefinitionexception.cause2; + +import org.springframework.stereotype.Component; + +@Component +public class BeanB2 implements IBeanB { + // +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/IBeanB.java b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/IBeanB.java new file mode 100644 index 0000000000..b8acb7faa6 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause2/IBeanB.java @@ -0,0 +1,5 @@ +package com.baeldung.ex.nosuchbeandefinitionexception.cause2; + +public interface IBeanB { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause3/BeanA.java b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause3/BeanA.java new file mode 100644 index 0000000000..c094362629 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/cause3/BeanA.java @@ -0,0 +1,19 @@ +package com.baeldung.ex.nosuchbeandefinitionexception.cause3; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; + +@Component +public class BeanA implements InitializingBean { + + @Autowired + private ApplicationContext context; + + @Override + public void afterPropertiesSet() { + context.getBean("someBeanName"); + } + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/spring/Cause1ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/spring/Cause1ContextWithJavaConfig.java new file mode 100644 index 0000000000..026ccc532b --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/spring/Cause1ContextWithJavaConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.ex.nosuchbeandefinitionexception.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.ex.nosuchbeandefinitionexception.cause1") +public class Cause1ContextWithJavaConfig { + + public Cause1ContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/spring/Cause2ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/spring/Cause2ContextWithJavaConfig.java new file mode 100644 index 0000000000..30da7f2119 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/spring/Cause2ContextWithJavaConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.ex.nosuchbeandefinitionexception.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.ex.nosuchbeandefinitionexception.cause2") +public class Cause2ContextWithJavaConfig { + + public Cause2ContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/spring/Cause3ContextWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/spring/Cause3ContextWithJavaConfig.java new file mode 100644 index 0000000000..e36c2e4eab --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nosuchbeandefinitionexception/spring/Cause3ContextWithJavaConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.ex.nosuchbeandefinitionexception.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.ex.nosuchbeandefinitionexception.cause3") +public class Cause3ContextWithJavaConfig { + + public Cause3ContextWithJavaConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/Setup.java b/spring-exceptions/src/main/java/com/baeldung/persistence/Setup.java new file mode 100644 index 0000000000..251ea4654c --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/Setup.java @@ -0,0 +1,26 @@ +package com.baeldung.persistence; + +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.stereotype.Component; + +@Component +public class Setup implements ApplicationListener { + + private boolean setupDone; + + public Setup() { + super(); + } + + // + + @Override + public final void onApplicationEvent(final ContextRefreshedEvent event) { + if (!setupDone) { + System.out.println(); + setupDone = true; + } + } + +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/common/AbstractHibernateDao.java b/spring-exceptions/src/main/java/com/baeldung/persistence/common/AbstractHibernateDao.java new file mode 100644 index 0000000000..90e4249c68 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/common/AbstractHibernateDao.java @@ -0,0 +1,65 @@ +package com.baeldung.persistence.common; + +import java.io.Serializable; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.base.Preconditions; + +@SuppressWarnings("unchecked") +public abstract class AbstractHibernateDao implements IOperations { + private Class clazz; + + @Autowired + private SessionFactory sessionFactory; + + // API + + protected final void setClazz(final Class clazzToSet) { + clazz = Preconditions.checkNotNull(clazzToSet); + } + + @Override + public final T findOne(final long id) { + return (T) getCurrentSession().get(clazz, id); + } + + @Override + public final List findAll() { + return getCurrentSession().createQuery("from " + clazz.getName()).list(); + } + + @Override + public final void create(final T entity) { + Preconditions.checkNotNull(entity); + // getCurrentSession().persist(entity); + getCurrentSession().saveOrUpdate(entity); + } + + @Override + public final T update(final T entity) { + Preconditions.checkNotNull(entity); + return (T) getCurrentSession().merge(entity); + } + + @Override + public final void delete(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().delete(entity); + } + + @Override + public final void deleteById(final long entityId) { + final T entity = findOne(entityId); + Preconditions.checkState(entity != null); + delete(entity); + } + + protected final Session getCurrentSession() { + return sessionFactory.getCurrentSession(); + } + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/common/AbstractService.java b/spring-exceptions/src/main/java/com/baeldung/persistence/common/AbstractService.java new file mode 100644 index 0000000000..5e1cdcba17 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/common/AbstractService.java @@ -0,0 +1,43 @@ +package com.baeldung.persistence.common; + +import java.io.Serializable; +import java.util.List; + +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public abstract class AbstractService implements IOperations { + + @Override + public T findOne(final long id) { + return getDao().findOne(id); + } + + @Override + public List findAll() { + return getDao().findAll(); + } + + @Override + public void create(final T entity) { + getDao().create(entity); + } + + @Override + public T update(final T entity) { + return getDao().update(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } + + protected abstract IOperations getDao(); + +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/common/IOperations.java b/spring-exceptions/src/main/java/com/baeldung/persistence/common/IOperations.java new file mode 100644 index 0000000000..feac025a6d --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/common/IOperations.java @@ -0,0 +1,20 @@ +package com.baeldung.persistence.common; + +import java.io.Serializable; +import java.util.List; + +public interface IOperations { + + T findOne(final long id); + + List findAll(); + + void create(final T entity); + + T update(final T entity); + + void delete(final T entity); + + void deleteById(final long entityId); + +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/dao/IChildDao.java b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/IChildDao.java new file mode 100644 index 0000000000..b662be5da3 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/IChildDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.common.IOperations; +import com.baeldung.persistence.model.Child; + +public interface IChildDao extends IOperations { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/dao/IFooDao.java b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/IFooDao.java new file mode 100644 index 0000000000..131cd04768 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/IFooDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.common.IOperations; +import com.baeldung.persistence.model.Foo; + +public interface IFooDao extends IOperations { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/dao/IParentDao.java b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/IParentDao.java new file mode 100644 index 0000000000..63b39c05c2 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/IParentDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.common.IOperations; +import com.baeldung.persistence.model.Parent; + +public interface IParentDao extends IOperations { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/dao/impl/ChildDao.java b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/impl/ChildDao.java new file mode 100644 index 0000000000..428189f522 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/impl/ChildDao.java @@ -0,0 +1,24 @@ +package com.baeldung.persistence.dao.impl; + +import com.baeldung.persistence.common.AbstractHibernateDao; +import com.baeldung.persistence.model.Child; +import com.baeldung.persistence.dao.IChildDao; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +@Repository +public class ChildDao extends AbstractHibernateDao implements IChildDao { + + @Autowired + private SessionFactory sessionFactory; + + public ChildDao() { + super(); + + setClazz(Child.class); + } + + // API + +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java new file mode 100644 index 0000000000..2754a0e96d --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java @@ -0,0 +1,24 @@ +package com.baeldung.persistence.dao.impl; + +import com.baeldung.persistence.common.AbstractHibernateDao; +import com.baeldung.persistence.dao.IFooDao; +import com.baeldung.persistence.model.Foo; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +@Repository +public class FooDao extends AbstractHibernateDao implements IFooDao { + + @Autowired + private SessionFactory sessionFactory; + + public FooDao() { + super(); + + setClazz(Foo.class); + } + + // API + +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/dao/impl/ParentDao.java b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/impl/ParentDao.java new file mode 100644 index 0000000000..c1551b9f2e --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/dao/impl/ParentDao.java @@ -0,0 +1,24 @@ +package com.baeldung.persistence.dao.impl; + +import com.baeldung.persistence.common.AbstractHibernateDao; +import com.baeldung.persistence.model.Parent; +import com.baeldung.persistence.dao.IParentDao; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +@Repository +public class ParentDao extends AbstractHibernateDao implements IParentDao { + + @Autowired + private SessionFactory sessionFactory; + + public ParentDao() { + super(); + + setClazz(Parent.class); + } + + // API + +} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/model/Child.java b/spring-exceptions/src/main/java/com/baeldung/persistence/model/Child.java similarity index 95% rename from spring-exceptions/src/main/java/org/baeldung/persistence/model/Child.java rename to spring-exceptions/src/main/java/com/baeldung/persistence/model/Child.java index 4eec4cf1d3..19cfb2e237 100644 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/model/Child.java +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/model/Child.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.model; +package com.baeldung.persistence.model; import java.io.Serializable; diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/model/Foo.java b/spring-exceptions/src/main/java/com/baeldung/persistence/model/Foo.java new file mode 100644 index 0000000000..9af3d07bed --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/model/Foo.java @@ -0,0 +1,83 @@ +package com.baeldung.persistence.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false) + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + 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; + } + + // + + @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-exceptions/src/main/java/org/baeldung/persistence/model/Parent.java b/spring-exceptions/src/main/java/com/baeldung/persistence/model/Parent.java similarity index 96% rename from spring-exceptions/src/main/java/org/baeldung/persistence/model/Parent.java rename to spring-exceptions/src/main/java/com/baeldung/persistence/model/Parent.java index 19e405615d..fa6948990b 100644 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/model/Parent.java +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/model/Parent.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.model; +package com.baeldung.persistence.model; import java.io.Serializable; diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/service/IChildService.java b/spring-exceptions/src/main/java/com/baeldung/persistence/service/IChildService.java new file mode 100644 index 0000000000..e7af073a4d --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/service/IChildService.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.service; + +import com.baeldung.persistence.common.IOperations; +import com.baeldung.persistence.model.Child; + +public interface IChildService extends IOperations { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/service/IFooService.java b/spring-exceptions/src/main/java/com/baeldung/persistence/service/IFooService.java new file mode 100644 index 0000000000..f154391bb5 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/service/IFooService.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.service; + +import com.baeldung.persistence.common.IOperations; +import com.baeldung.persistence.model.Foo; + +public interface IFooService extends IOperations { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/service/IParentService.java b/spring-exceptions/src/main/java/com/baeldung/persistence/service/IParentService.java new file mode 100644 index 0000000000..1c7ee45219 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/service/IParentService.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.service; + +import com.baeldung.persistence.common.IOperations; +import com.baeldung.persistence.model.Parent; + +public interface IParentService extends IOperations { + // +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/service/impl/ChildService.java b/spring-exceptions/src/main/java/com/baeldung/persistence/service/impl/ChildService.java new file mode 100644 index 0000000000..ed913188f1 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/service/impl/ChildService.java @@ -0,0 +1,28 @@ +package com.baeldung.persistence.service.impl; + +import com.baeldung.persistence.common.AbstractService; +import com.baeldung.persistence.common.IOperations; +import com.baeldung.persistence.service.IChildService; +import com.baeldung.persistence.dao.IChildDao; +import com.baeldung.persistence.model.Child; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ChildService extends AbstractService implements IChildService { + + @Autowired + private IChildDao dao; + + public ChildService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/service/impl/FooService.java b/spring-exceptions/src/main/java/com/baeldung/persistence/service/impl/FooService.java new file mode 100644 index 0000000000..d3d7fe81c8 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/service/impl/FooService.java @@ -0,0 +1,28 @@ +package com.baeldung.persistence.service.impl; + +import com.baeldung.persistence.common.AbstractService; +import com.baeldung.persistence.common.IOperations; +import com.baeldung.persistence.service.IFooService; +import com.baeldung.persistence.dao.IFooDao; +import com.baeldung.persistence.model.Foo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class FooService extends AbstractService implements IFooService { + + @Autowired + private IFooDao dao; + + public FooService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} diff --git a/spring-exceptions/src/main/java/com/baeldung/persistence/service/impl/ParentService.java b/spring-exceptions/src/main/java/com/baeldung/persistence/service/impl/ParentService.java new file mode 100644 index 0000000000..b7fa75a716 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/persistence/service/impl/ParentService.java @@ -0,0 +1,28 @@ +package com.baeldung.persistence.service.impl; + +import com.baeldung.persistence.common.AbstractService; +import com.baeldung.persistence.common.IOperations; +import com.baeldung.persistence.model.Parent; +import com.baeldung.persistence.service.IParentService; +import com.baeldung.persistence.dao.IParentDao; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ParentService extends AbstractService implements IParentService { + + @Autowired + private IParentDao dao; + + public ParentService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} diff --git a/spring-exceptions/src/main/java/org/baeldung/properties/core/ComponentInXmlUsingProperties.java b/spring-exceptions/src/main/java/com/baeldung/properties/core/ComponentInXmlUsingProperties.java similarity index 95% rename from spring-exceptions/src/main/java/org/baeldung/properties/core/ComponentInXmlUsingProperties.java rename to spring-exceptions/src/main/java/com/baeldung/properties/core/ComponentInXmlUsingProperties.java index f695326cd6..35f54b90e5 100644 --- a/spring-exceptions/src/main/java/org/baeldung/properties/core/ComponentInXmlUsingProperties.java +++ b/spring-exceptions/src/main/java/com/baeldung/properties/core/ComponentInXmlUsingProperties.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.core; +package com.baeldung.properties.core; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-exceptions/src/main/java/org/baeldung/properties/core/ComponentUsingProperties.java b/spring-exceptions/src/main/java/com/baeldung/properties/core/ComponentUsingProperties.java similarity index 95% rename from spring-exceptions/src/main/java/org/baeldung/properties/core/ComponentUsingProperties.java rename to spring-exceptions/src/main/java/com/baeldung/properties/core/ComponentUsingProperties.java index 7e082702fe..ff6e11d453 100644 --- a/spring-exceptions/src/main/java/org/baeldung/properties/core/ComponentUsingProperties.java +++ b/spring-exceptions/src/main/java/com/baeldung/properties/core/ComponentUsingProperties.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.core; +package com.baeldung.properties.core; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java b/spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfig.java similarity index 88% rename from spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java rename to spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfig.java index 9b5d7ed047..80c17ef059 100644 --- a/spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.spring; +package com.baeldung.properties.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -7,7 +7,7 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration -@ComponentScan("org.baeldung.properties.core") +@ComponentScan("com.baeldung.properties.core") @PropertySource("classpath:foo.properties") public class PropertiesWithJavaConfig { diff --git a/spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfigOther.java b/spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfigOther.java similarity index 88% rename from spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfigOther.java rename to spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfigOther.java index 594ba0a09d..54d7814045 100644 --- a/spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfigOther.java +++ b/spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithJavaConfigOther.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.spring; +package com.baeldung.properties.spring; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; diff --git a/spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfig.java b/spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithXmlConfig.java similarity index 82% rename from spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfig.java rename to spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithXmlConfig.java index 9ad7febcb0..2a774f449f 100644 --- a/spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithXmlConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.spring; +package com.baeldung.properties.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:configForProperties.xml") -@ComponentScan("org.baeldung.core") +@ComponentScan("com.baeldung.core") public class PropertiesWithXmlConfig { public PropertiesWithXmlConfig() { diff --git a/spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigOne.java b/spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithXmlConfigOne.java similarity index 82% rename from spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigOne.java rename to spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithXmlConfigOne.java index 9061cc10d4..205741d22b 100644 --- a/spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigOne.java +++ b/spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithXmlConfigOne.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.spring; +package com.baeldung.properties.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:configForPropertiesOne.xml") -@ComponentScan("org.baeldung.core") +@ComponentScan("com.baeldung.core") public class PropertiesWithXmlConfigOne { public PropertiesWithXmlConfigOne() { diff --git a/spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java b/spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java similarity index 88% rename from spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java rename to spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java index e4365cbc8b..98f64eb94d 100644 --- a/spring-exceptions/src/main/java/org/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java +++ b/spring-exceptions/src/main/java/com/baeldung/properties/spring/PropertiesWithXmlConfigTwo.java @@ -1,4 +1,4 @@ -package org.baeldung.properties.spring; +package com.baeldung.properties.spring; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; diff --git a/spring-exceptions/src/main/java/com/baeldung/spring/config/CoreConfig.java b/spring-exceptions/src/main/java/com/baeldung/spring/config/CoreConfig.java new file mode 100644 index 0000000000..8c51378ca9 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/spring/config/CoreConfig.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@ComponentScan("com.baeldung.core") +public class CoreConfig extends WebMvcConfigurerAdapter { + + public CoreConfig() { + super(); + } + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/spring/config/MainWebAppInitializer.java b/spring-exceptions/src/main/java/com/baeldung/spring/config/MainWebAppInitializer.java new file mode 100644 index 0000000000..3aaa1c8aee --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/spring/config/MainWebAppInitializer.java @@ -0,0 +1,41 @@ +package com.baeldung.spring.config; + +import java.util.Set; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +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; + +public class MainWebAppInitializer implements WebApplicationInitializer { + + /** + * Register and configure all Servlet container components necessary to power the web application. + */ + @Override + public void onStartup(final ServletContext sc) throws ServletException { + System.out.println("MainWebAppInitializer.onStartup()"); + + // Create the 'root' Spring application context + final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); + root.scan("com.baeldung.spring.config"); + // root.getEnvironment().setDefaultProfiles("embedded"); + + // Manages the lifecycle of the root application context + 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 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-exceptions/src/main/java/com/baeldung/spring/config/MvcConfig.java b/spring-exceptions/src/main/java/com/baeldung/spring/config/MvcConfig.java new file mode 100644 index 0000000000..717e3c9356 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/spring/config/MvcConfig.java @@ -0,0 +1,39 @@ +package com.baeldung.spring.config; + +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.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("/sample.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-exceptions/src/main/java/com/baeldung/spring/config/PersistenceConfig.java b/spring-exceptions/src/main/java/com/baeldung/spring/config/PersistenceConfig.java new file mode 100644 index 0000000000..0a31b158d9 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/spring/config/PersistenceConfig.java @@ -0,0 +1,76 @@ +package com.baeldung.spring.config; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp.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.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-mysql.properties" }) +@ComponentScan({ "com.baeldung.persistence" }) +public class PersistenceConfig { + + @Autowired + private Environment env; + + public PersistenceConfig() { + 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 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 HibernateTransactionManager transactionManager() { + final HibernateTransactionManager txManager = new HibernateTransactionManager(); + txManager.setSessionFactory(sessionFactory().getObject()); + + return txManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + +} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause1/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause1/BeanA.java deleted file mode 100644 index 50d07c6d39..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause1/BeanA.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause1; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class BeanA { - - @Autowired - private BeanB dependency; - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause1/BeanB.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause1/BeanB.java deleted file mode 100644 index 8b4b17a0c6..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause1/BeanB.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause1; - -public class BeanB { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/BeanA.java deleted file mode 100644 index 352dd5f2db..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/BeanA.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause2; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class BeanA { - - @Autowired - private IBeanB dependency; - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/BeanB1.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/BeanB1.java deleted file mode 100644 index b9ec961d1e..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/BeanB1.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause2; - -import org.springframework.stereotype.Component; - -@Component -public class BeanB1 implements IBeanB { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/BeanB2.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/BeanB2.java deleted file mode 100644 index aa7fe8250a..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/BeanB2.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause2; - -import org.springframework.stereotype.Component; - -@Component -public class BeanB2 implements IBeanB { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/IBeanB.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/IBeanB.java deleted file mode 100644 index 60e8a0a429..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause2/IBeanB.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause2; - -public interface IBeanB { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause3/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause3/BeanA.java deleted file mode 100644 index 2f2d1b2684..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause3/BeanA.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause3; - -import org.springframework.stereotype.Component; - -@Component -public class BeanA { - - public BeanA() { - super(); - throw new NullPointerException(); - } -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause4/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause4/BeanA.java deleted file mode 100644 index 7886f30f22..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause4/BeanA.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause4; - -import org.springframework.stereotype.Component; - -@Component -public abstract class BeanA implements IBeanA { - // -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause4/IBeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause4/IBeanA.java deleted file mode 100644 index 2f25c1c365..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause4/IBeanA.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause4; - -public interface IBeanA { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause5/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause5/BeanA.java deleted file mode 100644 index b8f88125b2..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause5/BeanA.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause5; - -import org.springframework.stereotype.Component; - -@Component -public class BeanA implements IBeanA { - - public BeanA(final String name) { - super(); - System.out.println(name); - } - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause5/IBeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause5/IBeanA.java deleted file mode 100644 index 5c575e400c..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause5/IBeanA.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause5; - -public interface IBeanA { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause6/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause6/BeanA.java deleted file mode 100644 index 164b006340..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause6/BeanA.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause6; - -import org.springframework.stereotype.Component; - -@Component -public class BeanA { - private IBeanB dependency; -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause6/BeanB.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause6/BeanB.java deleted file mode 100644 index 4a7bdab280..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause6/BeanB.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause6; - -import org.springframework.stereotype.Component; - -@Component -public class BeanB implements IBeanB { - // -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause6/IBeanB.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause6/IBeanB.java deleted file mode 100644 index 36b436ce98..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause6/IBeanB.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause6; - -public interface IBeanB { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/BeanA.java deleted file mode 100644 index 2a0230fa3f..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/BeanA.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause8; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class BeanA implements IBeanA { - private IBeanB beanB; - - @Autowired - public BeanA(final IBeanB beanB) { - super(); - this.beanB = beanB; - } - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/BeanB.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/BeanB.java deleted file mode 100644 index 2e8a3eed07..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/BeanB.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause8; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class BeanB implements IBeanB { - final IBeanA beanA; - - @Autowired - public BeanB(final IBeanA beanA) { - super(); - this.beanA = beanA; - } -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/IBeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/IBeanA.java deleted file mode 100644 index 3d6c4eef28..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/IBeanA.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause8; - -public interface IBeanA { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/IBeanB.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/IBeanB.java deleted file mode 100644 index 5f6f438968..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause8/IBeanB.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause8; - -public interface IBeanB { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause9/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause9/BeanA.java deleted file mode 100644 index 28c39e2777..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause9/BeanA.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause9; - -public abstract class BeanA implements IBeanA { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause9/BeanB.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause9/BeanB.java deleted file mode 100644 index 5e076023f0..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause9/BeanB.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause9; - -public class BeanB { - // -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause9/IBeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause9/IBeanA.java deleted file mode 100644 index 82114b18da..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/cause9/IBeanA.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.beancreationexception.cause9; - -public interface IBeanA { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause1ContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause1ContextWithJavaConfig.java deleted file mode 100644 index cb74b96b67..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause1ContextWithJavaConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.ex.beancreationexception.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.ex.beancreationexception.cause1") -public class Cause1ContextWithJavaConfig { - - public Cause1ContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause2ContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause2ContextWithJavaConfig.java deleted file mode 100644 index 6b20439059..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause2ContextWithJavaConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.ex.beancreationexception.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.ex.beancreationexception.cause2") -public class Cause2ContextWithJavaConfig { - - public Cause2ContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause3ContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause3ContextWithJavaConfig.java deleted file mode 100644 index 437d2c4c20..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause3ContextWithJavaConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.ex.beancreationexception.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.ex.beancreationexception.cause3") -public class Cause3ContextWithJavaConfig { - - public Cause3ContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause5ContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause5ContextWithJavaConfig.java deleted file mode 100644 index 821041cb0c..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause5ContextWithJavaConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.ex.beancreationexception.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.ex.beancreationexception.cause5") -public class Cause5ContextWithJavaConfig { - - public Cause5ContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause8ContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause8ContextWithJavaConfig.java deleted file mode 100644 index 084cf8d3af..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beancreationexception/spring/Cause8ContextWithJavaConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.ex.beancreationexception.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.ex.beancreationexception.cause8") -public class Cause8ContextWithJavaConfig { - - public Cause8ContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/cause2/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/cause2/BeanA.java deleted file mode 100644 index a0aefda1cd..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/cause2/BeanA.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.ex.beandefinitionstoreexception.cause2; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -@Component -public class BeanA { - - @Value("${some.property2}") - private String someProperty2; - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/spring/Cause1ContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/spring/Cause1ContextWithJavaConfig.java deleted file mode 100644 index 3b6b4f2b8d..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/spring/Cause1ContextWithJavaConfig.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.ex.beandefinitionstoreexception.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; - -@Configuration -@ComponentScan("org.baeldung.ex.beandefinitionstoreexception.cause1") -@ImportResource("beans.xml") -public class Cause1ContextWithJavaConfig { - - public Cause1ContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/spring/Cause2ContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/spring/Cause2ContextWithJavaConfig.java deleted file mode 100644 index d31890e0f3..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/spring/Cause2ContextWithJavaConfig.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.baeldung.ex.beandefinitionstoreexception.spring; - -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.support.PropertySourcesPlaceholderConfigurer; - -@Configuration -@ComponentScan("org.baeldung.ex.beandefinitionstoreexception.cause2") -public class Cause2ContextWithJavaConfig { - - @Value("${some.property}") - private String someProperty; - - public Cause2ContextWithJavaConfig() { - super(); - } - - // beans - - @Bean - public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/spring/Cause3ContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/spring/Cause3ContextWithJavaConfig.java deleted file mode 100644 index 11a00b1770..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/beandefinitionstoreexception/spring/Cause3ContextWithJavaConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.ex.beandefinitionstoreexception.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.ex.beandefinitionstoreexception.cause3") -public class Cause3ContextWithJavaConfig { - - public Cause3ContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/dataintegrityviolationexception/spring/Cause2DataContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/dataintegrityviolationexception/spring/Cause2DataContextWithJavaConfig.java deleted file mode 100644 index 4dcae6282c..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/dataintegrityviolationexception/spring/Cause2DataContextWithJavaConfig.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung.ex.dataintegrityviolationexception.spring; - -import org.baeldung.spring.config.PersistenceConfig; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -@Configuration -@ComponentScan("org.baeldung.ex.dataIntegrityviolationexception.cause2") -@Import(PersistenceConfig.class) -public class Cause2DataContextWithJavaConfig { - - public Cause2DataContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/dataintegrityviolationexception/spring/Cause3DataContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/dataintegrityviolationexception/spring/Cause3DataContextWithJavaConfig.java deleted file mode 100644 index bb9b905854..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/dataintegrityviolationexception/spring/Cause3DataContextWithJavaConfig.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung.ex.dataintegrityviolationexception.spring; - -import org.baeldung.spring.config.PersistenceConfig; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -@Configuration -@ComponentScan("org.baeldung.ex.dataIntegrityviolationexception.cause3") -@Import(PersistenceConfig.class) -public class Cause3DataContextWithJavaConfig { - - public Cause3DataContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause1/persistence/model/Foo.java b/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause1/persistence/model/Foo.java deleted file mode 100644 index 001c14d6d6..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause1/persistence/model/Foo.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.ex.mappingexception.cause1.persistence.model; - -import java.io.Serializable; - -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -public class Foo implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - public Foo() { - super(); - } - - // API - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause2/persistence/model/Foo.java b/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause2/persistence/model/Foo.java deleted file mode 100644 index fa1200f710..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause2/persistence/model/Foo.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.baeldung.ex.mappingexception.cause2.persistence.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Foo implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - public Foo() { - super(); - } - - // API - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause3/persistence/model/Foo.java b/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause3/persistence/model/Foo.java deleted file mode 100644 index 243196786c..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause3/persistence/model/Foo.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.baeldung.ex.mappingexception.cause3.persistence.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Foo implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - public Foo() { - super(); - } - - // API - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause4/persistence/model/Foo.java b/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause4/persistence/model/Foo.java deleted file mode 100644 index 11e71edf01..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/mappingexception/cause4/persistence/model/Foo.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.baeldung.ex.mappingexception.cause4.persistence.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Foo implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - public Foo() { - super(); - } - - // API - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanA.java deleted file mode 100644 index c664309426..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanA.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.ex.nosuchbeandefinitionexception.cause1; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class BeanA { - - @Autowired - private BeanB dependency; - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanB.java b/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanB.java deleted file mode 100644 index 8a198422e8..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause1/BeanB.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.nosuchbeandefinitionexception.cause1; - -public class BeanB { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanA.java deleted file mode 100644 index 2b454bfabb..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanA.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.ex.nosuchbeandefinitionexception.cause2; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class BeanA { - - @Autowired - private IBeanB dependency; - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB1.java b/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB1.java deleted file mode 100644 index 877f400668..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB1.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.ex.nosuchbeandefinitionexception.cause2; - -import org.springframework.stereotype.Component; - -@Component -public class BeanB1 implements IBeanB { - // -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB2.java b/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB2.java deleted file mode 100644 index 6bf4160966..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/BeanB2.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.ex.nosuchbeandefinitionexception.cause2; - -import org.springframework.stereotype.Component; - -@Component -public class BeanB2 implements IBeanB { - // -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/IBeanB.java b/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/IBeanB.java deleted file mode 100644 index 3e70126c1a..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause2/IBeanB.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.ex.nosuchbeandefinitionexception.cause2; - -public interface IBeanB { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause3/BeanA.java b/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause3/BeanA.java deleted file mode 100644 index 091d3f1aa8..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/cause3/BeanA.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung.ex.nosuchbeandefinitionexception.cause3; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Component; - -@Component -public class BeanA implements InitializingBean { - - @Autowired - private ApplicationContext context; - - @Override - public void afterPropertiesSet() { - context.getBean("someBeanName"); - } - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/spring/Cause1ContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/spring/Cause1ContextWithJavaConfig.java deleted file mode 100644 index 5ba971baa9..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/spring/Cause1ContextWithJavaConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.ex.nosuchbeandefinitionexception.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.ex.nosuchbeandefinitionexception.cause1") -public class Cause1ContextWithJavaConfig { - - public Cause1ContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/spring/Cause2ContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/spring/Cause2ContextWithJavaConfig.java deleted file mode 100644 index 9f4816ef7c..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/spring/Cause2ContextWithJavaConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.ex.nosuchbeandefinitionexception.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.ex.nosuchbeandefinitionexception.cause2") -public class Cause2ContextWithJavaConfig { - - public Cause2ContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/spring/Cause3ContextWithJavaConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/spring/Cause3ContextWithJavaConfig.java deleted file mode 100644 index a8d0fbe37b..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nosuchbeandefinitionexception/spring/Cause3ContextWithJavaConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.ex.nosuchbeandefinitionexception.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.ex.nosuchbeandefinitionexception.cause3") -public class Cause3ContextWithJavaConfig { - - public Cause3ContextWithJavaConfig() { - super(); - } - - // beans - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/Setup.java b/spring-exceptions/src/main/java/org/baeldung/persistence/Setup.java deleted file mode 100644 index 5cba4e70fb..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/Setup.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.persistence; - -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.stereotype.Component; - -@Component -public class Setup implements ApplicationListener { - - private boolean setupDone; - - public Setup() { - super(); - } - - // - - @Override - public final void onApplicationEvent(final ContextRefreshedEvent event) { - if (!setupDone) { - System.out.println(); - setupDone = true; - } - } - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/common/AbstractHibernateDao.java b/spring-exceptions/src/main/java/org/baeldung/persistence/common/AbstractHibernateDao.java deleted file mode 100644 index cadb2ac061..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/common/AbstractHibernateDao.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.baeldung.persistence.common; - -import java.io.Serializable; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.google.common.base.Preconditions; - -@SuppressWarnings("unchecked") -public abstract class AbstractHibernateDao implements IOperations { - private Class clazz; - - @Autowired - private SessionFactory sessionFactory; - - // API - - protected final void setClazz(final Class clazzToSet) { - clazz = Preconditions.checkNotNull(clazzToSet); - } - - @Override - public final T findOne(final long id) { - return (T) getCurrentSession().get(clazz, id); - } - - @Override - public final List findAll() { - return getCurrentSession().createQuery("from " + clazz.getName()).list(); - } - - @Override - public final void create(final T entity) { - Preconditions.checkNotNull(entity); - // getCurrentSession().persist(entity); - getCurrentSession().saveOrUpdate(entity); - } - - @Override - public final T update(final T entity) { - Preconditions.checkNotNull(entity); - return (T) getCurrentSession().merge(entity); - } - - @Override - public final void delete(final T entity) { - Preconditions.checkNotNull(entity); - getCurrentSession().delete(entity); - } - - @Override - public final void deleteById(final long entityId) { - final T entity = findOne(entityId); - Preconditions.checkState(entity != null); - delete(entity); - } - - protected final Session getCurrentSession() { - return sessionFactory.getCurrentSession(); - } - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/common/AbstractService.java b/spring-exceptions/src/main/java/org/baeldung/persistence/common/AbstractService.java deleted file mode 100644 index d2e162ad7b..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/common/AbstractService.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.baeldung.persistence.common; - -import java.io.Serializable; -import java.util.List; - -import org.baeldung.persistence.common.IOperations; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public abstract class AbstractService implements IOperations { - - @Override - public T findOne(final long id) { - return getDao().findOne(id); - } - - @Override - public List findAll() { - return getDao().findAll(); - } - - @Override - public void create(final T entity) { - getDao().create(entity); - } - - @Override - public T update(final T entity) { - return getDao().update(entity); - } - - @Override - public void delete(final T entity) { - getDao().delete(entity); - } - - @Override - public void deleteById(final long entityId) { - getDao().deleteById(entityId); - } - - protected abstract IOperations getDao(); - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/common/IOperations.java b/spring-exceptions/src/main/java/org/baeldung/persistence/common/IOperations.java deleted file mode 100644 index dee27950c7..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/common/IOperations.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung.persistence.common; - -import java.io.Serializable; -import java.util.List; - -public interface IOperations { - - T findOne(final long id); - - List findAll(); - - void create(final T entity); - - T update(final T entity); - - void delete(final T entity); - - void deleteById(final long entityId); - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/IChildDao.java b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/IChildDao.java deleted file mode 100644 index 25290554f3..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/IChildDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.common.IOperations; -import org.baeldung.persistence.model.Child; - -public interface IChildDao extends IOperations { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/IFooDao.java b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/IFooDao.java deleted file mode 100644 index b41cd9edde..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/IFooDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.common.IOperations; -import org.baeldung.persistence.model.Foo; - -public interface IFooDao extends IOperations { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/IParentDao.java b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/IParentDao.java deleted file mode 100644 index a047d97ef1..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/IParentDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.common.IOperations; -import org.baeldung.persistence.model.Parent; - -public interface IParentDao extends IOperations { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ChildDao.java b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ChildDao.java deleted file mode 100644 index e068573c5c..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ChildDao.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.persistence.dao.impl; - -import org.baeldung.persistence.common.AbstractHibernateDao; -import org.baeldung.persistence.dao.IChildDao; -import org.baeldung.persistence.model.Child; -import org.hibernate.SessionFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; - -@Repository -public class ChildDao extends AbstractHibernateDao implements IChildDao { - - @Autowired - private SessionFactory sessionFactory; - - public ChildDao() { - super(); - - setClazz(Child.class); - } - - // API - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java deleted file mode 100644 index baf29c9ecd..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.persistence.dao.impl; - -import org.baeldung.persistence.common.AbstractHibernateDao; -import org.baeldung.persistence.dao.IFooDao; -import org.baeldung.persistence.model.Foo; -import org.hibernate.SessionFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; - -@Repository -public class FooDao extends AbstractHibernateDao implements IFooDao { - - @Autowired - private SessionFactory sessionFactory; - - public FooDao() { - super(); - - setClazz(Foo.class); - } - - // API - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ParentDao.java b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ParentDao.java deleted file mode 100644 index 5634137b63..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ParentDao.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.persistence.dao.impl; - -import org.baeldung.persistence.common.AbstractHibernateDao; -import org.baeldung.persistence.dao.IParentDao; -import org.baeldung.persistence.model.Parent; -import org.hibernate.SessionFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; - -@Repository -public class ParentDao extends AbstractHibernateDao implements IParentDao { - - @Autowired - private SessionFactory sessionFactory; - - public ParentDao() { - super(); - - setClazz(Parent.class); - } - - // API - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-exceptions/src/main/java/org/baeldung/persistence/model/Foo.java deleted file mode 100644 index 8e1dee33e8..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/model/Foo.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.baeldung.persistence.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Foo implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - @Column(nullable = false) - private String name; - - public Foo() { - super(); - } - - public Foo(final String name) { - super(); - - 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; - } - - // - - @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-exceptions/src/main/java/org/baeldung/persistence/service/IChildService.java b/spring-exceptions/src/main/java/org/baeldung/persistence/service/IChildService.java deleted file mode 100644 index e2c2055ca2..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/service/IChildService.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.service; - -import org.baeldung.persistence.common.IOperations; -import org.baeldung.persistence.model.Child; - -public interface IChildService extends IOperations { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/service/IFooService.java b/spring-exceptions/src/main/java/org/baeldung/persistence/service/IFooService.java deleted file mode 100644 index 64b826db02..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/service/IFooService.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.service; - -import org.baeldung.persistence.common.IOperations; -import org.baeldung.persistence.model.Foo; - -public interface IFooService extends IOperations { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/service/IParentService.java b/spring-exceptions/src/main/java/org/baeldung/persistence/service/IParentService.java deleted file mode 100644 index a05f07658f..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/service/IParentService.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.service; - -import org.baeldung.persistence.common.IOperations; -import org.baeldung.persistence.model.Parent; - -public interface IParentService extends IOperations { - // -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ChildService.java b/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ChildService.java deleted file mode 100644 index 89597313ea..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ChildService.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.baeldung.persistence.service.impl; - -import org.baeldung.persistence.common.AbstractService; -import org.baeldung.persistence.common.IOperations; -import org.baeldung.persistence.dao.IChildDao; -import org.baeldung.persistence.model.Child; -import org.baeldung.persistence.service.IChildService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class ChildService extends AbstractService implements IChildService { - - @Autowired - private IChildDao dao; - - public ChildService() { - super(); - } - - // API - - @Override - protected IOperations getDao() { - return dao; - } - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/FooService.java b/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/FooService.java deleted file mode 100644 index f0a4d7a649..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/FooService.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.baeldung.persistence.service.impl; - -import org.baeldung.persistence.common.AbstractService; -import org.baeldung.persistence.common.IOperations; -import org.baeldung.persistence.dao.IFooDao; -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class FooService extends AbstractService implements IFooService { - - @Autowired - private IFooDao dao; - - public FooService() { - super(); - } - - // API - - @Override - protected IOperations getDao() { - return dao; - } - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ParentService.java b/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ParentService.java deleted file mode 100644 index 97c44f4a2f..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ParentService.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.baeldung.persistence.service.impl; - -import org.baeldung.persistence.common.AbstractService; -import org.baeldung.persistence.common.IOperations; -import org.baeldung.persistence.dao.IParentDao; -import org.baeldung.persistence.model.Parent; -import org.baeldung.persistence.service.IParentService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class ParentService extends AbstractService implements IParentService { - - @Autowired - private IParentDao dao; - - public ParentService() { - super(); - } - - // API - - @Override - protected IOperations getDao() { - return dao; - } - -} diff --git a/spring-exceptions/src/main/java/org/baeldung/spring/config/CoreConfig.java b/spring-exceptions/src/main/java/org/baeldung/spring/config/CoreConfig.java deleted file mode 100644 index ff1742351b..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/spring/config/CoreConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.spring.config; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@ComponentScan("org.baeldung.core") -public class CoreConfig extends WebMvcConfigurerAdapter { - - public CoreConfig() { - super(); - } - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java b/spring-exceptions/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java deleted file mode 100644 index 5ef83b8afd..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.spring.config; - -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -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; - -public class MainWebAppInitializer implements WebApplicationInitializer { - - /** - * Register and configure all Servlet container components necessary to power the web application. - */ - @Override - public void onStartup(final ServletContext sc) throws ServletException { - System.out.println("MainWebAppInitializer.onStartup()"); - - // Create the 'root' Spring application context - final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.scan("org.baeldung.spring.config"); - // root.getEnvironment().setDefaultProfiles("embedded"); - - // Manages the lifecycle of the root application context - 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 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-exceptions/src/main/java/org/baeldung/spring/config/MvcConfig.java b/spring-exceptions/src/main/java/org/baeldung/spring/config/MvcConfig.java deleted file mode 100644 index f87e400fce..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/spring/config/MvcConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.spring.config; - -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.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("/sample.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-exceptions/src/main/java/org/baeldung/spring/config/PersistenceConfig.java b/spring-exceptions/src/main/java/org/baeldung/spring/config/PersistenceConfig.java deleted file mode 100644 index 4fb3fdacd5..0000000000 --- a/spring-exceptions/src/main/java/org/baeldung/spring/config/PersistenceConfig.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.baeldung.spring.config; - -import java.util.Properties; - -import javax.sql.DataSource; - -import org.apache.tomcat.dbcp.dbcp.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.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.google.common.base.Preconditions; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-mysql.properties" }) -@ComponentScan({ "org.baeldung.persistence" }) -public class PersistenceConfig { - - @Autowired - private Environment env; - - public PersistenceConfig() { - super(); - } - - @Bean - public LocalSessionFactoryBean sessionFactory() { - final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); - sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); - sessionFactory.setHibernateProperties(hibernateProperties()); - - return sessionFactory; - } - - @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 HibernateTransactionManager transactionManager() { - final HibernateTransactionManager txManager = new HibernateTransactionManager(); - txManager.setSessionFactory(sessionFactory().getObject()); - - return txManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - final Properties hibernateProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); - return hibernateProperties; - } - -} \ No newline at end of file diff --git a/spring-exceptions/src/main/resources/beancreationexception_cause4.xml b/spring-exceptions/src/main/resources/beancreationexception_cause4.xml index ad7edc3763..47f55db2d7 100644 --- a/spring-exceptions/src/main/resources/beancreationexception_cause4.xml +++ b/spring-exceptions/src/main/resources/beancreationexception_cause4.xml @@ -6,6 +6,6 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> - + \ No newline at end of file diff --git a/spring-exceptions/src/main/resources/beancreationexception_cause6.xml b/spring-exceptions/src/main/resources/beancreationexception_cause6.xml index fe60786151..fdfed069f0 100644 --- a/spring-exceptions/src/main/resources/beancreationexception_cause6.xml +++ b/spring-exceptions/src/main/resources/beancreationexception_cause6.xml @@ -6,7 +6,7 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> - + diff --git a/spring-exceptions/src/main/resources/beancreationexception_cause7.xml b/spring-exceptions/src/main/resources/beancreationexception_cause7.xml index d8ef7dd18c..29b7bab317 100644 --- a/spring-exceptions/src/main/resources/beancreationexception_cause7.xml +++ b/spring-exceptions/src/main/resources/beancreationexception_cause7.xml @@ -6,6 +6,6 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> - + \ No newline at end of file diff --git a/spring-exceptions/src/main/resources/beancreationexception_cause9.xml b/spring-exceptions/src/main/resources/beancreationexception_cause9.xml index 5d658f819f..b059ec67c3 100644 --- a/spring-exceptions/src/main/resources/beancreationexception_cause9.xml +++ b/spring-exceptions/src/main/resources/beancreationexception_cause9.xml @@ -6,6 +6,6 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> - + \ No newline at end of file diff --git a/spring-exceptions/src/main/resources/configForProperties.xml b/spring-exceptions/src/main/resources/configForProperties.xml index 0f766665eb..e61d883c70 100644 --- a/spring-exceptions/src/main/resources/configForProperties.xml +++ b/spring-exceptions/src/main/resources/configForProperties.xml @@ -9,7 +9,7 @@ - + diff --git a/spring-exceptions/src/main/resources/configForPropertiesOne.xml b/spring-exceptions/src/main/resources/configForPropertiesOne.xml index 068c86a840..53072d89bb 100644 --- a/spring-exceptions/src/main/resources/configForPropertiesOne.xml +++ b/spring-exceptions/src/main/resources/configForPropertiesOne.xml @@ -9,7 +9,7 @@ - + diff --git a/spring-exceptions/src/main/webapp/WEB-INF/web_old.xml b/spring-exceptions/src/main/webapp/WEB-INF/web_old.xml index 016369ad27..c8b38fae30 100644 --- a/spring-exceptions/src/main/webapp/WEB-INF/web_old.xml +++ b/spring-exceptions/src/main/webapp/WEB-INF/web_old.xml @@ -16,7 +16,7 @@ contextConfigLocation - org.baeldung.spring.web.config + com.baeldung.spring.web.config diff --git a/spring-exceptions/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-exceptions/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..a9ba0cf5c1 --- /dev/null +++ b/spring-exceptions/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.spring.config.PersistenceConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java similarity index 93% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java index 9597c09568..81fb4770ac 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java @@ -1,4 +1,4 @@ -package org.baeldung.ex.beancreationexception; +package com.baeldung.ex.beancreationexception; import org.junit.runner.RunWith; import org.junit.runners.Suite; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java similarity index 84% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java index 350347bb19..441e17cf98 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beancreationexception; +package com.baeldung.ex.beancreationexception; -import org.baeldung.ex.beancreationexception.spring.Cause1ContextWithJavaConfig; +import com.baeldung.ex.beancreationexception.spring.Cause1ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java similarity index 84% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java index c2b9561848..6b760d4fbe 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beancreationexception; +package com.baeldung.ex.beancreationexception; -import org.baeldung.ex.beancreationexception.spring.Cause2ContextWithJavaConfig; +import com.baeldung.ex.beancreationexception.spring.Cause2ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java similarity index 84% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java index 7b9b49bf58..83935c2e2e 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beancreationexception; +package com.baeldung.ex.beancreationexception; -import org.baeldung.ex.beancreationexception.spring.Cause3ContextWithJavaConfig; +import com.baeldung.ex.beancreationexception.spring.Cause3ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java similarity index 84% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java index 3a6e30476c..0e4d83e929 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beancreationexception; +package com.baeldung.ex.beancreationexception; -import org.baeldung.ex.beancreationexception.spring.Cause4ContextWithJavaConfig; +import com.baeldung.ex.beancreationexception.spring.Cause4ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java similarity index 84% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java index e69a323f8d..828c200a3d 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beancreationexception; +package com.baeldung.ex.beancreationexception; -import org.baeldung.ex.beancreationexception.spring.Cause5ContextWithJavaConfig; +import com.baeldung.ex.beancreationexception.spring.Cause5ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java similarity index 84% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java index 30fbd47635..9bae716684 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beancreationexception; +package com.baeldung.ex.beancreationexception; -import org.baeldung.ex.beancreationexception.spring.Cause6ContextWithJavaConfig; +import com.baeldung.ex.beancreationexception.spring.Cause6ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java similarity index 84% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java index d832bddf72..35606d4339 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beancreationexception; +package com.baeldung.ex.beancreationexception; -import org.baeldung.ex.beancreationexception.spring.Cause7ContextWithJavaConfig; +import com.baeldung.ex.beancreationexception.spring.Cause7ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java similarity index 84% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java index a9f32b6d1a..51809af8bf 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beancreationexception; +package com.baeldung.ex.beancreationexception; -import org.baeldung.ex.beancreationexception.spring.Cause8ContextWithJavaConfig; +import com.baeldung.ex.beancreationexception.spring.Cause8ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java similarity index 84% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java index 6af5fb3712..9a6cee8192 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beancreationexception; +package com.baeldung.ex.beancreationexception; -import org.baeldung.ex.beancreationexception.spring.Cause9ContextWithJavaConfig; +import com.baeldung.ex.beancreationexception.spring.Cause9ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java similarity index 83% rename from spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java index 1580546fa7..f5c3cc1ed8 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beandefinitionstoreexception; +package com.baeldung.ex.beandefinitionstoreexception; -import org.baeldung.ex.beandefinitionstoreexception.spring.Cause1ContextWithJavaConfig; +import com.baeldung.ex.beandefinitionstoreexception.spring.Cause1ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java similarity index 83% rename from spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java index ce0db694dc..cddbb173ec 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beandefinitionstoreexception; +package com.baeldung.ex.beandefinitionstoreexception; -import org.baeldung.ex.beandefinitionstoreexception.spring.Cause2ContextWithJavaConfig; +import com.baeldung.ex.beandefinitionstoreexception.spring.Cause2ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java similarity index 83% rename from spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java index c090ac7b5f..a5c458be9f 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.beandefinitionstoreexception; +package com.baeldung.ex.beandefinitionstoreexception; -import org.baeldung.ex.beandefinitionstoreexception.spring.Cause3ContextWithJavaConfig; +import com.baeldung.ex.beandefinitionstoreexception.spring.Cause3ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java similarity index 82% rename from spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java index 056e052359..e41f916000 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java @@ -1,10 +1,10 @@ -package org.baeldung.ex.dataintegrityviolationexception; +package com.baeldung.ex.dataintegrityviolationexception; -import org.baeldung.ex.dataintegrityviolationexception.spring.Cause1DataContextWithJavaConfig; -import org.baeldung.persistence.model.Child; -import org.baeldung.persistence.model.Parent; -import org.baeldung.persistence.service.IChildService; -import org.baeldung.persistence.service.IParentService; +import com.baeldung.ex.dataintegrityviolationexception.spring.Cause1DataContextWithJavaConfig; +import com.baeldung.persistence.model.Child; +import com.baeldung.persistence.model.Parent; +import com.baeldung.persistence.service.IChildService; +import com.baeldung.persistence.service.IParentService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java similarity index 80% rename from spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java index e36a027105..b41cead90d 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java @@ -1,8 +1,8 @@ -package org.baeldung.ex.dataintegrityviolationexception; +package com.baeldung.ex.dataintegrityviolationexception; -import org.baeldung.ex.dataintegrityviolationexception.spring.Cause2DataContextWithJavaConfig; -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; +import com.baeldung.ex.dataintegrityviolationexception.spring.Cause2DataContextWithJavaConfig; +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IFooService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java similarity index 82% rename from spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java index 4194e1c9fe..c41321c144 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java @@ -1,10 +1,10 @@ -package org.baeldung.ex.dataintegrityviolationexception; +package com.baeldung.ex.dataintegrityviolationexception; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import org.baeldung.ex.dataintegrityviolationexception.spring.Cause3DataContextWithJavaConfig; -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; +import com.baeldung.ex.dataintegrityviolationexception.spring.Cause3DataContextWithJavaConfig; +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IFooService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java similarity index 85% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java index 7ba9618a77..b00b9d7257 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java @@ -1,7 +1,7 @@ -package org.baeldung.ex.mappingexception; +package com.baeldung.ex.mappingexception; -import org.baeldung.ex.mappingexception.cause1.persistence.model.Foo; -import org.baeldung.ex.mappingexception.spring.Cause1PersistenceConfig; +import com.baeldung.ex.mappingexception.cause1.persistence.model.Foo; +import com.baeldung.ex.mappingexception.spring.Cause1PersistenceConfig; import org.hibernate.MappingException; import org.hibernate.SessionFactory; import org.junit.Test; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java similarity index 84% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java index 66923fc6a9..1ff4170276 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java @@ -1,7 +1,7 @@ -package org.baeldung.ex.mappingexception; +package com.baeldung.ex.mappingexception; -import org.baeldung.ex.mappingexception.cause2.persistence.model.Foo; -import org.baeldung.ex.mappingexception.spring.Cause2PersistenceConfig; +import com.baeldung.ex.mappingexception.cause2.persistence.model.Foo; +import com.baeldung.ex.mappingexception.spring.Cause2PersistenceConfig; import org.hibernate.SessionFactory; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java similarity index 85% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java index e6888d1685..54a4c9cde3 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java @@ -1,7 +1,7 @@ -package org.baeldung.ex.mappingexception; +package com.baeldung.ex.mappingexception; -import org.baeldung.ex.mappingexception.cause3.persistence.model.Foo; -import org.baeldung.ex.mappingexception.spring.Cause3PersistenceConfig; +import com.baeldung.ex.mappingexception.cause3.persistence.model.Foo; +import com.baeldung.ex.mappingexception.spring.Cause3PersistenceConfig; import org.hibernate.MappingException; import org.hibernate.SessionFactory; import org.junit.Test; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java similarity index 93% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java index ea90b3d6cc..7f6b765073 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java @@ -1,10 +1,10 @@ -package org.baeldung.ex.mappingexception; +package com.baeldung.ex.mappingexception; import java.io.IOException; import java.io.InputStream; import java.util.Properties; -import org.baeldung.ex.mappingexception.cause4.persistence.model.Foo; +import com.baeldung.ex.mappingexception.cause4.persistence.model.Foo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; diff --git a/spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java new file mode 100644 index 0000000000..2aebf6ff42 --- /dev/null +++ b/spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java @@ -0,0 +1,27 @@ +package com.baeldung.ex.nontransientdataaccessexception; + +import javax.sql.DataSource; + +import com.baeldung.ex.nontransientexception.cause.Cause5NonTransientConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.CannotGetJdbcConnectionException; +import org.springframework.jdbc.core.JdbcTemplate; +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 = { Cause5NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) +public class CannotGetJdbcConnectionExceptionManualTest { + + @Autowired + private DataSource restDataSource; + + @Test(expected = CannotGetJdbcConnectionException.class) + public void whenJdbcUrlIncorrect_thenCannotGetJdbcConnectionException() { + JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + jdbcTemplate.execute("select * from foo"); + } +} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java similarity index 87% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java index b98a210125..2450554055 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java @@ -1,10 +1,10 @@ -package org.baeldung.ex.nontransientdataaccessexception; +package com.baeldung.ex.nontransientdataaccessexception; import javax.sql.DataSource; -import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; +import com.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IFooService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java similarity index 92% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java index 122278580f..8f0d6d60cc 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java @@ -1,9 +1,9 @@ -package org.baeldung.ex.nontransientdataaccessexception; +package com.baeldung.ex.nontransientdataaccessexception; import javax.sql.DataSource; -import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; -import org.baeldung.persistence.model.Foo; +import com.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; +import com.baeldung.persistence.model.Foo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java similarity index 89% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java index 4da5f94098..508fb77e61 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java @@ -1,8 +1,8 @@ -package org.baeldung.ex.nontransientdataaccessexception; +package com.baeldung.ex.nontransientdataaccessexception; import javax.sql.DataSource; -import org.baeldung.ex.nontransientexception.cause.Cause4NonTransientConfig; +import com.baeldung.ex.nontransientexception.cause.Cause4NonTransientConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java similarity index 90% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java index fc420acfe9..3e64f69884 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java @@ -1,7 +1,7 @@ -package org.baeldung.ex.nontransientdataaccessexception; +package com.baeldung.ex.nontransientdataaccessexception; -import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; -import org.baeldung.persistence.service.IFooService; +import com.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; +import com.baeldung.persistence.service.IFooService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-exceptions/src/test/java/com/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java new file mode 100644 index 0000000000..52cd2f31ea --- /dev/null +++ b/spring-exceptions/src/test/java/com/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java @@ -0,0 +1,19 @@ +package com.baeldung.ex.nosuchbeandefinitionexception; + +import com.baeldung.ex.nosuchbeandefinitionexception.spring.Cause1ContextWithJavaConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Cause1ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) +public class Cause1NoSuchBeanDefinitionExceptionManualTest { + + @Test + public final void givenContextIsInitialized_thenNoException() { + // + } + +} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java similarity index 83% rename from spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java index 09ed2b4435..b165482ea1 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.nosuchbeandefinitionexception; +package com.baeldung.ex.nosuchbeandefinitionexception; -import org.baeldung.ex.nosuchbeandefinitionexception.spring.Cause2ContextWithJavaConfig; +import com.baeldung.ex.nosuchbeandefinitionexception.spring.Cause2ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java b/spring-exceptions/src/test/java/com/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java similarity index 83% rename from spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java index 7dc016a568..ec0f8c8b1e 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.ex.nosuchbeandefinitionexception; +package com.baeldung.ex.nosuchbeandefinitionexception; -import org.baeldung.ex.nosuchbeandefinitionexception.spring.Cause3ContextWithJavaConfig; +import com.baeldung.ex.nosuchbeandefinitionexception.spring.Cause3ContextWithJavaConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaManualTest.java b/spring-exceptions/src/test/java/com/baeldung/properties/core/PropertiesWithJavaManualTest.java similarity index 86% rename from spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/properties/core/PropertiesWithJavaManualTest.java index 91db8210b3..e3f360e6a5 100644 --- a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/properties/core/PropertiesWithJavaManualTest.java @@ -1,7 +1,7 @@ -package org.baeldung.properties.core; +package com.baeldung.properties.core; -import org.baeldung.properties.spring.PropertiesWithJavaConfig; -import org.baeldung.properties.spring.PropertiesWithJavaConfigOther; +import com.baeldung.properties.spring.PropertiesWithJavaConfig; +import com.baeldung.properties.spring.PropertiesWithJavaConfigOther; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java b/spring-exceptions/src/test/java/com/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java similarity index 86% rename from spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java index 201e554381..b63cd74646 100644 --- a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java @@ -1,7 +1,7 @@ -package org.baeldung.properties.core; +package com.baeldung.properties.core; -import org.baeldung.properties.spring.PropertiesWithXmlConfigOne; -import org.baeldung.properties.spring.PropertiesWithXmlConfigTwo; +import com.baeldung.properties.spring.PropertiesWithXmlConfigOne; +import com.baeldung.properties.spring.PropertiesWithXmlConfigTwo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlManualTest.java b/spring-exceptions/src/test/java/com/baeldung/properties/core/PropertiesWithXmlManualTest.java similarity index 90% rename from spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlManualTest.java rename to spring-exceptions/src/test/java/com/baeldung/properties/core/PropertiesWithXmlManualTest.java index a54dd8a3fb..b848dab75f 100644 --- a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlManualTest.java +++ b/spring-exceptions/src/test/java/com/baeldung/properties/core/PropertiesWithXmlManualTest.java @@ -1,6 +1,6 @@ -package org.baeldung.properties.core; +package com.baeldung.properties.core; -import org.baeldung.properties.spring.PropertiesWithXmlConfig; +import com.baeldung.properties.spring.PropertiesWithXmlConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-exceptions/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-exceptions/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index ece7e0e730..0000000000 --- a/spring-exceptions/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.config.PersistenceConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java deleted file mode 100644 index b7ed103394..0000000000 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.baeldung.ex.nontransientdataaccessexception; - -import javax.sql.DataSource; - -import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; -import org.baeldung.ex.nontransientexception.cause.Cause5NonTransientConfig; -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.jdbc.CannotGetJdbcConnectionException; -import org.springframework.jdbc.core.JdbcTemplate; -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 = { Cause5NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class CannotGetJdbcConnectionExceptionManualTest { - - @Autowired - private DataSource restDataSource; - - @Test(expected = CannotGetJdbcConnectionException.class) - public void whenJdbcUrlIncorrect_thenCannotGetJdbcConnectionException() { - JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); - jdbcTemplate.execute("select * from foo"); - } -} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java deleted file mode 100644 index 45ffdf9096..0000000000 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung.ex.nosuchbeandefinitionexception; - -import org.baeldung.ex.nosuchbeandefinitionexception.spring.Cause1ContextWithJavaConfig; -import org.baeldung.persistence.model.Child; -import org.baeldung.persistence.model.Parent; -import org.baeldung.persistence.service.IChildService; -import org.baeldung.persistence.service.IParentService; -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.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { Cause1ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause1NoSuchBeanDefinitionExceptionManualTest { - - @Test - public final void givenContextIsInitialized_thenNoException() { - // - } - -} diff --git a/spring-freemarker/src/test/java/com/baeldung/SpringContextTest.java b/spring-freemarker/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..32db673519 --- /dev/null +++ b/spring-freemarker/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.freemarker.config.SpringWebConfig; +import com.baeldung.freemarker.config.WebConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringWebConfig.class, WebConfiguration.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java b/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 49b8fe94d1..0000000000 --- a/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -import com.baeldung.freemarker.config.SpringWebConfig; -import com.baeldung.freemarker.config.WebConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { SpringWebConfig.class, WebConfiguration.class }) -@WebAppConfiguration -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index ebdde5a1ee..a985f55d89 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -85,7 +85,7 @@ com.h2database h2 - 1.4.197 + ${h2.version} @@ -124,6 +124,7 @@ 1.1.1 2.10 1.5.0 + 1.4.197
diff --git a/spring-integration/src/test/java/com/baeldung/SpringContextTest.java b/spring-integration/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..60050eafa0 --- /dev/null +++ b/spring-integration/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.si.security.MessageConsumer; +import com.baeldung.si.security.SecuredDirectChannel; +import com.baeldung.si.security.SecurityConfig; +import com.baeldung.si.security.SecurityPubSubChannel; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SecurityConfig.class, SecuredDirectChannel.class, SecurityPubSubChannel.class, + MessageConsumer.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-integration/src/test/java/org/baeldung/SpringContextTest.java b/spring-integration/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e45997b71e..0000000000 --- a/spring-integration/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.si.security.MessageConsumer; -import com.baeldung.si.security.SecuredDirectChannel; -import com.baeldung.si.security.SecurityConfig; -import com.baeldung.si.security.SecurityPubSubChannel; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { SecurityConfig.class, SecuredDirectChannel.class, SecurityPubSubChannel.class, - MessageConsumer.class }) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix b/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix index b76bb8a81a..871fee4ccb 100644 --- a/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix +++ b/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix @@ -72,7 +72,7 @@ node { if (isUnix()) { sh 'nohup ./mvnw spring-boot:run -Dserver.port=8989 &' } else { - bat 'start ./mvnw.cmd spring-boot:run -Dserver.port=8989' + bat 'start mvnw.cmd spring-boot:run -Dserver.port=8989' } } } diff --git a/spring-jenkins-pipeline/src/test/java/com/baeldung/SpringContextTest.java b/spring-jenkins-pipeline/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..932d390201 --- /dev/null +++ b/spring-jenkins-pipeline/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringJenkinsPipelineApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringJenkinsPipelineApplication.class) +@DirtiesContext +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 79ab2f48b8..0000000000 --- a/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.SpringJenkinsPipelineApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringJenkinsPipelineApplication.class) -@DirtiesContext -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-jersey/src/test/java/com/baeldung/SpringContextTest.java b/spring-jersey/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c6b026f466 --- /dev/null +++ b/spring-jersey/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.server.config.RestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RestConfig.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jersey/src/test/java/org/baeldung/SpringContextTest.java b/spring-jersey/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index f480e597b3..0000000000 --- a/spring-jersey/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.server.config.RestConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = RestConfig.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-jinq/pom.xml b/spring-jinq/pom.xml index 991401c4a1..29fc3605d7 100644 --- a/spring-jinq/pom.xml +++ b/spring-jinq/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-boot-1 0.0.1-SNAPSHOT + ../parent-boot-1
diff --git a/spring-jinq/src/test/java/com/baeldung/SpringContextTest.java b/spring-jinq/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..86c529e574 --- /dev/null +++ b/spring-jinq/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.jinq.JinqApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = JinqApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jinq/src/test/java/org/baeldung/SpringContextTest.java b/spring-jinq/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e0da75c7af..0000000000 --- a/spring-jinq/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.jinq.JinqApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = JinqApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml index a0d2625477..9cd9126fac 100644 --- a/spring-jms/pom.xml +++ b/spring-jms/pom.xml @@ -38,7 +38,7 @@ org.springframework.boot spring-boot-starter-test - 1.5.10.RELEASE + ${spring-boot-test.version} test @@ -64,6 +64,7 @@ 4.3.4.RELEASE 5.14.1 + 1.5.10.RELEASE diff --git a/spring-jms/src/test/java/com/baeldung/SpringContextTest.java b/spring-jms/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..000474754f --- /dev/null +++ b/spring-jms/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung; + +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(locations = { "classpath:applicationContext.xml" }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jms/src/test/java/org/baeldung/SpringContextTest.java b/spring-jms/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 11c9d9bca6..0000000000 --- a/spring-jms/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung; - -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(locations = { "classpath:applicationContext.xml" }) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index 620172f2a1..63c6b5c8ee 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -36,6 +36,7 @@ com.h2database h2 + ${h2.version} diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java index b313eafdb9..fde56bebc0 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java @@ -25,7 +25,7 @@ public class KafkaApplication { public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = SpringApplication.run(KafkaApplication.class, args); - + MessageProducer producer = context.getBean(MessageProducer.class); MessageListener listener = context.getBean(MessageListener.class); /* @@ -101,15 +101,17 @@ public class KafkaApplication { private String greetingTopicName; public void sendMessage(String message) { - + ListenableFuture> future = kafkaTemplate.send(topicName, message); - + future.addCallback(new ListenableFutureCallback>() { @Override public void onSuccess(SendResult result) { - System.out.println("Sent message=[" + message + "] with offset=[" + result.getRecordMetadata().offset() + "]"); + System.out.println("Sent message=[" + message + "] with offset=[" + result.getRecordMetadata() + .offset() + "]"); } + @Override public void onFailure(Throwable ex) { System.out.println("Unable to send message=[" + message + "] due to : " + ex.getMessage()); @@ -158,7 +160,7 @@ public class KafkaApplication { latch.countDown(); } - @KafkaListener(topicPartitions = @TopicPartition(topic = "${partitioned.topic.name}", partitions = { "0", "3" })) + @KafkaListener(topicPartitions = @TopicPartition(topic = "${partitioned.topic.name}", partitions = { "0", "3" }), containerFactory = "partitionsKafkaListenerContainerFactory") public void listenToParition(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) { System.out.println("Received Message: " + message + " from partition: " + partition); this.partitionLatch.countDown(); diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java index 933d2353aa..abaa431eec 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java @@ -29,7 +29,7 @@ public class KafkaConsumerConfig { props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); return new DefaultKafkaConsumerFactory<>(props); } - + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory(String groupId) { ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory(groupId)); @@ -50,12 +50,12 @@ public class KafkaConsumerConfig { public ConcurrentKafkaListenerContainerFactory headersKafkaListenerContainerFactory() { return kafkaListenerContainerFactory("headers"); } - + @Bean public ConcurrentKafkaListenerContainerFactory partitionsKafkaListenerContainerFactory() { return kafkaListenerContainerFactory("partitions"); } - + @Bean public ConcurrentKafkaListenerContainerFactory filterKafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory factory = kafkaListenerContainerFactory("filter"); diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaProducerConfig.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaProducerConfig.java index 7e2527b36e..0223bab0fe 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaProducerConfig.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaProducerConfig.java @@ -32,7 +32,7 @@ public class KafkaProducerConfig { public KafkaTemplate kafkaTemplate() { return new KafkaTemplate<>(producerFactory()); } - + @Bean public ProducerFactory greetingProducerFactory() { Map configProps = new HashMap<>(); @@ -41,10 +41,10 @@ public class KafkaProducerConfig { configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(configProps); } - + @Bean public KafkaTemplate greetingKafkaTemplate() { return new KafkaTemplate<>(greetingProducerFactory()); } - + } diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaTopicConfig.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaTopicConfig.java index a3426e78a3..fb60fadde4 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaTopicConfig.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaTopicConfig.java @@ -12,10 +12,10 @@ import org.springframework.kafka.core.KafkaAdmin; @Configuration public class KafkaTopicConfig { - + @Value(value = "${kafka.bootstrapAddress}") private String bootstrapAddress; - + @Value(value = "${message.topic.name}") private String topicName; @@ -27,31 +27,31 @@ public class KafkaTopicConfig { @Value(value = "${greeting.topic.name}") private String greetingTopicName; - + @Bean public KafkaAdmin kafkaAdmin() { Map configs = new HashMap<>(); configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); return new KafkaAdmin(configs); } - + @Bean public NewTopic topic1() { - return new NewTopic(topicName, 1, (short) 1); + return new NewTopic(topicName, 1, (short) 1); } - + @Bean public NewTopic topic2() { - return new NewTopic(partionedTopicName, 6, (short) 1); + return new NewTopic(partionedTopicName, 6, (short) 1); } - + @Bean public NewTopic topic3() { - return new NewTopic(filteredTopicName, 1, (short) 1); + return new NewTopic(filteredTopicName, 1, (short) 1); } - + @Bean public NewTopic topic4() { - return new NewTopic(greetingTopicName, 1, (short) 1); + return new NewTopic(greetingTopicName, 1, (short) 1); } } diff --git a/spring-kafka/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-kafka/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..60262df9d4 --- /dev/null +++ b/spring-kafka/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.kafka.KafkaApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KafkaApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-kafka/src/test/java/com/baeldung/SpringContextManualTest.java b/spring-kafka/src/test/java/com/baeldung/SpringContextManualTest.java new file mode 100644 index 0000000000..0d2c19136f --- /dev/null +++ b/spring-kafka/src/test/java/com/baeldung/SpringContextManualTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.kafka.KafkaApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KafkaApplication.class) +public class SpringContextManualTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-kafka/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-kafka/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index d8fb3131f5..0000000000 --- a/spring-kafka/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.kafka.KafkaApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = KafkaApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-kafka/src/test/java/org/baeldung/SpringContextManualTest.java b/spring-kafka/src/test/java/org/baeldung/SpringContextManualTest.java deleted file mode 100644 index b8195633fd..0000000000 --- a/spring-kafka/src/test/java/org/baeldung/SpringContextManualTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.kafka.KafkaApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = KafkaApplication.class) -public class SpringContextManualTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-katharsis/src/main/java/com/baeldung/Application.java b/spring-katharsis/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..6c4f047b26 --- /dev/null +++ b/spring-katharsis/src/main/java/com/baeldung/Application.java @@ -0,0 +1,18 @@ +package com.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) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-katharsis/src/main/java/com/baeldung/Setup.java b/spring-katharsis/src/main/java/com/baeldung/Setup.java new file mode 100644 index 0000000000..5363dd829a --- /dev/null +++ b/spring-katharsis/src/main/java/com/baeldung/Setup.java @@ -0,0 +1,40 @@ +package com.baeldung; + +import java.util.Arrays; +import java.util.HashSet; + +import javax.annotation.PostConstruct; + +import com.baeldung.persistence.dao.RoleRepository; +import com.baeldung.persistence.dao.UserRepository; +import com.baeldung.persistence.model.Role; +import com.baeldung.persistence.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class Setup { + + @Autowired + private UserRepository userRepository; + + @Autowired + private RoleRepository roleRepository; + + @PostConstruct + private void setupData() { + Role roleUser = new Role("ROLE_USER"); + roleUser = roleRepository.save(roleUser); + Role roleAdmin = new Role("ROLE_ADMIN"); + roleAdmin = roleRepository.save(roleAdmin); + + final User userJohn = new User("john", "john@test.com"); + userJohn.setRoles(new HashSet(Arrays.asList(roleUser, roleAdmin))); + userRepository.save(userJohn); + + final User userTom = new User("tom", "tom@test.com"); + userTom.setRoles(new HashSet(Arrays.asList(roleUser))); + userRepository.save(userTom); + } + +} \ No newline at end of file diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/dao/RoleRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/dao/RoleRepository.java new file mode 100644 index 0000000000..6b7cc0204c --- /dev/null +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/dao/RoleRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.Role; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface RoleRepository extends JpaRepository { + +} diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/dao/UserRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/dao/UserRepository.java new file mode 100644 index 0000000000..89c2f3ec07 --- /dev/null +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/dao/UserRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + +} diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java similarity index 89% rename from spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java rename to spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java index 1998c414bb..c5e6326075 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java @@ -1,12 +1,12 @@ -package org.baeldung.persistence.katharsis; +package com.baeldung.persistence.katharsis; +import com.baeldung.persistence.dao.RoleRepository; 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; +import com.baeldung.persistence.model.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java similarity index 89% rename from spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java rename to spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java index 9b3de31601..616431f3f0 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java @@ -1,11 +1,11 @@ -package org.baeldung.persistence.katharsis; +package com.baeldung.persistence.katharsis; +import com.baeldung.persistence.dao.UserRepository; +import com.baeldung.persistence.model.User; 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; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java similarity index 89% rename from spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java rename to spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java index dbeb769fac..066292c00f 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java @@ -1,5 +1,8 @@ -package org.baeldung.persistence.katharsis; +package com.baeldung.persistence.katharsis; +import com.baeldung.persistence.dao.RoleRepository; +import com.baeldung.persistence.dao.UserRepository; +import com.baeldung.persistence.model.User; import io.katharsis.queryspec.QuerySpec; import io.katharsis.repository.RelationshipRepositoryV2; import io.katharsis.resource.list.ResourceList; @@ -7,10 +10,7 @@ import io.katharsis.resource.list.ResourceList; import java.util.HashSet; import java.util.Set; -import org.baeldung.persistence.dao.RoleRepository; -import org.baeldung.persistence.dao.UserRepository; -import org.baeldung.persistence.model.Role; -import org.baeldung.persistence.model.User; +import com.baeldung.persistence.model.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/model/Role.java b/spring-katharsis/src/main/java/com/baeldung/persistence/model/Role.java new file mode 100644 index 0000000000..2f928993c2 --- /dev/null +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/model/Role.java @@ -0,0 +1,103 @@ +package com.baeldung.persistence.model; + +import io.katharsis.resource.annotations.JsonApiId; +import io.katharsis.resource.annotations.JsonApiRelation; +import io.katharsis.resource.annotations.JsonApiResource; + +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +@JsonApiResource(type = "roles") +public class Role { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @JsonApiId + private Long id; + + @Column(nullable = false, unique = true) + private String name; + + @ManyToMany(mappedBy = "roles") + @JsonApiRelation + private Set users; + + // + public Role() { + super(); + } + + public Role(String name) { + super(); + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + // + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (id == null ? 0 : id.hashCode()); + 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 Role other = (Role) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(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("Role [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/model/User.java b/spring-katharsis/src/main/java/com/baeldung/persistence/model/User.java new file mode 100644 index 0000000000..111435c52e --- /dev/null +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/model/User.java @@ -0,0 +1,112 @@ +package com.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.SerializeType; + +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; + +@Entity +@JsonApiResource(type = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @JsonApiId + private Long id; + + private String username; + + private String email; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) + @JsonApiRelation(serialize=SerializeType.EAGER) + private Set roles; + + public User() { + super(); + } + + public User(String username, String email) { + super(); + this.username = username; + this.email = email; + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(final String email) { + this.email = email; + } + + public Set getRoles() { + return roles; + } + + public void setRoles(Set roles) { + this.roles = roles; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (email == null ? 0 : email.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final User user = (User) obj; + if (!email.equals(user.email)) { + return false; + } + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [id=").append(id).append(", username=").append(username).append(", email=").append(email).append(", roles=").append(roles).append("]"); + return builder.toString(); + } + +} \ No newline at end of file diff --git a/spring-katharsis/src/main/java/org/baeldung/Application.java b/spring-katharsis/src/main/java/org/baeldung/Application.java deleted file mode 100644 index 5ce4ac7e08..0000000000 --- a/spring-katharsis/src/main/java/org/baeldung/Application.java +++ /dev/null @@ -1,18 +0,0 @@ -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) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-katharsis/src/main/java/org/baeldung/Setup.java b/spring-katharsis/src/main/java/org/baeldung/Setup.java deleted file mode 100644 index c9088067eb..0000000000 --- a/spring-katharsis/src/main/java/org/baeldung/Setup.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung; - -import java.util.Arrays; -import java.util.HashSet; - -import javax.annotation.PostConstruct; - -import org.baeldung.persistence.dao.RoleRepository; -import org.baeldung.persistence.dao.UserRepository; -import org.baeldung.persistence.model.Role; -import org.baeldung.persistence.model.User; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class Setup { - - @Autowired - private UserRepository userRepository; - - @Autowired - private RoleRepository roleRepository; - - @PostConstruct - private void setupData() { - Role roleUser = new Role("ROLE_USER"); - roleUser = roleRepository.save(roleUser); - Role roleAdmin = new Role("ROLE_ADMIN"); - roleAdmin = roleRepository.save(roleAdmin); - - final User userJohn = new User("john", "john@test.com"); - userJohn.setRoles(new HashSet(Arrays.asList(roleUser, roleAdmin))); - userRepository.save(userJohn); - - final User userTom = new User("tom", "tom@test.com"); - userTom.setRoles(new HashSet(Arrays.asList(roleUser))); - userRepository.save(userTom); - } - -} \ No newline at end of file diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/dao/RoleRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/dao/RoleRepository.java deleted file mode 100644 index f4542ad097..0000000000 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/dao/RoleRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.Role; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface RoleRepository extends JpaRepository { - -} diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/dao/UserRepository.java deleted file mode 100644 index cfe857ec40..0000000000 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/dao/UserRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.User; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface UserRepository extends JpaRepository { - -} 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 deleted file mode 100644 index f391efd37c..0000000000 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.baeldung.persistence.model; - -import io.katharsis.resource.annotations.JsonApiId; -import io.katharsis.resource.annotations.JsonApiRelation; -import io.katharsis.resource.annotations.JsonApiResource; - -import java.util.Set; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToMany; - -@Entity -@JsonApiResource(type = "roles") -public class Role { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @JsonApiId - private Long id; - - @Column(nullable = false, unique = true) - private String name; - - @ManyToMany(mappedBy = "roles") - @JsonApiRelation - private Set users; - - // - public Role() { - super(); - } - - public Role(String name) { - super(); - this.name = name; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - // - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (id == null ? 0 : id.hashCode()); - 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 Role other = (Role) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(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("Role [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - -} 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 deleted file mode 100644 index 7c55e29599..0000000000 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java +++ /dev/null @@ -1,112 +0,0 @@ -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.SerializeType; - -import java.util.Set; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; - -@Entity -@JsonApiResource(type = "users") -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @JsonApiId - private Long id; - - private String username; - - private String email; - - @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) - @JsonApiRelation(serialize=SerializeType.EAGER) - private Set roles; - - public User() { - super(); - } - - public User(String username, String email) { - super(); - this.username = username; - this.email = email; - } - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getEmail() { - return email; - } - - public void setEmail(final String email) { - this.email = email; - } - - public Set getRoles() { - return roles; - } - - public void setRoles(Set roles) { - this.roles = roles; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (email == null ? 0 : email.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final User user = (User) obj; - if (!email.equals(user.email)) { - return false; - } - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [id=").append(id).append(", username=").append(username).append(", email=").append(email).append(", roles=").append(roles).append("]"); - return builder.toString(); - } - -} \ No newline at end of file diff --git a/spring-katharsis/src/test/java/com/baeldung/SpringContextTest.java b/spring-katharsis/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..13c1c162f1 --- /dev/null +++ b/spring-katharsis/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +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(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-katharsis/src/test/java/org/baeldung/test/JsonApiLiveTest.java b/spring-katharsis/src/test/java/com/baeldung/test/JsonApiLiveTest.java similarity index 94% rename from spring-katharsis/src/test/java/org/baeldung/test/JsonApiLiveTest.java rename to spring-katharsis/src/test/java/com/baeldung/test/JsonApiLiveTest.java index e512202d96..a7c60d4a90 100644 --- a/spring-katharsis/src/test/java/org/baeldung/test/JsonApiLiveTest.java +++ b/spring-katharsis/src/test/java/com/baeldung/test/JsonApiLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.test; +package com.baeldung.test; import static org.junit.Assert.assertEquals; diff --git a/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java b/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 769a436778..0000000000 --- a/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.Application; -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(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index f3e0b04808..5d2cd7c445 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -28,7 +28,7 @@ - 2.21.0 + 2.24.0 diff --git a/spring-mvc-basics-2/README.md b/spring-mvc-basics-2/README.md index 4a5ea24283..673b7b1fef 100644 --- a/spring-mvc-basics-2/README.md +++ b/spring-mvc-basics-2/README.md @@ -1,14 +1,16 @@ -## Spring MVC Basics +## Spring MVC Basics 2 -This module contains articles about the basics of Spring MVC. Articles about more specific areas of Spring MVC have -their own module. +This module contains articles about Spring MVC -### The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles: -- [Quick Guide to Spring Controllers](http://www.baeldung.com/spring-controllers) -- [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) -- [Model, ModelMap, and ModelView in Spring MVC](http://www.baeldung.com/spring-mvc-model-model-map-model-view) -- [Spring Web Contexts](http://www.baeldung.com/spring-web-contexts) -- [[<-- Prev]](/spring-mvc-basics) \ No newline at end of file +## Relevant articles: +- [HandlerAdapters in Spring MVC](https://www.baeldung.com/spring-mvc-handler-adapters) +- [Template Engines for Spring](https://www.baeldung.com/spring-template-engines) +- [Spring 5 and Servlet 4 – The PushBuilder](https://www.baeldung.com/spring-5-push) +- [Servlet Redirect vs Forward](https://www.baeldung.com/servlet-redirect-forward) +- [Apache Tiles Integration with Spring MVC](https://www.baeldung.com/spring-mvc-apache-tiles) +- [Guide to Spring Email](https://www.baeldung.com/spring-email) +- [Using ThymeLeaf and FreeMarker Emails Templates with Spring](https://www.baeldung.com/spring-email-templates) +- [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405) +- [Spring @RequestParam Annotation](https://www.baeldung.com/spring-request-param) +- More articles: [[more -->]](/spring-mvc-basics-3) +- More articles: [[<-- prev]](/spring-mvc-basics) diff --git a/spring-mvc-basics-2/pom.xml b/spring-mvc-basics-2/pom.xml index 8e36eb38d8..4c3041a209 100644 --- a/spring-mvc-basics-2/pom.xml +++ b/spring-mvc-basics-2/pom.xml @@ -1,37 +1,185 @@ - + 4.0.0 spring-mvc-basics-2 + 0.0.1-SNAPSHOT spring-mvc-basics-2 war com.baeldung - parent-boot-2 + parent-spring-5 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-spring-5 - com.fasterxml.jackson.core - jackson-databind + org.springframework + spring-oxm + ${spring.version} - org.springframework - spring-web + com.sun.mail + javax.mail + ${javax.mail.version} javax.servlet javax.servlet-api - provided + ${javax.servlet-api.version} + + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax.servlet.jsp-api.version} + + + javax.servlet + jstl + ${jstl.version} + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} org.springframework spring-webmvc + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + + + + org.freemarker + freemarker + ${freemarker.version} + + + org.springframework + spring-context-support + ${spring.version} + + + + + org.codehaus.groovy + groovy-templates + ${groovy.version} + + + + + de.neuland-bfi + spring-jade4j + ${jade.version} + + + + org.apache.tiles + tiles-jsp + ${apache-tiles.version} + + + + + org.springframework + spring-test + ${spring.version} + test + + + com.rometools + rome + ${rome.version} + + + com.thoughtworks.xstream + xstream + ${xstream.version} + + + com.github.scribejava + scribejava-apis + ${scribejava.version} + + + org.json + json + ${json.version} + + + org.apache.maven.surefire + surefire-logger-api + ${maven-surefire-plugin.version} + + test + true - \ No newline at end of file + + spring-mvc-basics-2 + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + springMvcSimple + false + ${deploy-path} + + + + + + + + 1.8 + 1.8 + 2.21.0 + 2.3.2-b02 + 4.0.0 + 6.0.10.Final + enter-location-of-server + 1.3.2 + 3.0.7.RELEASE + 2.4.12 + 2.3.27-incubating + 1.2.5 + 1.9.0 + 1.4.9 + 5.1.0 + 20180130 + 3.0.8 + 1.6.1 + + + diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java new file mode 100644 index 0000000000..e70e801577 --- /dev/null +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java @@ -0,0 +1,65 @@ +package com.baeldung.spring.configuration; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +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.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.WebMvcConfigurer; +import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +import com.baeldung.spring.controller.rss.ArticleRssFeedViewResolver; +import com.baeldung.spring.controller.rss.JsonChannelHttpMessageConverter; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator", "com.baeldung.spring.mail", "com.baeldung.spring.service" }) +public class ApplicationConfiguration implements WebMvcConfigurer { + + @Override + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Bean + public ContentNegotiatingViewResolver viewResolver(ContentNegotiationManager cnManager) { + ContentNegotiatingViewResolver cnvResolver = new ContentNegotiatingViewResolver(); + cnvResolver.setContentNegotiationManager(cnManager); + List resolvers = new ArrayList<>(); + + InternalResourceViewResolver bean = new InternalResourceViewResolver("/WEB-INF/views/",".jsp"); + ArticleRssFeedViewResolver articleRssFeedViewResolver = new ArticleRssFeedViewResolver(); + + resolvers.add(bean); + resolvers.add(articleRssFeedViewResolver); + + cnvResolver.setViewResolvers(resolvers); + return cnvResolver; + } + + @Bean + public MultipartResolver multipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(5242880); + return multipartResolver; + } + + @Override + public void configureMessageConverters(List> converters) { + converters.add(new StringHttpMessageConverter()); + converters.add(new RssChannelHttpMessageConverter()); + converters.add(new JsonChannelHttpMessageConverter()); + } + +} diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/EmailConfiguration.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/EmailConfiguration.java new file mode 100644 index 0000000000..1bbbc51304 --- /dev/null +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/EmailConfiguration.java @@ -0,0 +1,89 @@ +package com.baeldung.spring.configuration; + +import java.util.Properties; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; +import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; + +@Configuration +@ComponentScan(basePackages = { "com.baeldung.spring.mail" }) +public class EmailConfiguration { + + @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", "false"); + props.put("mail.debug", "true"); + + return mailSender; + } + + @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 SpringTemplateEngine thymeleafTemplateEngine() { + SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(thymeleafTemplateResolver()); + templateEngine.setTemplateEngineMessageSource(emailMessageSource()); + return templateEngine; + } + + @Bean + public SpringResourceTemplateResolver thymeleafTemplateResolver() { + SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/views/mail/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML"); + templateResolver.setCharacterEncoding("UTF-8"); + return templateResolver; + } + + @Bean + public FreeMarkerConfigurer freemarkerConfig() { + FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); + freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/mail"); + return freeMarkerConfigurer; + } + + @Bean + public FreeMarkerViewResolver freemarkerViewResolver() { + FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); + resolver.setCache(true); + resolver.setPrefix(""); + resolver.setSuffix(".ftl"); + return resolver; + } + + + @Bean + public ResourceBundleMessageSource emailMessageSource() { + final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("/mailMessages"); + return messageSource; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/PushConfiguration.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/PushConfiguration.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/PushConfiguration.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/PushConfiguration.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/WebInitializer.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/WebInitializer.java new file mode 100644 index 0000000000..4d43549440 --- /dev/null +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/WebInitializer.java @@ -0,0 +1,36 @@ +package com.baeldung.spring.configuration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class WebInitializer implements WebApplicationInitializer { + + public void onStartup(ServletContext container) throws ServletException { + + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(ApplicationConfiguration.class); + // ctx.register(ThymeleafConfiguration.class); + // ctx.register(FreemarkerConfiguration.class); + // ctx.register(GroovyConfiguration.class); + // ctx.register(JadeTemplateConfiguration.class); + // ctx.register(PushConfiguration.class); + ctx.register(EmailConfiguration.class); + // ctx.setServletContext(container); + + //ctx.register(TilesApplicationConfiguration.class); + + // Manage the lifecycle of the root application context + container.addListener(new ContextLoaderListener(ctx)); + + ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx)); + + servlet.setLoadOnStartup(1); + servlet.addMapping("/"); + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/AnnotationMethodHandlerAdapterExample.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/AnnotationMethodHandlerAdapterExample.java similarity index 97% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/AnnotationMethodHandlerAdapterExample.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/AnnotationMethodHandlerAdapterExample.java index 89f5b2501b..30bda5c582 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/AnnotationMethodHandlerAdapterExample.java +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/AnnotationMethodHandlerAdapterExample.java @@ -1,15 +1,15 @@ -package com.baeldung.spring.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.servlet.ModelAndView; - -@Controller -public class AnnotationMethodHandlerAdapterExample { - @RequestMapping("/annotedName") - public ModelAndView getEmployeeName() { - ModelAndView model = new ModelAndView("Greeting"); - model.addObject("message", "Dinesh"); - return model; - } +package com.baeldung.spring.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class AnnotationMethodHandlerAdapterExample { + @RequestMapping("/annotedName") + public ModelAndView getEmployeeName() { + ModelAndView model = new ModelAndView("Greeting"); + model.addObject("message", "Dinesh"); + return model; + } } \ No newline at end of file diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/CustomerController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/CustomerController.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/CustomerController.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/CustomerController.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/EmployeeController.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/EmployeeController.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/EmployeeController.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/FileUploadController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/FileUploadController.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/FileUploadController.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/FileUploadController.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/MailController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/MailController.java new file mode 100644 index 0000000000..b6e19a4c39 --- /dev/null +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/MailController.java @@ -0,0 +1,176 @@ +package com.baeldung.spring.controller; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.mail.MessagingException; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.Errors; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.baeldung.spring.domain.MailObject; +import com.baeldung.spring.mail.EmailService; + +import freemarker.template.TemplateException; + +@Controller +@RequestMapping("/mail") +public class MailController { + + @Autowired + public EmailService emailService; + + @Value("${attachment.invoice}") + private String attachmentPath; + + private static final Map> labels; + + static { + labels = new HashMap<>(); + + //Simple email + Map props = new HashMap<>(); + props.put("headerText", "Send Simple Email"); + props.put("messageLabel", "Message"); + props.put("additionalInfo", ""); + labels.put("send", props); + + //Email with template + props = new HashMap<>(); + props.put("headerText", "Send Email Using Text Template"); + props.put("messageLabel", "Template Parameter"); + props.put("additionalInfo", + "The parameter value will be added to the following message template:
" + + "This is the test email template for your email:
'Template Parameter'
" + ); + labels.put("sendTemplate", props); + + //Email with attachment + props = new HashMap<>(); + props.put("headerText", "Send Email With Attachment"); + props.put("messageLabel", "Message"); + 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, + HttpServletRequest request) { + String action = request.getRequestURL().substring( + request.getRequestURL().lastIndexOf("/") + 1 + ); + Map props = labels.get(action); + Set keys = props.keySet(); + Iterator iterator = keys.iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + model.addAttribute(key, props.get(key)); + } + + model.addAttribute("mailObject", new MailObject()); + return "mail/send"; + } + + + @RequestMapping(value = "/send", method = RequestMethod.POST) + public String createMail(Model model, + @ModelAttribute("mailObject") @Valid MailObject mailObject, + Errors errors) { + if (errors.hasErrors()) { + return "mail/send"; + } + emailService.sendSimpleMessage(mailObject.getTo(), + mailObject.getSubject(), mailObject.getText()); + + return "emails"; + } + + @RequestMapping(value = "/sendTemplate", method = RequestMethod.POST) + public String createMailWithTemplate(Model model, + @ModelAttribute("mailObject") @Valid MailObject mailObject, + Errors errors) { + if (errors.hasErrors()) { + return "mail/send"; + } + emailService.sendSimpleMessageUsingTemplate(mailObject.getTo(), + mailObject.getSubject(), + mailObject.getText()); + + return "redirect:/mail"; + } + + @RequestMapping(value = "/sendAttachment", method = RequestMethod.POST) + public String createMailWithAttachment(Model model, + @ModelAttribute("mailObject") @Valid MailObject mailObject, + Errors errors) { + if (errors.hasErrors()) { + return "mail/send"; + } + emailService.sendMessageWithAttachment( + mailObject.getTo(), + mailObject.getSubject(), + mailObject.getText(), + attachmentPath + ); + + return "redirect:/mail"; + } + + + @RequestMapping(value = {"/sendHtml"}, method = RequestMethod.GET) + public String getHtmlMailView(Model model, + HttpServletRequest request) { + + Map templateEngines = new HashMap<>(); + templateEngines.put("Thymeleaf", "Thymeleaf"); + templateEngines.put("Freemarker", "Freemarker"); + model.addAttribute("mailObject", new MailObject()); + model.addAttribute("templateEngines", templateEngines); + return "mail/sendHtml"; + } + + @RequestMapping(value = "/sendHtml", method = RequestMethod.POST) + public String createHtmlMail(Model model, + @ModelAttribute("mailObject") @Valid MailObject mailObject, + Errors errors) throws IOException, MessagingException, TemplateException { + if (errors.hasErrors()) { + return "mail/send"; + } + + Map templateModel = new HashMap<>(); + templateModel.put("recipientName", mailObject.getRecipientName()); + templateModel.put("text", mailObject.getText()); + templateModel.put("senderName", mailObject.getSenderName()); + + if (mailObject.getTemplateEngine().equalsIgnoreCase("thymeleaf")) { + emailService.sendMessageUsingThymeleafTemplate( + mailObject.getTo(), + mailObject.getSubject(), + templateModel); + } else { + emailService.sendMessageUsingFreemarkerTemplate( + mailObject.getTo(), + mailObject.getSubject(), + templateModel); + } + + return "redirect:/mail"; + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestMappingHandlerAdapterExample.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/RequestMappingHandlerAdapterExample.java similarity index 97% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestMappingHandlerAdapterExample.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/RequestMappingHandlerAdapterExample.java index 754bea79f1..628f853208 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestMappingHandlerAdapterExample.java +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/RequestMappingHandlerAdapterExample.java @@ -1,15 +1,15 @@ -package com.baeldung.spring.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.servlet.ModelAndView; - -@Controller -public class RequestMappingHandlerAdapterExample { - @RequestMapping("/requestName") - public ModelAndView getEmployeeName() { - ModelAndView model = new ModelAndView("Greeting"); - model.addObject("message", "Madhwal"); - return model; - } +package com.baeldung.spring.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class RequestMappingHandlerAdapterExample { + @RequestMapping("/requestName") + public ModelAndView getEmployeeName() { + ModelAndView model = new ModelAndView("Greeting"); + model.addObject("message", "Madhwal"); + return model; + } } \ No newline at end of file diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestMethodController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/RequestMethodController.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestMethodController.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/RequestMethodController.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/SimpleControllerHandlerAdapterExample.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/SimpleControllerHandlerAdapterExample.java similarity index 97% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/SimpleControllerHandlerAdapterExample.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/SimpleControllerHandlerAdapterExample.java index 17c4ab689e..d3800d4e1c 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/SimpleControllerHandlerAdapterExample.java +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/SimpleControllerHandlerAdapterExample.java @@ -1,16 +1,16 @@ -package com.baeldung.spring.controller; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.mvc.AbstractController; - -public class SimpleControllerHandlerAdapterExample extends AbstractController { - @Override - protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { - ModelAndView model = new ModelAndView("Greeting"); - model.addObject("message", "Dinesh Madhwal"); - return model; - } +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class SimpleControllerHandlerAdapterExample extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + ModelAndView model = new ModelAndView("Greeting"); + model.addObject("message", "Dinesh Madhwal"); + return model; + } } \ No newline at end of file diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/UserController.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/UserController.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/Article.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/rss/Article.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/Article.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/rss/Article.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleFeedView.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/rss/ArticleFeedView.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleFeedView.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/rss/ArticleFeedView.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleRssController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/rss/ArticleRssController.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleRssController.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/rss/ArticleRssController.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleRssFeedViewResolver.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/rss/ArticleRssFeedViewResolver.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleRssFeedViewResolver.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/rss/ArticleRssFeedViewResolver.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/JsonChannelHttpMessageConverter.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/rss/JsonChannelHttpMessageConverter.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/JsonChannelHttpMessageConverter.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/rss/JsonChannelHttpMessageConverter.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/GithubController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/scribe/GithubController.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/GithubController.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/scribe/GithubController.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/TwitterController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/scribe/TwitterController.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/TwitterController.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/scribe/TwitterController.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/Customer.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/Customer.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/domain/Customer.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/Customer.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/Employee.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/Employee.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/domain/Employee.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/Employee.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/MailObject.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/MailObject.java new file mode 100644 index 0000000000..d425ca9a26 --- /dev/null +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/MailObject.java @@ -0,0 +1,70 @@ +package com.baeldung.spring.domain; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +/** + * Created by Olga on 7/20/2016. + */ +public class MailObject { + @Email + @NotNull + @Size(min = 1, message = "Please, set an email address to send the message to it") + private String to; + private String recipientName; + private String subject; + private String text; + private String senderName; + private String templateEngine; + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getRecipientName() { + return recipientName; + } + + public void setRecipientName(String recipientName) { + this.recipientName = recipientName; + } + + public String getSenderName() { + return senderName; + } + + public void setSenderName(String senderName) { + this.senderName = senderName; + } + + public String getTemplateEngine() { + return templateEngine; + } + + public void setTemplateEngine(String templateEngine) { + this.templateEngine = templateEngine; + } + + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/User.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/User.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/exception/InvalidRequestException.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/exception/InvalidRequestException.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/exception/InvalidRequestException.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/exception/InvalidRequestException.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/interceptor/FileUploadExceptionAdvice.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/interceptor/FileUploadExceptionAdvice.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/interceptor/FileUploadExceptionAdvice.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/interceptor/FileUploadExceptionAdvice.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailService.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailService.java new file mode 100644 index 0000000000..b7d5be09c8 --- /dev/null +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailService.java @@ -0,0 +1,34 @@ +package com.baeldung.spring.mail; + +import java.io.IOException; +import java.util.Map; + +import javax.mail.MessagingException; + +import freemarker.template.TemplateException; + +/** + * Created by Olga on 8/22/2016. + */ +public interface EmailService { + void sendSimpleMessage(String to, + String subject, + String text); + void sendSimpleMessageUsingTemplate(String to, + String subject, + String ...templateModel); + void sendMessageWithAttachment(String to, + String subject, + String text, + String pathToAttachment); + + void sendMessageUsingThymeleafTemplate(String to, + String subject, + Map templateModel) + throws IOException, MessagingException; + + void sendMessageUsingFreemarkerTemplate(String to, + String subject, + Map templateModel) + throws IOException, TemplateException, MessagingException; +} diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java new file mode 100644 index 0000000000..0592415ab5 --- /dev/null +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java @@ -0,0 +1,129 @@ +package com.baeldung.spring.mail; + +import java.io.File; +import java.io.IOException; +import java.util.Map; + +import javax.mail.MessagingException; +import javax.mail.internet.MimeMessage; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.mail.MailException; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.stereotype.Service; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; +import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; +import org.thymeleaf.context.Context; +import org.thymeleaf.spring4.SpringTemplateEngine; + +import freemarker.template.Template; +import freemarker.template.TemplateException; + +/** + * Created by Olga on 7/15/2016. + */ +@Service("EmailService") +public class EmailServiceImpl implements EmailService { + + @Autowired + public JavaMailSender emailSender; + + @Autowired + public SimpleMailMessage template; + + @Autowired + private SpringTemplateEngine thymeleafTemplateEngine; + + @Autowired + private FreeMarkerConfigurer freemarkerConfigurer; + + @Value("classpath:/mail-logo.png") + Resource resourceFile; + + public void sendSimpleMessage(String to, String subject, String text) { + try { + SimpleMailMessage message = new SimpleMailMessage(); + message.setTo(to); + message.setSubject(subject); + message.setText(text); + + emailSender.send(message); + } catch (MailException exception) { + exception.printStackTrace(); + } + } + + @Override + public void sendSimpleMessageUsingTemplate(String to, + String subject, + String ...templateModel) { + String text = String.format(template.getText(), templateModel); + sendSimpleMessage(to, subject, text); + } + + @Override + public void sendMessageWithAttachment(String to, + String subject, + String text, + String pathToAttachment) { + try { + MimeMessage message = emailSender.createMimeMessage(); + // pass 'true' to the constructor to create a multipart message + MimeMessageHelper helper = new MimeMessageHelper(message, true); + + helper.setTo(to); + helper.setSubject(subject); + helper.setText(text); + + FileSystemResource file = new FileSystemResource(new File(pathToAttachment)); + helper.addAttachment("Invoice", file); + + emailSender.send(message); + } catch (MessagingException e) { + e.printStackTrace(); + } + } + + + @Override + public void sendMessageUsingThymeleafTemplate( + String to, String subject, Map templateModel) + throws MessagingException { + + Context thymeleafContext = new Context(); + thymeleafContext.setVariables(templateModel); + + String htmlBody = thymeleafTemplateEngine.process("template-thymeleaf.html", thymeleafContext); + + sendHtmlMessage(to, subject, htmlBody); + } + + @Override + public void sendMessageUsingFreemarkerTemplate( + String to, String subject, Map templateModel) + throws IOException, TemplateException, MessagingException { + + Template freemarkerTemplate = freemarkerConfigurer.createConfiguration().getTemplate("template-freemarker.ftl"); + String htmlBody = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerTemplate, templateModel); + + sendHtmlMessage(to, subject, htmlBody); + } + + private void sendHtmlMessage(String to, String subject, String htmlBody) throws MessagingException { + + MimeMessage message = emailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); + helper.setTo(to); + helper.setSubject(subject); + helper.setText(htmlBody, true); + helper.addInline("attachment.png", resourceFile); + emailSender.send(message); + + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/push/controller/PushController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/push/controller/PushController.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/push/controller/PushController.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/push/controller/PushController.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/requestparam/RequestParamController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/requestparam/RequestParamController.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/requestparam/RequestParamController.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/requestparam/RequestParamController.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeService.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/service/EmployeeService.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeService.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/service/EmployeeService.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeServiceImpl.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/service/EmployeeServiceImpl.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeServiceImpl.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/service/EmployeeServiceImpl.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/servlets/ForwardedServlet.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/servlets/ForwardedServlet.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/servlets/ForwardedServlet.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/servlets/ForwardedServlet.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/servlets/HelloServlet.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/servlets/HelloServlet.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/servlets/HelloServlet.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/servlets/HelloServlet.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/servlets/RedirectedServlet.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/servlets/RedirectedServlet.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/servlets/RedirectedServlet.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/servlets/RedirectedServlet.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/servlets/WelcomeServlet.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/servlets/WelcomeServlet.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/servlets/WelcomeServlet.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/servlets/WelcomeServlet.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/validator/CustomerValidator.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/validator/CustomerValidator.java similarity index 100% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/validator/CustomerValidator.java rename to spring-mvc-basics-2/src/main/java/com/baeldung/spring/validator/CustomerValidator.java diff --git a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/config/WebConfig.java b/spring-mvc-basics-2/src/main/java/org/baeldung/controller/config/WebConfig.java deleted file mode 100644 index 018c530f18..0000000000 --- a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/config/WebConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.baeldung.controller.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.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = { "org.baeldung.controller.controller", "com.baeldung.controller", "org.baeldung.controller.config" }) -public class WebConfig implements WebMvcConfigurer { - @Override - public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setPrefix("/WEB-INF/"); - bean.setSuffix(".jsp"); - return bean; - } -} \ No newline at end of file diff --git a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/student/Student.java b/spring-mvc-basics-2/src/main/java/org/baeldung/controller/student/Student.java deleted file mode 100644 index 5f49e5ceb9..0000000000 --- a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/student/Student.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.baeldung.controller.student; - -public class Student { - private String name; - - private int id; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - @Override - public int hashCode() { - return this.id; - } - - @Override - public boolean equals(Object obj) { - return this.name.equals(((Student) obj).getName()); - } -} \ No newline at end of file diff --git a/spring-mvc-basics-2/src/main/resources/application.properties b/spring-mvc-basics-2/src/main/resources/application.properties index 709574239b..9a804c07d8 100644 --- a/spring-mvc-basics-2/src/main/resources/application.properties +++ b/spring-mvc-basics-2/src/main/resources/application.properties @@ -1 +1,22 @@ -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +#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/webapp/resources/logo.png b/spring-mvc-basics-2/src/main/resources/mail-logo.png similarity index 100% rename from spring-mvc-simple/src/main/webapp/resources/logo.png rename to spring-mvc-basics-2/src/main/resources/mail-logo.png diff --git a/spring-mvc-basics-2/src/main/resources/mailMessages.properties b/spring-mvc-basics-2/src/main/resources/mailMessages.properties new file mode 100644 index 0000000000..46f7a80ed3 --- /dev/null +++ b/spring-mvc-basics-2/src/main/resources/mailMessages.properties @@ -0,0 +1,5 @@ +greetings=Hi {0}, +subscriptions=Please find below your current subscriptions to our forum: +regards=Regards, +unsubscribe=Unsubscribe from these emails here +signature={0} at Baeldung \ No newline at end of file diff --git a/spring-mvc-basics-2/src/main/resources/mailMessages_fr_FR.properties b/spring-mvc-basics-2/src/main/resources/mailMessages_fr_FR.properties new file mode 100644 index 0000000000..6f300a9ab7 --- /dev/null +++ b/spring-mvc-basics-2/src/main/resources/mailMessages_fr_FR.properties @@ -0,0 +1,5 @@ +greetings=Bonjour {0}, +subscriptions=Voici vos différentes souscriptions sur notre forum : +regards=Cordialement, +unsubscribe=Se désinscrire de ces emails ici +signature={0} à Baeldung \ No newline at end of file diff --git a/spring-mvc-basics-2/src/main/resources/test-mvc.xml b/spring-mvc-basics-2/src/main/resources/test-mvc.xml deleted file mode 100644 index 8013170379..0000000000 --- a/spring-mvc-basics-2/src/main/resources/test-mvc.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - /WEB-INF/ - - - .jsp - - - \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/Greeting.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/Greeting.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/Greeting.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/Greeting.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/Greeting.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/Greeting.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/Greeting.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/Greeting.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/customerHome.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/customerHome.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/customerHome.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/customerHome.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/customerView.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/customerView.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/customerView.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/customerView.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/demo.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/demo.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/demo.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/demo.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/emails.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/emails.jsp similarity index 82% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/emails.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/emails.jsp index 63351bbf3a..dafa71cbb0 100644 --- a/spring-mvc-simple/src/main/webapp/WEB-INF/views/emails.jsp +++ b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/emails.jsp @@ -26,7 +26,7 @@ - + @@ -34,6 +34,11 @@ + + + + + diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/employeeHome.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/employeeHome.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/employeeHome.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/employeeHome.jsp diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/employeeView.jsp similarity index 100% rename from spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/employeeView.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/error.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/error.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/error.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/error.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/file.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/file.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/file.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/file.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/mail/send.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/send.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/mail/send.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/send.jsp diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/sendHtml.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/sendHtml.jsp new file mode 100644 index 0000000000..f91a8826d1 --- /dev/null +++ b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/sendHtml.jsp @@ -0,0 +1,73 @@ +<%-- + User: Benjamin CAURE + Date: 4/14/2020 +--%> +<%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" language="java" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> + + + Send HTML Email + + +
+

Send Email Using Text Template

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Enter email address
+ +
+ Enter the recipient name
+ +
+ Enter the subject
+ +
+ +
+ Enter the sender name
+ +
+ Select the template engine
+ +
+ +
+
+
+
+
+ + diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-freemarker.ftl b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-freemarker.ftl new file mode 100644 index 0000000000..066fc0302c --- /dev/null +++ b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-freemarker.ftl @@ -0,0 +1,15 @@ + + + + + + +

Hi ${recipientName}

+

${text}

+

Regards,

+

+ ${senderName} at Baeldung
+ +

+ + diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-thymeleaf.html b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-thymeleaf.html new file mode 100644 index 0000000000..b255b5dee5 --- /dev/null +++ b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-thymeleaf.html @@ -0,0 +1,15 @@ + + + + + + +

+

+

+

+
+ +

+ + diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/home.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/pages/home.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/home.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/pages/home.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/springmvc.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/pages/springmvc.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/springmvc.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/pages/springmvc.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/registration-freemarker.ftl similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/registration-freemarker.ftl diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/registration-groovy.tpl similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/registration-groovy.tpl diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/registration-jade.jade similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/registration-jade.jade diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/registration-thymeleaf.html similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/registration-thymeleaf.html diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/registration.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/registration.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/tiles.xml b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/tiles/tiles.xml similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/tiles.xml rename to spring-mvc-basics-2/src/main/webapp/WEB-INF/views/tiles/tiles.xml diff --git a/spring-mvc-basics-2/src/main/webapp/resources/logo.png b/spring-mvc-basics-2/src/main/webapp/resources/logo.png new file mode 100644 index 0000000000..edb83efbe3 Binary files /dev/null and b/spring-mvc-basics-2/src/main/webapp/resources/logo.png differ diff --git a/spring-mvc-simple/src/main/webapp/static/css/app.css b/spring-mvc-basics-2/src/main/webapp/static/css/app.css similarity index 100% rename from spring-mvc-simple/src/main/webapp/static/css/app.css rename to spring-mvc-basics-2/src/main/webapp/static/css/app.css diff --git a/spring-mvc-basics-2/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-basics-2/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5c276254d3 --- /dev/null +++ b/spring-mvc-basics-2/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,22 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.spring.configuration.ApplicationConfiguration; +import com.baeldung.spring.configuration.EmailConfiguration; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes={ApplicationConfiguration.class, EmailConfiguration.class}) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} + diff --git a/spring-mvc-simple/src/test/java/com/baeldung/controller/push/PushControllerIntegrationTest.java b/spring-mvc-basics-2/src/test/java/com/baeldung/controller/push/PushControllerIntegrationTest.java similarity index 100% rename from spring-mvc-simple/src/test/java/com/baeldung/controller/push/PushControllerIntegrationTest.java rename to spring-mvc-basics-2/src/test/java/com/baeldung/controller/push/PushControllerIntegrationTest.java diff --git a/spring-mvc-simple/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java b/spring-mvc-basics-2/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java similarity index 92% rename from spring-mvc-simple/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java rename to spring-mvc-basics-2/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java index fe7aeeb570..2ed70489c0 100644 --- a/spring-mvc-simple/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java +++ b/spring-mvc-basics-2/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java @@ -1,6 +1,8 @@ package com.baeldung.controller.rss; import com.baeldung.spring.configuration.ApplicationConfiguration; +import com.baeldung.spring.configuration.EmailConfiguration; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -13,7 +15,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@SpringJUnitWebConfig(ApplicationConfiguration.class) +@SpringJUnitWebConfig(classes={ApplicationConfiguration.class, EmailConfiguration.class}) public class ArticleRssIntegrationTest { public static final String APPLICATION_RSS_XML = "application/rss+xml"; public static final String APPLICATION_RSS_JSON = "application/rss+json"; diff --git a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletIntegrationTest.java b/spring-mvc-basics-2/src/test/java/com/baeldung/spring/servlets/HelloServletIntegrationTest.java similarity index 100% rename from spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletIntegrationTest.java rename to spring-mvc-basics-2/src/test/java/com/baeldung/spring/servlets/HelloServletIntegrationTest.java diff --git a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletIntegrationTest.java b/spring-mvc-basics-2/src/test/java/com/baeldung/spring/servlets/WelcomeServletIntegrationTest.java similarity index 100% rename from spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletIntegrationTest.java rename to spring-mvc-basics-2/src/test/java/com/baeldung/spring/servlets/WelcomeServletIntegrationTest.java diff --git a/spring-mvc-basics-2/src/test/resources/test-mvc.xml b/spring-mvc-basics-2/src/test/resources/test-mvc.xml deleted file mode 100644 index 15f950ed4f..0000000000 --- a/spring-mvc-basics-2/src/test/resources/test-mvc.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - /WEB-INF/ - - - .jsp - - - \ No newline at end of file diff --git a/spring-mvc-basics-3/README.md b/spring-mvc-basics-3/README.md new file mode 100644 index 0000000000..074c60152c --- /dev/null +++ b/spring-mvc-basics-3/README.md @@ -0,0 +1,16 @@ +## Spring MVC Basics 3 + +This module contains articles about Spring MVC + +## Relevant articles: +- [How to Read HTTP Headers in Spring REST Controllers](https://www.baeldung.com/spring-rest-http-headers) +- [A Custom Data Binder in Spring MVC](https://www.baeldung.com/spring-mvc-custom-data-binder) +- [Validating Lists in a Spring Controller](https://www.baeldung.com/spring-validate-list-controller) +- [Spring Validation Message Interpolation](https://www.baeldung.com/spring-validation-message-interpolation) +- [Using a Slash Character in Spring URLs](https://www.baeldung.com/spring-slash-character-in-url) +- [Using Enums as Request Parameters in Spring](https://www.baeldung.com/spring-enum-request-param) +- [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter) +- [Guide to Flash Attributes in a Spring Web Application](https://www.baeldung.com/spring-web-flash-attributes) +- [Handling URL Encoded Form Data in Spring REST](https://www.baeldung.com/spring-url-encoded-form-data) +- [Reading HttpServletRequest Multiple Times in Spring](https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times) +- More articles: [[<-- prev]](/spring-mvc-basics-2)[[more -->]](/spring-mvc-basics-4) diff --git a/spring-mvc-basics-3/pom.xml b/spring-mvc-basics-3/pom.xml new file mode 100644 index 0000000000..1dea8f9e93 --- /dev/null +++ b/spring-mvc-basics-3/pom.xml @@ -0,0 +1,151 @@ + + + 4.0.0 + spring-mvc-basics-3 + spring-mvc-basics-3 + war + Demo project for Spring Boot + + + com.baeldung + parent-boot-2 + 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-thymeleaf + provided + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + 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.springframework.cloud + spring-cloud-context + ${springcloud.version} + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + + + ${project.artifactId} + + + src/main/resources + true + + **/conf.properties + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + + com.baeldung.boot.Application + 3.1.1 + 3.3.7-1 + 2.2 + 18.0 + 3.1.7 + 2.0.2.RELEASE + 4.5.8 + + + diff --git a/spring-mvc-basics-3/src/main/java/com/baeldung/boot/Application.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/Application.java new file mode 100644 index 0000000000..cb0d0c1532 --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/Application.java @@ -0,0 +1,14 @@ +package com.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-mvc-basics-3/src/main/java/com/baeldung/boot/config/WebConfig.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/config/WebConfig.java new file mode 100644 index 0000000000..44a5e823f7 --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/config/WebConfig.java @@ -0,0 +1,30 @@ +package com.baeldung.boot.config; + +import java.util.List; + +import com.baeldung.boot.converter.GenericBigDecimalConverter; +import com.baeldung.boot.converter.StringToAbstractEntityConverterFactory; +import com.baeldung.boot.converter.StringToEmployeeConverter; +import com.baeldung.boot.converter.StringToEnumConverter; +import com.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; + +@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.addConverter(new StringToEnumConverter()); + registry.addConverterFactory(new StringToAbstractEntityConverterFactory()); + registry.addConverter(new GenericBigDecimalConverter()); + } +} diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/controller/GenericEntityController.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/controller/GenericEntityController.java similarity index 91% rename from spring-mvc-simple-2/src/main/java/org/baeldung/boot/controller/GenericEntityController.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/boot/controller/GenericEntityController.java index 17457f4c20..39fd5af318 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/controller/GenericEntityController.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/controller/GenericEntityController.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.controller; +package com.baeldung.boot.controller; -import org.baeldung.boot.domain.GenericEntity; -import org.baeldung.boot.domain.Modes; -import org.baeldung.boot.web.resolver.Version; +import com.baeldung.boot.domain.GenericEntity; +import com.baeldung.boot.domain.Modes; +import com.baeldung.boot.web.resolver.Version; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java new file mode 100644 index 0000000000..0040327e00 --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java @@ -0,0 +1,34 @@ +package com.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-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToAbstractEntityConverterFactory.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToAbstractEntityConverterFactory.java similarity index 87% rename from spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToAbstractEntityConverterFactory.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToAbstractEntityConverterFactory.java index 9e7fd8f858..bfeb03f748 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToAbstractEntityConverterFactory.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToAbstractEntityConverterFactory.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.converter; +package com.baeldung.boot.converter; -import org.baeldung.boot.domain.AbstractEntity; -import org.baeldung.boot.domain.Bar; -import org.baeldung.boot.domain.Foo; +import com.baeldung.boot.domain.AbstractEntity; +import com.baeldung.boot.domain.Bar; +import com.baeldung.boot.domain.Foo; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; diff --git a/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java new file mode 100644 index 0000000000..678ae49195 --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java @@ -0,0 +1,13 @@ +package com.baeldung.boot.converter; + +import com.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-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToEnumConverter.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToEnumConverter.java similarity index 75% rename from spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToEnumConverter.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToEnumConverter.java index 498b44abec..320c26cba0 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToEnumConverter.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToEnumConverter.java @@ -1,6 +1,6 @@ -package org.baeldung.boot.converter; +package com.baeldung.boot.converter; -import org.baeldung.boot.domain.Modes; +import com.baeldung.boot.domain.Modes; import org.springframework.core.convert.converter.Converter; public class StringToEnumConverter implements Converter { diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToLocalDateTimeConverter.java similarity index 92% rename from spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToLocalDateTimeConverter.java index 8a08b438f2..8d9b85f57a 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/StringToLocalDateTimeConverter.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.converter; +package com.baeldung.boot.converter; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/controller/AbstractEntityController.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/controller/AbstractEntityController.java similarity index 84% rename from spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/controller/AbstractEntityController.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/controller/AbstractEntityController.java index d3c012ba31..ac5bebcdeb 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/controller/AbstractEntityController.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/controller/AbstractEntityController.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.converter.controller; +package com.baeldung.boot.converter.controller; -import org.baeldung.boot.domain.Bar; -import org.baeldung.boot.domain.Foo; -import org.baeldung.boot.domain.Modes; +import com.baeldung.boot.domain.Bar; +import com.baeldung.boot.domain.Foo; +import com.baeldung.boot.domain.Modes; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java new file mode 100644 index 0000000000..ed118f9cdb --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java @@ -0,0 +1,15 @@ +package com.baeldung.boot.converter.controller; + +import com.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-mvc-simple-2/src/main/java/org/baeldung/boot/domain/AbstractEntity.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/AbstractEntity.java similarity index 78% rename from spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/AbstractEntity.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/AbstractEntity.java index 30e0d1e5fe..08953928cb 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/AbstractEntity.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/AbstractEntity.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.domain; +package com.baeldung.boot.domain; public abstract class AbstractEntity { diff --git a/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Bar.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Bar.java new file mode 100644 index 0000000000..063ed3db63 --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Bar.java @@ -0,0 +1,29 @@ +package com.baeldung.boot.domain; + +public class Bar extends AbstractEntity { + + private int value; + + public Bar(long id) { + super(id); + } + + public Bar(long id, int value) { + super(id); + this.value = value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + @Override + public String toString() { + return "Bar [value=" + value + ", id=" + id + "]"; + } + +} diff --git a/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Employee.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Employee.java new file mode 100644 index 0000000000..a96fc5d051 --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Employee.java @@ -0,0 +1,37 @@ +package com.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-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Foo.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Foo.java new file mode 100644 index 0000000000..c6637f6162 --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Foo.java @@ -0,0 +1,31 @@ +package com.baeldung.boot.domain; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +public class Foo extends AbstractEntity { + + private String name; + + public Foo(long id) { + super(id); + name = randomAlphanumeric(4); + } + + public Foo(long id, String name) { + super(id); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Foo [name=" + name + ", id=" + id + "]"; + } + +} diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/GenericEntity.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/GenericEntity.java similarity index 95% rename from spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/GenericEntity.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/GenericEntity.java index f1c936e432..a2a676200a 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/GenericEntity.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/GenericEntity.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.domain; +package com.baeldung.boot.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Modes.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Modes.java new file mode 100644 index 0000000000..7717294996 --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/domain/Modes.java @@ -0,0 +1,6 @@ +package com.baeldung.boot.domain; + +public enum Modes { + + ALPHA, BETA; +} diff --git a/spring-mvc-basics-3/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java new file mode 100644 index 0000000000..5abe7ea6b1 --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.boot.repository; + +import com.baeldung.boot.domain.GenericEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface GenericEntityRepository extends JpaRepository { +} diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java similarity index 96% rename from spring-mvc-simple-2/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java index b3a0dba7e8..de10fa5098 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.web.resolver; +package com.baeldung.boot.web.resolver; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Component; diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/web/resolver/Version.java b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/web/resolver/Version.java similarity index 86% rename from spring-mvc-simple-2/src/main/java/org/baeldung/boot/web/resolver/Version.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/boot/web/resolver/Version.java index f69d40510e..84dabe2b47 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/web/resolver/Version.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/boot/web/resolver/Version.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.web.resolver; +package com.baeldung.boot.web.resolver; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/CachedBodyHttpServletRequest.java b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/CachedBodyHttpServletRequest.java similarity index 97% rename from spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/CachedBodyHttpServletRequest.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/CachedBodyHttpServletRequest.java index b6d4905653..89acbe79a4 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/CachedBodyHttpServletRequest.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/CachedBodyHttpServletRequest.java @@ -1,4 +1,4 @@ -package org.baeldung.cachedrequest; +package com.baeldung.cachedrequest; import java.io.BufferedReader; import java.io.ByteArrayInputStream; diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/CachedBodyServletInputStream.java b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/CachedBodyServletInputStream.java similarity index 96% rename from spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/CachedBodyServletInputStream.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/CachedBodyServletInputStream.java index a18de30788..4d44b23ee9 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/CachedBodyServletInputStream.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/CachedBodyServletInputStream.java @@ -1,4 +1,4 @@ -package org.baeldung.cachedrequest; +package com.baeldung.cachedrequest; import java.io.ByteArrayInputStream; import java.io.IOException; diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/ContentCachingFilter.java b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/ContentCachingFilter.java similarity index 96% rename from spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/ContentCachingFilter.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/ContentCachingFilter.java index e3f3b7a060..ba3901077b 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/ContentCachingFilter.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/ContentCachingFilter.java @@ -1,4 +1,4 @@ -package org.baeldung.cachedrequest; +package com.baeldung.cachedrequest; import java.io.IOException; diff --git a/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/HttpRequestDemoConfig.java b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/HttpRequestDemoConfig.java new file mode 100644 index 0000000000..9516ff861e --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/HttpRequestDemoConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.cachedrequest; + +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.WebMvcConfigurer; +/** + * To initialize the WebApplication, Please see + * {@link com.baeldung.spring.config.MainWebAppInitializer} + */ + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = "com.baeldung.cachedrequest") +public class HttpRequestDemoConfig implements WebMvcConfigurer { + +} \ No newline at end of file diff --git a/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/Person.java b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/Person.java new file mode 100644 index 0000000000..d7ac4c66a3 --- /dev/null +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/Person.java @@ -0,0 +1,47 @@ +package com.baeldung.cachedrequest; + +public class Person { + private String firstName; + + private String lastName; + + private int age; + + public Person() { + } + + public Person(String firstName, String lastName, int age) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + 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; + } + + @Override + public String toString() { + return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}'; + } +} diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/PersonController.java b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/PersonController.java similarity index 95% rename from spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/PersonController.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/PersonController.java index 6f241b3fb3..3c505f4754 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/PersonController.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/PersonController.java @@ -1,4 +1,4 @@ -package org.baeldung.cachedrequest; +package com.baeldung.cachedrequest; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/PrintRequestContentFilter.java b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/PrintRequestContentFilter.java similarity index 97% rename from spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/PrintRequestContentFilter.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/PrintRequestContentFilter.java index 55455f590f..9c4c589a5d 100644 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/PrintRequestContentFilter.java +++ b/spring-mvc-basics-3/src/main/java/com/baeldung/cachedrequest/PrintRequestContentFilter.java @@ -1,4 +1,4 @@ -package org.baeldung.cachedrequest; +package com.baeldung.cachedrequest; import java.io.IOException; diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/Application.java b/spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/Application.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/Application.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/Application.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/controller/FAQController.java b/spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/controller/FAQController.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/controller/FAQController.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/controller/FAQController.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/controller/Ping.java b/spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/controller/Ping.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/controller/Ping.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/controller/Ping.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/filter/FilterRegistrationConfig.java b/spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/filter/FilterRegistrationConfig.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/filter/FilterRegistrationConfig.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/filter/FilterRegistrationConfig.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/filter/HeaderValidatorFilter.java b/spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/filter/HeaderValidatorFilter.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/filter/HeaderValidatorFilter.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/filter/HeaderValidatorFilter.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/filter/LogFilter.java b/spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/filter/LogFilter.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/filter/LogFilter.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/filter/LogFilter.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/service/FAQService.java b/spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/service/FAQService.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/service/FAQService.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/service/FAQService.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/service/FAQServiceImpl.java b/spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/service/FAQServiceImpl.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/exclude_urls_filter/service/FAQServiceImpl.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/exclude_urls_filter/service/FAQServiceImpl.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/Application.java b/spring-mvc-basics-3/src/main/java/com/baeldung/flash_attributes/Application.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/Application.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/flash_attributes/Application.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/controllers/PoemSubmission.java b/spring-mvc-basics-3/src/main/java/com/baeldung/flash_attributes/controllers/PoemSubmission.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/controllers/PoemSubmission.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/flash_attributes/controllers/PoemSubmission.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/model/Poem.java b/spring-mvc-basics-3/src/main/java/com/baeldung/flash_attributes/model/Poem.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/model/Poem.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/flash_attributes/model/Poem.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/form_submission/Application.java b/spring-mvc-basics-3/src/main/java/com/baeldung/form_submission/Application.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/form_submission/Application.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/form_submission/Application.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/form_submission/controllers/FeedbackForm.java b/spring-mvc-basics-3/src/main/java/com/baeldung/form_submission/controllers/FeedbackForm.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/form_submission/controllers/FeedbackForm.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/form_submission/controllers/FeedbackForm.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/form_submission/model/Feedback.java b/spring-mvc-basics-3/src/main/java/com/baeldung/form_submission/model/Feedback.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/form_submission/model/Feedback.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/form_submission/model/Feedback.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/interpolation/MyMessageInterpolator.java b/spring-mvc-basics-3/src/main/java/com/baeldung/interpolation/MyMessageInterpolator.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/interpolation/MyMessageInterpolator.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/interpolation/MyMessageInterpolator.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/interpolation/NotNullRequest.java b/spring-mvc-basics-3/src/main/java/com/baeldung/interpolation/NotNullRequest.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/interpolation/NotNullRequest.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/interpolation/NotNullRequest.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/interpolation/ValidationController.java b/spring-mvc-basics-3/src/main/java/com/baeldung/interpolation/ValidationController.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/interpolation/ValidationController.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/interpolation/ValidationController.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/interpolation/ValidationExamples.java b/spring-mvc-basics-3/src/main/java/com/baeldung/interpolation/ValidationExamples.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/interpolation/ValidationExamples.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/interpolation/ValidationExamples.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/spring/Application.java b/spring-mvc-basics-3/src/main/java/com/baeldung/spring/Application.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/spring/Application.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/spring/Application.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/spring/config/MvcConfig.java b/spring-mvc-basics-3/src/main/java/com/baeldung/spring/config/MvcConfig.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/spring/config/MvcConfig.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/spring/config/MvcConfig.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/spring/config/converter/StringToEnumConverter.java b/spring-mvc-basics-3/src/main/java/com/baeldung/spring/config/converter/StringToEnumConverter.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/spring/config/converter/StringToEnumConverter.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/spring/config/converter/StringToEnumConverter.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/spring/enums/EnumController.java b/spring-mvc-basics-3/src/main/java/com/baeldung/spring/enums/EnumController.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/spring/enums/EnumController.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/spring/enums/EnumController.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/spring/exceptions/GlobalControllerExceptionHandler.java b/spring-mvc-basics-3/src/main/java/com/baeldung/spring/exceptions/GlobalControllerExceptionHandler.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/spring/exceptions/GlobalControllerExceptionHandler.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/spring/exceptions/GlobalControllerExceptionHandler.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/spring/headers/controller/ReadHeaderRestController.java b/spring-mvc-basics-3/src/main/java/com/baeldung/spring/headers/controller/ReadHeaderRestController.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/spring/headers/controller/ReadHeaderRestController.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/spring/headers/controller/ReadHeaderRestController.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/spring/model/Modes.java b/spring-mvc-basics-3/src/main/java/com/baeldung/spring/model/Modes.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/spring/model/Modes.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/spring/model/Modes.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/spring/slash/Application.java b/spring-mvc-basics-3/src/main/java/com/baeldung/spring/slash/Application.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/spring/slash/Application.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/spring/slash/Application.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/spring/slash/SlashParsingController.java b/spring-mvc-basics-3/src/main/java/com/baeldung/spring/slash/SlashParsingController.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/spring/slash/SlashParsingController.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/spring/slash/SlashParsingController.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java b/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java b/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java b/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java b/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java b/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java b/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/service/MovieService.java b/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/service/MovieService.java similarity index 100% rename from spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/service/MovieService.java rename to spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/service/MovieService.java diff --git a/spring-mvc-simple-2/src/main/resources/application.properties b/spring-mvc-basics-3/src/main/resources/application.properties similarity index 100% rename from spring-mvc-simple-2/src/main/resources/application.properties rename to spring-mvc-basics-3/src/main/resources/application.properties diff --git a/spring-mvc-simple-2/src/main/resources/templates/feedback.html b/spring-mvc-basics-3/src/main/resources/templates/feedback.html similarity index 100% rename from spring-mvc-simple-2/src/main/resources/templates/feedback.html rename to spring-mvc-basics-3/src/main/resources/templates/feedback.html diff --git a/spring-mvc-simple-2/src/main/resources/templates/submit.html b/spring-mvc-basics-3/src/main/resources/templates/submit.html similarity index 100% rename from spring-mvc-simple-2/src/main/resources/templates/submit.html rename to spring-mvc-basics-3/src/main/resources/templates/submit.html diff --git a/spring-mvc-simple-2/src/main/resources/templates/success.html b/spring-mvc-basics-3/src/main/resources/templates/success.html similarity index 100% rename from spring-mvc-simple-2/src/main/resources/templates/success.html rename to spring-mvc-basics-3/src/main/resources/templates/success.html diff --git a/spring-mvc-simple-2/src/test/java/com/baeldung/AppContextIntegrationTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/AppContextIntegrationTest.java similarity index 100% rename from spring-mvc-simple-2/src/test/java/com/baeldung/AppContextIntegrationTest.java rename to spring-mvc-basics-3/src/test/java/com/baeldung/AppContextIntegrationTest.java diff --git a/spring-mvc-basics-3/src/test/java/com/baeldung/SpringBootApplicationIntegrationTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/SpringBootApplicationIntegrationTest.java new file mode 100644 index 0000000000..d2b4c1aff9 --- /dev/null +++ b/spring-mvc-basics-3/src/test/java/com/baeldung/SpringBootApplicationIntegrationTest.java @@ -0,0 +1,59 @@ +package com.baeldung; + +import com.baeldung.boot.Application; +import com.baeldung.boot.domain.Modes; +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.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = Application.class) +@WebAppConfiguration +public class SpringBootApplicationIntegrationTest { + + @Autowired + private WebApplicationContext webApplicationContext; + + private MockMvc mockMvc; + + @Before + public void setupMockMvc() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + } + + @Test + public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(4))); + } + + @Test + public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.id", equalTo(1))); + } + + @Test + public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$.id", equalTo(1))); + } + + @Test + public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.id", equalTo(1))); + } +} \ No newline at end of file diff --git a/spring-mvc-simple-2/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java similarity index 86% rename from spring-mvc-simple-2/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java rename to spring-mvc-basics-3/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java index c283529435..6ebc34973e 100644 --- a/spring-mvc-simple-2/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java +++ b/spring-mvc-basics-3/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java @@ -1,8 +1,8 @@ package com.baeldung; -import org.baeldung.boot.Application; -import org.baeldung.boot.domain.GenericEntity; -import org.baeldung.boot.repository.GenericEntityRepository; +import com.baeldung.boot.Application; +import com.baeldung.boot.domain.GenericEntity; +import com.baeldung.boot.repository.GenericEntityRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-mvc-simple-2/src/test/java/com/baeldung/SpringBootMailIntegrationTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/SpringBootMailIntegrationTest.java similarity index 98% rename from spring-mvc-simple-2/src/test/java/com/baeldung/SpringBootMailIntegrationTest.java rename to spring-mvc-basics-3/src/test/java/com/baeldung/SpringBootMailIntegrationTest.java index 1a2a4e22d9..1349e7e9e0 100644 --- a/spring-mvc-simple-2/src/test/java/com/baeldung/SpringBootMailIntegrationTest.java +++ b/spring-mvc-basics-3/src/test/java/com/baeldung/SpringBootMailIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung; -import org.baeldung.boot.Application; +import com.baeldung.boot.Application; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/CachedBodyHttpServletRequestUnitTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/CachedBodyHttpServletRequestUnitTest.java similarity index 98% rename from spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/CachedBodyHttpServletRequestUnitTest.java rename to spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/CachedBodyHttpServletRequestUnitTest.java index 1fe9dd4c82..1ff0093b4b 100644 --- a/spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/CachedBodyHttpServletRequestUnitTest.java +++ b/spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/CachedBodyHttpServletRequestUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.cachedrequest; +package com.baeldung.cachedrequest; import java.io.BufferedReader; import java.io.IOException; diff --git a/spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/CachedBodyServletInputStreamUnitTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/CachedBodyServletInputStreamUnitTest.java similarity index 98% rename from spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/CachedBodyServletInputStreamUnitTest.java rename to spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/CachedBodyServletInputStreamUnitTest.java index d7000d91ee..af025f632e 100644 --- a/spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/CachedBodyServletInputStreamUnitTest.java +++ b/spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/CachedBodyServletInputStreamUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.cachedrequest; +package com.baeldung.cachedrequest; import java.io.ByteArrayOutputStream; import java.io.IOException; diff --git a/spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/ContentCachingFilterUnitTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/ContentCachingFilterUnitTest.java similarity index 97% rename from spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/ContentCachingFilterUnitTest.java rename to spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/ContentCachingFilterUnitTest.java index 057f1ac627..ec0f8948c2 100644 --- a/spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/ContentCachingFilterUnitTest.java +++ b/spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/ContentCachingFilterUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.cachedrequest; +package com.baeldung.cachedrequest; import java.io.IOException; diff --git a/spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/PersonControllerIntegrationTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/PersonControllerIntegrationTest.java similarity index 98% rename from spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/PersonControllerIntegrationTest.java rename to spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/PersonControllerIntegrationTest.java index 046a310cc0..9212ceb886 100644 --- a/spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/PersonControllerIntegrationTest.java +++ b/spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/PersonControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.cachedrequest; +package com.baeldung.cachedrequest; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; diff --git a/spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/PrintRequestContentFilterUnitTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/PrintRequestContentFilterUnitTest.java similarity index 97% rename from spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/PrintRequestContentFilterUnitTest.java rename to spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/PrintRequestContentFilterUnitTest.java index ca2d5c600b..3d2acabe6b 100644 --- a/spring-mvc-simple-2/src/test/java/org/baeldung/cachedrequest/PrintRequestContentFilterUnitTest.java +++ b/spring-mvc-basics-3/src/test/java/com/baeldung/cachedrequest/PrintRequestContentFilterUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.cachedrequest; +package com.baeldung.cachedrequest; import java.io.IOException; diff --git a/spring-mvc-simple-2/src/test/java/com/baeldung/headers/controller/ReadHeaderRestControllerIntegrationTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/headers/controller/ReadHeaderRestControllerIntegrationTest.java similarity index 100% rename from spring-mvc-simple-2/src/test/java/com/baeldung/headers/controller/ReadHeaderRestControllerIntegrationTest.java rename to spring-mvc-basics-3/src/test/java/com/baeldung/headers/controller/ReadHeaderRestControllerIntegrationTest.java diff --git a/spring-mvc-simple-2/src/test/java/com/baeldung/spring/slash/SlashParsingControllerIntTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/spring/slash/SlashParsingControllerIntTest.java similarity index 100% rename from spring-mvc-simple-2/src/test/java/com/baeldung/spring/slash/SlashParsingControllerIntTest.java rename to spring-mvc-basics-3/src/test/java/com/baeldung/spring/slash/SlashParsingControllerIntTest.java diff --git a/spring-mvc-simple-2/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java b/spring-mvc-basics-3/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java similarity index 100% rename from spring-mvc-simple-2/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java rename to spring-mvc-basics-3/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java diff --git a/core-java-modules/core-java-lang-oop/src/test/resources/.gitignore b/spring-mvc-basics-4/.gitignore similarity index 100% rename from core-java-modules/core-java-lang-oop/src/test/resources/.gitignore rename to spring-mvc-basics-4/.gitignore diff --git a/spring-mvc-basics-4/README.md b/spring-mvc-basics-4/README.md new file mode 100644 index 0000000000..19cb9059ed --- /dev/null +++ b/spring-mvc-basics-4/README.md @@ -0,0 +1,11 @@ +## Spring MVC Basics with Java Configuration Example Project + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: +- [Quick Guide to Spring Controllers](https://www.baeldung.com/spring-controllers) +- [Model, ModelMap, and ModelView in Spring MVC](https://www.baeldung.com/spring-mvc-model-model-map-model-view) +- [Spring Web Contexts](https://www.baeldung.com/spring-web-contexts) +- [Spring Optional Path variables](https://www.baeldung.com/spring-optional-path-variables) +- More articles: [[<-- prev]](/spring-mvc-basics-3) \ No newline at end of file diff --git a/spring-mvc-basics-4/pom.xml b/spring-mvc-basics-4/pom.xml new file mode 100644 index 0000000000..8382cd03b8 --- /dev/null +++ b/spring-mvc-basics-4/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + spring-mvc-basics-4 + spring-mvc-basics-4 + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + com.fasterxml.jackson.core + jackson-databind + + + org.springframework + spring-web + + + javax.servlet + javax.servlet-api + provided + + + org.springframework + spring-webmvc + + + + \ No newline at end of file diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/Greeting.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/Greeting.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/Greeting.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/Greeting.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/services/ApplicationContextUtilService.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/services/ApplicationContextUtilService.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/services/ApplicationContextUtilService.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/services/ApplicationContextUtilService.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/contexts/services/GreeterService.java b/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/services/GreeterService.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/contexts/services/GreeterService.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/contexts/services/GreeterService.java diff --git a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/StudentControllerConfig.java similarity index 96% rename from spring-mvc-basics-2/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/StudentControllerConfig.java index 218418ecc8..b84094132d 100644 --- a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java +++ b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/StudentControllerConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.controller.config; +package com.baeldung.controller.config; import javax.servlet.ServletContext; import javax.servlet.ServletException; diff --git a/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/WebConfig.java b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/WebConfig.java new file mode 100644 index 0000000000..6e79ac0aad --- /dev/null +++ b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/WebConfig.java @@ -0,0 +1,28 @@ +package com.baeldung.controller.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.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.controller.controller", "com.baeldung.controller", "com.baeldung.controller.config" }) +public class WebConfig implements WebMvcConfigurer { + @Override + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Bean + public ViewResolver viewResolver() { + InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setPrefix("/WEB-INF/"); + bean.setSuffix(".jsp"); + return bean; + } +} \ No newline at end of file diff --git a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/PassParametersController.java b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/PassParametersController.java similarity index 96% rename from spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/PassParametersController.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/PassParametersController.java index c282ae6a62..d8330333cb 100644 --- a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/PassParametersController.java +++ b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/PassParametersController.java @@ -1,4 +1,4 @@ -package org.baeldung.controller.controller; +package com.baeldung.controller.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; diff --git a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/RestAnnotatedController.java b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestAnnotatedController.java similarity index 84% rename from spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/RestAnnotatedController.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestAnnotatedController.java index 48981fd012..f41d45caff 100644 --- a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/RestAnnotatedController.java +++ b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestAnnotatedController.java @@ -1,6 +1,6 @@ -package org.baeldung.controller.controller; +package com.baeldung.controller.controller; -import org.baeldung.controller.student.Student; +import com.baeldung.controller.student.Student; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/RestController.java b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestController.java similarity index 85% rename from spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/RestController.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestController.java index 4e5d1d9e17..a529faeed3 100644 --- a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/RestController.java +++ b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestController.java @@ -1,6 +1,6 @@ -package org.baeldung.controller.controller; +package com.baeldung.controller.controller; -import org.baeldung.controller.student.Student; +import com.baeldung.controller.student.Student; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/TestController.java b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/TestController.java similarity index 92% rename from spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/TestController.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/TestController.java index 12ae4e0ab1..cf275ffc0f 100644 --- a/spring-mvc-basics-2/src/main/java/org/baeldung/controller/controller/TestController.java +++ b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/TestController.java @@ -2,7 +2,7 @@ /** * @author Prashant Dutta */ -package org.baeldung.controller.controller; +package com.baeldung.controller.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-mvc-basics-4/src/main/java/com/baeldung/controller/student/Student.java b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/student/Student.java new file mode 100644 index 0000000000..8a82dd5553 --- /dev/null +++ b/spring-mvc-basics-4/src/main/java/com/baeldung/controller/student/Student.java @@ -0,0 +1,33 @@ +package com.baeldung.controller.student; + +public class Student { + private String name; + + private int id; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Override + public int hashCode() { + return this.id; + } + + @Override + public boolean equals(Object obj) { + return this.name.equals(((Student) obj).getName()); + } +} \ No newline at end of file diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/Article.java b/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/Article.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/Article.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/Article.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/ArticleViewerController.java b/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerController.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/ArticleViewerController.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerController.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithMapParamController.java b/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamController.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithMapParamController.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamController.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithOptionalParamController.java b/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithOptionalParamController.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithOptionalParamController.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithOptionalParamController.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithRequiredAttributeController.java b/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithRequiredAttributeController.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithRequiredAttributeController.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithRequiredAttributeController.java diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithTwoSeparateMethodsController.java b/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsController.java similarity index 100% rename from spring-mvc-basics-2/src/main/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithTwoSeparateMethodsController.java rename to spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsController.java diff --git a/spring-boot-mvc-2/src/main/resources/application.properties b/spring-mvc-basics-4/src/main/resources/application.properties similarity index 100% rename from spring-boot-mvc-2/src/main/resources/application.properties rename to spring-mvc-basics-4/src/main/resources/application.properties diff --git a/spring-mvc-basics-4/src/main/resources/logback.xml b/spring-mvc-basics-4/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-mvc-basics-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-mvc-basics-4/src/main/resources/test-mvc.xml b/spring-mvc-basics-4/src/main/resources/test-mvc.xml new file mode 100644 index 0000000000..44c300dfc6 --- /dev/null +++ b/spring-mvc-basics-4/src/main/resources/test-mvc.xml @@ -0,0 +1,24 @@ + + + + + + + + /WEB-INF/ + + + .jsp + + + \ No newline at end of file diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/greeting.xml b/spring-mvc-basics-4/src/main/webapp/WEB-INF/greeting.xml similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/greeting.xml rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/greeting.xml diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/index.jsp b/spring-mvc-basics-4/src/main/webapp/WEB-INF/index.jsp similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/index.jsp rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/index.jsp diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/normal-webapp-servlet.xml b/spring-mvc-basics-4/src/main/webapp/WEB-INF/normal-webapp-servlet.xml similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/normal-webapp-servlet.xml rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/normal-webapp-servlet.xml diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/rootApplicationContext.xml b/spring-mvc-basics-4/src/main/webapp/WEB-INF/rootApplicationContext.xml similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/rootApplicationContext.xml rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/rootApplicationContext.xml diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/secure-webapp-servlet.xml b/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure-webapp-servlet.xml similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/secure-webapp-servlet.xml rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/secure-webapp-servlet.xml diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/secure/view/welcome.jsp b/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure/view/welcome.jsp similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/secure/view/welcome.jsp rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/secure/view/welcome.jsp diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/view/sample.jsp b/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/sample.jsp similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/view/sample.jsp rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/view/sample.jsp diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/view/scopesExample.jsp b/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/scopesExample.jsp similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/view/scopesExample.jsp rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/view/scopesExample.jsp diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/view/viewPage.html b/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/viewPage.html similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/view/viewPage.html rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/view/viewPage.html diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/welcome.jsp similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/view/welcome.jsp rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/view/welcome.jsp diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/web-old.xml b/spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml similarity index 98% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/web-old.xml rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml index 03322279e2..1344362d19 100644 --- a/spring-mvc-basics-2/src/main/webapp/WEB-INF/web-old.xml +++ b/spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml @@ -29,7 +29,7 @@ --> diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/welcome.jsp b/spring-mvc-basics-4/src/main/webapp/WEB-INF/welcome.jsp similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/WEB-INF/welcome.jsp rename to spring-mvc-basics-4/src/main/webapp/WEB-INF/welcome.jsp diff --git a/spring-mvc-basics-2/src/main/webapp/index.jsp b/spring-mvc-basics-4/src/main/webapp/index.jsp similarity index 100% rename from spring-mvc-basics-2/src/main/webapp/index.jsp rename to spring-mvc-basics-4/src/main/webapp/index.jsp diff --git a/spring-mvc-basics-2/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java b/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java similarity index 95% rename from spring-mvc-basics-2/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java rename to spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java index e32d9f7aca..f378357548 100644 --- a/spring-mvc-basics-2/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java +++ b/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.controller; +package com.baeldung.controller; import com.fasterxml.jackson.databind.ObjectMapper; -import org.baeldung.controller.config.WebConfig; -import org.baeldung.controller.student.Student; +import com.baeldung.controller.config.WebConfig; +import com.baeldung.controller.student.Student; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/spring-mvc-basics-2/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java b/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java similarity index 96% rename from spring-mvc-basics-2/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java rename to spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java index 8e8a021530..7e5cf1532e 100644 --- a/spring-mvc-basics-2/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java +++ b/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.controller; +package com.baeldung.controller; import org.junit.Assert; import org.junit.Before; @@ -14,7 +14,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; -import org.baeldung.controller.student.Student; +import com.baeldung.controller.student.Student; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) diff --git a/spring-mvc-basics-2/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.java b/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java similarity index 96% rename from spring-mvc-basics-2/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.java rename to spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java index 21084f44ce..aa8148c1ef 100644 --- a/spring-mvc-basics-2/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.java +++ b/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.controller; +package com.baeldung.controller; import org.junit.Assert; import org.junit.Before; @@ -15,7 +15,7 @@ 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. + * This is the test class for {@link com.baeldung.controller.controller.PassParametersController} class. * 09/09/2017 * * @author Ahmet Cetin diff --git a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerControllerIntegrationTest.java b/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java similarity index 97% rename from spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerControllerIntegrationTest.java rename to spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java index 2fb3569fc1..173ac165c3 100644 --- a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerControllerIntegrationTest.java +++ b/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import org.baeldung.controller.config.WebConfig; +import com.baeldung.controller.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration diff --git a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java b/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java similarity index 97% rename from spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java rename to spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java index c7b568b68e..1fadfb7038 100644 --- a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java +++ b/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import org.baeldung.controller.config.WebConfig; +import com.baeldung.controller.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration diff --git a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java b/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java similarity index 97% rename from spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java rename to spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java index 760d94af17..00d620ef9a 100644 --- a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java +++ b/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import org.baeldung.controller.config.WebConfig; +import com.baeldung.controller.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration diff --git a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java b/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java similarity index 97% rename from spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java rename to spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java index fca6bba5fd..f7fff714a9 100644 --- a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java +++ b/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import org.baeldung.controller.config.WebConfig; +import com.baeldung.controller.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration diff --git a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java b/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java similarity index 97% rename from spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java rename to spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java index 5d2733ec92..b4e4c9ade5 100644 --- a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java +++ b/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import org.baeldung.controller.config.WebConfig; +import com.baeldung.controller.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration diff --git a/spring-mvc-basics-4/src/test/resources/test-mvc.xml b/spring-mvc-basics-4/src/test/resources/test-mvc.xml new file mode 100644 index 0000000000..f1aa8e9504 --- /dev/null +++ b/spring-mvc-basics-4/src/test/resources/test-mvc.xml @@ -0,0 +1,24 @@ + + + + + + + + /WEB-INF/ + + + .jsp + + + \ No newline at end of file diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index a995c89a07..cd36ffd94a 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -17,4 +17,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Using Spring @ResponseStatus to Set HTTP Status Code](https://www.baeldung.com/spring-response-status) - [Spring MVC and the @ModelAttribute Annotation](https://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) - [The HttpMediaTypeNotAcceptableException in Spring MVC](https://www.baeldung.com/spring-httpmediatypenotacceptable) -- [[Next -->]](/spring-mvc-basics-2) \ No newline at end of file +- More articles: [[more -->]](/spring-mvc-basics-2) \ No newline at end of file diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml index ab6d200e67..159dda955f 100644 --- a/spring-mvc-basics/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -38,6 +38,7 @@ + spring-mvc-basics org.springframework.boot diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/userHome.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/userHome.jsp new file mode 100644 index 0000000000..38c08d5a18 --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/userHome.jsp @@ -0,0 +1,55 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> + + + + + User Form + + + +
+ +

New User

+
${message}
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + +
+
+ + diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java index 6500955d23..4ccba79f9c 100644 --- a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java @@ -1,9 +1,5 @@ package com.baeldung.web.controller; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -12,6 +8,10 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @SpringBootTest @AutoConfigureMockMvc public class EmployeeControllerContentNegotiationIntegrationTest { @@ -23,7 +23,7 @@ public class EmployeeControllerContentNegotiationIntegrationTest { public void whenEndpointUsingJsonSuffixCalled_thenJsonResponseObtained() throws Exception { this.mockMvc.perform(get("/employee/1.json")) .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)); } @Test @@ -37,7 +37,7 @@ public class EmployeeControllerContentNegotiationIntegrationTest { public void whenEndpointUsingJsonParameterCalled_thenJsonResponseObtained() throws Exception { this.mockMvc.perform(get("/employee/1?mediaType=json")) .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)); } @Test @@ -51,7 +51,7 @@ public class EmployeeControllerContentNegotiationIntegrationTest { public void whenEndpointUsingJsonAcceptHeaderCalled_thenJsonResponseObtained() throws Exception { this.mockMvc.perform(get("/employee/1").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)); } @Test diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java index 87d70c2d29..8071828fa3 100644 --- a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java @@ -1,19 +1,17 @@ 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.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + public class SimpleBookControllerIntegrationTest { private MockMvc mockMvc; - private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; @BeforeEach public void setup() { @@ -25,7 +23,7 @@ public class SimpleBookControllerIntegrationTest { this.mockMvc .perform(get("/books/42")) .andExpect(status().isOk()) - .andExpect(content().contentType(CONTENT_TYPE)) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(42)); } diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java index 294943f2e2..1062280f3b 100644 --- a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java @@ -1,19 +1,17 @@ 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.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + public class SimpleBookRestControllerIntegrationTest { private MockMvc mockMvc; - private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; @BeforeEach public void setup() { @@ -25,7 +23,7 @@ public class SimpleBookRestControllerIntegrationTest { this.mockMvc .perform(get("/books-rest/42")) .andExpect(status().isOk()) - .andExpect(content().contentType(CONTENT_TYPE)) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(42)); } diff --git a/jackson-simple/.gitignore b/spring-mvc-crash/.gitignore similarity index 100% rename from jackson-simple/.gitignore rename to spring-mvc-crash/.gitignore diff --git a/spring-mvc-crash/README.md b/spring-mvc-crash/README.md new file mode 100644 index 0000000000..f158a947b6 --- /dev/null +++ b/spring-mvc-crash/README.md @@ -0,0 +1,11 @@ +## Spring MVC XML + +This module contains articles about Spring MVC with XML configuration + +### Relevant Articles: + +- [Getting Started with CRaSH](https://www.baeldung.com/jvm-crash-shell) + +## Spring MVC with XML Configuration Example Project + +- access a sample jsp page at: `http://localhost:8080/spring-mvc-crash/welcome.htm \ No newline at end of file diff --git a/spring-mvc-crash/pom.xml b/spring-mvc-crash/pom.xml new file mode 100644 index 0000000000..d23e18361b --- /dev/null +++ b/spring-mvc-crash/pom.xml @@ -0,0 +1,176 @@ + + + 4.0.0 + spring-mvc-crash + 0.1-SNAPSHOT + spring-mvc-xml + war + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + + + + javax.servlet + jstl + ${jstl.version} + runtime + + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + commons-io + commons-io + ${commons-io.version} + + + com.maxmind.geoip2 + geoip2 + ${geoip2.version} + + + com.fasterxml.jackson.core + jackson-databind + + + commons-logging + commons-logging + + + + + org.glassfish + javax.el + ${javax.el.version} + + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + + + + org.crashub + crash.embed.spring + ${crash.version} + + + org.crashub + crash.cli + ${crash.version} + + + org.crashub + crash.connectors.telnet + ${crash.version} + + + log4j + log4j + + + + + + + org.codehaus.groovy + groovy + ${groovy.version} + + + + + spring-mvc-xml + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + + + + + + + 5.0.2.RELEASE + 1.5.10.RELEASE + + + 5.1.40 + + + 4.4.5 + 4.5.2 + + + 6.0.10.Final + 3.0.1-b08 + + + 19.0 + 2.8.0 + + + 1.6.1 + + 1.3.2 + 3.0.0-rc-3 + + + + diff --git a/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfig.java new file mode 100644 index 0000000000..cc60a1ff8f --- /dev/null +++ b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.spring; + +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.WebMvcConfigurer; + +@ImportResource("classpath:webMvcConfig.xml") +@Configuration +@ComponentScan +public class ClientWebConfig implements WebMvcConfigurer { + + public ClientWebConfig() { + super(); + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfigJava.java b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfigJava.java new file mode 100644 index 0000000000..55af23034f --- /dev/null +++ b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfigJava.java @@ -0,0 +1,33 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@ComponentScan("com.baeldung.spring") +public class ClientWebConfigJava implements WebMvcConfigurer { + + public ClientWebConfigJava() { + super(); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } + + @Bean + public MethodValidationPostProcessor methodValidationPostProcessor() { + return new MethodValidationPostProcessor(); + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/java/com/baeldung/spring/controller/WelcomeController.java b/spring-mvc-crash/src/main/java/com/baeldung/spring/controller/WelcomeController.java new file mode 100644 index 0000000000..526833611b --- /dev/null +++ b/spring-mvc-crash/src/main/java/com/baeldung/spring/controller/WelcomeController.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class WelcomeController extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + + ModelAndView model = new ModelAndView("welcome"); + model.addObject("msg", "Welcome to Introduction to CRaSH article from Baeldung"); + + return model; + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/resources/contentManagementWebMvcConfig.xml b/spring-mvc-crash/src/main/resources/contentManagementWebMvcConfig.xml new file mode 100644 index 0000000000..8a0671ca87 --- /dev/null +++ b/spring-mvc-crash/src/main/resources/contentManagementWebMvcConfig.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-boot/src/main/resources/logback.xml b/spring-mvc-crash/src/main/resources/logback.xml similarity index 100% rename from spring-boot/src/main/resources/logback.xml rename to spring-mvc-crash/src/main/resources/logback.xml diff --git a/spring-mvc-crash/src/main/resources/messages.properties b/spring-mvc-crash/src/main/resources/messages.properties new file mode 100644 index 0000000000..2a3cccf76c --- /dev/null +++ b/spring-mvc-crash/src/main/resources/messages.properties @@ -0,0 +1,2 @@ +required.name = Name is required! +NotEmpty.person.password = Password is required! \ No newline at end of file diff --git a/spring-mvc-crash/src/main/resources/webMvcConfig.xml b/spring-mvc-crash/src/main/resources/webMvcConfig.xml new file mode 100644 index 0000000000..4bdb405237 --- /dev/null +++ b/spring-mvc-crash/src/main/resources/webMvcConfig.xml @@ -0,0 +1,38 @@ + + + + + + + + + image/jpeg + image/png + + + + + + + + + + + + + + + + + + + diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message.groovy b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message.groovy new file mode 100644 index 0000000000..d66ab13d96 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message.groovy @@ -0,0 +1,14 @@ +import org.crsh.cli.Command; +import org.crsh.cli.Usage; +import org.crsh.cli.Option; + +class message { + + @Usage("show my own message") + @Command + Object main(@Usage("custom message") @Option(names=["m","message"]) String message) { + if (message == null) + message = "No message given..."; + return message; + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message2.java b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message2.java new file mode 100644 index 0000000000..d1ead88024 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message2.java @@ -0,0 +1,14 @@ +import org.crsh.command.BaseCommand; +import org.crsh.cli.Usage; +import org.crsh.cli.Command; +import org.crsh.cli.Option; + +public class message2 extends BaseCommand { + @Usage("show my own message using java") + @Command + public Object main(@Usage("custom message") @Option(names = { "m", "message" }) String message) { + if (message == null) + message = "No message given..."; + return message; + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/crash.properties b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/crash.properties new file mode 100644 index 0000000000..f9ad0d7cf6 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/crash.properties @@ -0,0 +1 @@ +crash.telnet.port=50001 diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/telnet.properties b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/telnet.properties new file mode 100644 index 0000000000..99071d09ff --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/telnet.properties @@ -0,0 +1,65 @@ +############################ +# Telnet daemon properties # +############################ + +##################### +# Terminals Section # +##################### + +# List of terminals available and defined below +terminals=vt100,ansi,windoof,xterm + +# vt100 implementation and aliases +term.vt100.class=net.wimpi.telnetd.io.terminal.vt100 +term.vt100.aliases=default,vt100-am,vt102,dec-vt100 + +# ansi implementation and aliases +term.ansi.class=net.wimpi.telnetd.io.terminal.ansi +term.ansi.aliases=color-xterm,xterm-color,vt320,vt220,linux,screen + +# windoof implementation and aliases +term.windoof.class=net.wimpi.telnetd.io.terminal.Windoof +term.windoof.aliases= + +# xterm implementation and aliases +term.xterm.class=net.wimpi.telnetd.io.terminal.xterm +term.xterm.aliases= + +################## +# Shells Section # +################## + +# List of shells available and defined below +shells=simple + +# shell implementations +shell.simple.class=org.crsh.telnet.term.TelnetHandler + +##################### +# Listeners Section # +##################### +listeners=std + + +# std listener specific properties + +#Basic listener and connection management settings (port is commented because CRaSH configures it) +# std.port=5000 +std.floodprotection=5 +std.maxcon=25 + + +# Timeout Settings for connections (ms) +std.time_to_warning=3600000 +std.time_to_timedout=60000 + +# Housekeeping thread active every 1 secs +std.housekeepinginterval=1000 + +std.inputmode=character + +# Login shell +std.loginshell=simple + +# Connection filter class +std.connectionfilter=none \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-mvc-crash/src/main/webapp/WEB-INF/mvc-servlet.xml new file mode 100644 index 0000000000..46b159d984 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + welcomeController + welcomeController + + + + + + + + + + + + + + 5000 + + + + diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/view/error.jsp b/spring-mvc-crash/src/main/webapp/WEB-INF/view/error.jsp new file mode 100644 index 0000000000..8f3d83af17 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/view/error.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +SpringMVCExample + + + +

Pleas enter the correct details

+ + + + +
Retry
+ + + + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/view/errorPage.jsp b/spring-mvc-crash/src/main/webapp/WEB-INF/view/errorPage.jsp new file mode 100644 index 0000000000..ba8a836285 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/view/errorPage.jsp @@ -0,0 +1,10 @@ +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> +<%@ page session="false"%> + + + Home + + +

${errorMsg}

+ + diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-mvc-crash/src/main/webapp/WEB-INF/view/welcome.jsp new file mode 100644 index 0000000000..348ca652ff --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/view/welcome.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Welcome Page + + +

Welcome to ${msg}

+
+

+ Go to spring handler mappings homepage + + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/web.xml b/spring-mvc-crash/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..4a3d6cb321 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,70 @@ + + + Spring MVC XML Application + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + com.baeldung.spring + + + + org.springframework.web.context.ContextLoaderListener + + + org.crsh.plugin.WebPluginLifeCycle + + + + + mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc + / + + + + + + ExampleOne + com.baeldung.jsp.ExampleOne + + + ExampleOne + /jsp/ExampleOne + + + ExampleThree + com.baeldung.jsp.ExampleThree + + + ExampleThree + /jsp/ExampleThree + + + + + + 10 + + + index.jsp + + + + /errors + + diff --git a/spring-mvc-crash/src/main/webapp/index.jsp b/spring-mvc-crash/src/main/webapp/index.jsp new file mode 100644 index 0000000000..149fc5fe0b --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/index.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC Examples + + + +

Spring MVC Examples

+ + + + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/jsp/ExampleThree.jsp b/spring-mvc-crash/src/main/webapp/jsp/ExampleThree.jsp new file mode 100644 index 0000000000..665eb86a30 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/jsp/ExampleThree.jsp @@ -0,0 +1,10 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Java Binding Example + + +

Bound Value

+

You said: ${text}

+ + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/jsp/ExampleTwo.jsp b/spring-mvc-crash/src/main/webapp/jsp/ExampleTwo.jsp new file mode 100644 index 0000000000..7b2247638d --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/jsp/ExampleTwo.jsp @@ -0,0 +1,13 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Java in Static Page Example + + +

Java in Static Page Example

+ <% String[] arr = {"What's up?", "Hello", "It's a nice day today!"}; + String greetings = arr[(int)(Math.random() * arr.length)]; + %> +

<%= greetings %>

+ + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/jsp/index.jsp b/spring-mvc-crash/src/main/webapp/jsp/index.jsp new file mode 100644 index 0000000000..58c464125d --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/jsp/index.jsp @@ -0,0 +1,12 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + JSP Examples + + +

Simple JSP Examples

+

Invoke HTML rendered by Servlet: here

+

Java in static page: here

+

Java injected by Servlet: here

+ + \ No newline at end of file diff --git a/spring-mvc-crash/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-crash/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..62e34859ee --- /dev/null +++ b/spring-mvc-crash/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.spring.ClientWebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ClientWebConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java index e35fc8c86c..b7e09685b9 100644 --- a/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import com.baeldung.springmvcforms.configuration.ApplicationConfiguration; diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java index 751df882f9..12bb470f1b 100644 --- a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung.listbindingexample; +package com.baeldung.listbindingexample; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java index 0b308319b1..a00c44206a 100644 --- a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung.sessionattrs; +package com.baeldung.sessionattrs; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-mvc-basics-2/.gitignore b/spring-mvc-java-2/.gitignore similarity index 100% rename from spring-mvc-basics-2/.gitignore rename to spring-mvc-java-2/.gitignore diff --git a/spring-mvc-java-2/README.md b/spring-mvc-java-2/README.md new file mode 100644 index 0000000000..09c8d8b294 --- /dev/null +++ b/spring-mvc-java-2/README.md @@ -0,0 +1,6 @@ +### Relevant Articles: + +- [Cache Headers in Spring MVC](https://www.baeldung.com/spring-mvc-cache-headers) +- [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) +- [Spring MVC @PathVariable with a dot (.) gets truncated](https://www.baeldung.com/spring-mvc-pathvariable-dot) +- [A Quick Guide to Spring MVC Matrix Variables](https://www.baeldung.com/spring-mvc-matrix-variables) \ No newline at end of file diff --git a/spring-mvc-java-2/pom.xml b/spring-mvc-java-2/pom.xml new file mode 100644 index 0000000000..af622321cb --- /dev/null +++ b/spring-mvc-java-2/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + spring-mvc-java-2 + 0.1-SNAPSHOT + spring-mvc-java-2 + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + javax.servlet + javax.servlet-api + ${javax.version} + + + org.springframework + spring-webmvc + ${spring.mvc.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + spring-mvc-java-2 + + + src/main/resources + true + + + + + + 4.0.1 + 5.2.2.RELEASE + + + + \ No newline at end of file diff --git a/spring-mvc-java-2/src/main/java/com/baeldung/cache/CacheControlController.java b/spring-mvc-java-2/src/main/java/com/baeldung/cache/CacheControlController.java new file mode 100644 index 0000000000..7305f836cf --- /dev/null +++ b/spring-mvc-java-2/src/main/java/com/baeldung/cache/CacheControlController.java @@ -0,0 +1,54 @@ +package com.baeldung.cache; + +import org.springframework.http.CacheControl; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.context.request.WebRequest; + +import javax.servlet.http.HttpServletResponse; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.concurrent.TimeUnit; + +@Controller +public class CacheControlController { + + @GetMapping(value = "/hello/{name}") + public ResponseEntity hello(@PathVariable String name) { + CacheControl cacheControl = CacheControl.maxAge(60, TimeUnit.SECONDS) + .noTransform() + .mustRevalidate(); + return ResponseEntity.ok() + .cacheControl(cacheControl) + .body("Hello " + name); + } + + @GetMapping(value = "/home/{name}") + public String home(@PathVariable String name, final HttpServletResponse response) { + response.addHeader("Cache-Control", "max-age=60, must-revalidate, no-transform"); + return "home"; + } + + @GetMapping(value = "/login/{name}") + public ResponseEntity intercept(@PathVariable String name) { + return ResponseEntity.ok().body("Hello " + name); + } + + @GetMapping(value = "/productInfo/{name}") + public ResponseEntity validate(@PathVariable String name, WebRequest request) { + + ZoneId zoneId = ZoneId.of("GMT"); + long lastModifiedTimestamp = LocalDateTime.of(2020, 02, 4, 19, 57, 45) + .atZone(zoneId).toInstant().toEpochMilli(); + + if (request.checkNotModified(lastModifiedTimestamp)) { + return ResponseEntity.status(304).build(); + } + + return ResponseEntity.ok().body("Hello " + name); + } + + +} diff --git a/spring-mvc-java-2/src/main/java/com/baeldung/cache/CacheWebConfig.java b/spring-mvc-java-2/src/main/java/com/baeldung/cache/CacheWebConfig.java new file mode 100644 index 0000000000..95367077bd --- /dev/null +++ b/spring-mvc-java-2/src/main/java/com/baeldung/cache/CacheWebConfig.java @@ -0,0 +1,41 @@ +package com.baeldung.cache; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.CacheControl; +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.mvc.WebContentInterceptor; + +import java.util.concurrent.TimeUnit; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = {"com.baeldung.cache"}) +public class CacheWebConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/") + .setCacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS) + .noTransform() + .mustRevalidate()); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + WebContentInterceptor interceptor = new WebContentInterceptor(); + interceptor.addCacheMapping(CacheControl.maxAge(60, TimeUnit.SECONDS) + .noTransform() + .mustRevalidate(), "/login/*"); + registry.addInterceptor(interceptor); + } +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/datetime/DateTimeConfig.java b/spring-mvc-java-2/src/main/java/com/baeldung/datetime/DateTimeConfig.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/datetime/DateTimeConfig.java rename to spring-mvc-java-2/src/main/java/com/baeldung/datetime/DateTimeConfig.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/datetime/DateTimeController.java b/spring-mvc-java-2/src/main/java/com/baeldung/datetime/DateTimeController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/datetime/DateTimeController.java rename to spring-mvc-java-2/src/main/java/com/baeldung/datetime/DateTimeController.java diff --git a/spring-mvc-java-2/src/main/java/com/baeldung/matrix/config/MatrixWebConfig.java b/spring-mvc-java-2/src/main/java/com/baeldung/matrix/config/MatrixWebConfig.java new file mode 100644 index 0000000000..489740fd33 --- /dev/null +++ b/spring-mvc-java-2/src/main/java/com/baeldung/matrix/config/MatrixWebConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.matrix.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.util.UrlPathHelper; + +@Configuration +public class MatrixWebConfig implements WebMvcConfigurer { + + @Override + public void configurePathMatch(PathMatchConfigurer configurer) { + final UrlPathHelper urlPathHelper = new UrlPathHelper(); + urlPathHelper.setRemoveSemicolonContent(false); + + configurer.setUrlPathHelper(urlPathHelper); + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java b/spring-mvc-java-2/src/main/java/com/baeldung/matrix/controller/CompanyController.java similarity index 81% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java rename to spring-mvc-java-2/src/main/java/com/baeldung/matrix/controller/CompanyController.java index af1e729c13..7a21ded026 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java +++ b/spring-mvc-java-2/src/main/java/com/baeldung/matrix/controller/CompanyController.java @@ -1,23 +1,16 @@ -package com.baeldung.web.controller; - -import java.util.HashMap; -import java.util.Map; +package com.baeldung.matrix.controller; +import com.baeldung.matrix.model.Company; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.MatrixVariable; -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.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; -import com.baeldung.model.Company; +import java.util.HashMap; +import java.util.Map; @Controller public class CompanyController { diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-java-2/src/main/java/com/baeldung/matrix/controller/EmployeeController.java similarity index 86% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java rename to spring-mvc-java-2/src/main/java/com/baeldung/matrix/controller/EmployeeController.java index 251287dff8..3f9de2179a 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java-2/src/main/java/com/baeldung/matrix/controller/EmployeeController.java @@ -1,32 +1,22 @@ -package com.baeldung.web.controller; +package com.baeldung.matrix.controller; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; +import com.baeldung.matrix.model.Employee; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.MatrixVariable; -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.bind.annotation.SessionAttributes; +import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; -import com.baeldung.model.Employee; +import java.util.*; @SessionAttributes("employees") @Controller public class EmployeeController { - Map employeeMap = new HashMap<>(); + public Map employeeMap = new HashMap<>(); @ModelAttribute("employees") public void initEmployees() { diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/Company.java b/spring-mvc-java-2/src/main/java/com/baeldung/matrix/model/Company.java similarity index 94% rename from spring-mvc-java/src/main/java/com/baeldung/model/Company.java rename to spring-mvc-java-2/src/main/java/com/baeldung/matrix/model/Company.java index 558507268a..cdf6cb0fd6 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/Company.java +++ b/spring-mvc-java-2/src/main/java/com/baeldung/matrix/model/Company.java @@ -1,4 +1,4 @@ -package com.baeldung.model; +package com.baeldung.matrix.model; public class Company { diff --git a/spring-mvc-java-2/src/main/java/com/baeldung/matrix/model/Employee.java b/spring-mvc-java-2/src/main/java/com/baeldung/matrix/model/Employee.java new file mode 100644 index 0000000000..c3384122b4 --- /dev/null +++ b/spring-mvc-java-2/src/main/java/com/baeldung/matrix/model/Employee.java @@ -0,0 +1,61 @@ +package com.baeldung.matrix.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Employee { + + private long id; + private String name; + private String contactNumber; + private String workingArea; + + public Employee() { + super(); + } + + public Employee(final long id, final String name, final String contactNumber, final String workingArea) { + this.id = id; + this.name = name; + this.contactNumber = contactNumber; + this.workingArea = workingArea; + } + + 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; + } + + public String getWorkingArea() { + return workingArea; + } + + public void setWorkingArea(final String workingArea) { + this.workingArea = workingArea; + } + + @Override + public String toString() { + return "Employee [id=" + id + ", name=" + name + ", contactNumber=" + contactNumber + ", workingArea=" + workingArea + "]"; + } + +} diff --git a/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/CustomWebMvcConfigurationSupport.java b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/CustomWebMvcConfigurationSupport.java new file mode 100644 index 0000000000..12c208c623 --- /dev/null +++ b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/CustomWebMvcConfigurationSupport.java @@ -0,0 +1,17 @@ +package com.baeldung.pathvariable; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; + +@Configuration +public class CustomWebMvcConfigurationSupport extends WebMvcConfigurationSupport { + + @Override + protected PathMatchConfigurer getPathMatchConfigurer() { + PathMatchConfigurer pathMatchConfigurer = super.getPathMatchConfigurer(); + pathMatchConfigurer.setUseSuffixPatternMatch(false); + + return pathMatchConfigurer; + } +} diff --git a/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/SiteController.java b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/SiteController.java new file mode 100644 index 0000000000..493161b0eb --- /dev/null +++ b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/SiteController.java @@ -0,0 +1,33 @@ +package com.baeldung.pathvariable; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/site") +public class SiteController { + + @GetMapping("/{firstValue}/{secondValue}") + public String requestWithError(@PathVariable("firstValue") String firstValue, + @PathVariable("secondValue") String secondValue) { + + return firstValue + " - " + secondValue; + } + + @GetMapping("/{firstValue}/{secondValue:.+}") + public String requestWithRegex(@PathVariable("firstValue") String firstValue, + @PathVariable("secondValue") String secondValue) { + + return firstValue + " - " + secondValue; + } + + @GetMapping("/{firstValue}/{secondValue}/") + public String requestWithSlash(@PathVariable("firstValue") String firstValue, + @PathVariable("secondValue") String secondValue) { + + return firstValue + " - " + secondValue; + } +} diff --git a/spring-mvc-java-2/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-mvc-java-2/src/main/webapp/WEB-INF/mvc-servlet.xml new file mode 100644 index 0000000000..00dac5f8cb --- /dev/null +++ b/spring-mvc-java-2/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -0,0 +1,27 @@ + + + + + + + + /WEB-INF/view/ + + + .jsp + + + + + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/companyHome.jsp b/spring-mvc-java-2/src/main/webapp/WEB-INF/view/companyHome.jsp similarity index 100% rename from spring-mvc-java/src/main/webapp/WEB-INF/view/companyHome.jsp rename to spring-mvc-java-2/src/main/webapp/WEB-INF/view/companyHome.jsp diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/companyView.jsp b/spring-mvc-java-2/src/main/webapp/WEB-INF/view/companyView.jsp similarity index 100% rename from spring-mvc-java/src/main/webapp/WEB-INF/view/companyView.jsp rename to spring-mvc-java-2/src/main/webapp/WEB-INF/view/companyView.jsp diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-java-2/src/main/webapp/WEB-INF/view/employeeHome.jsp similarity index 100% rename from spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp rename to spring-mvc-java-2/src/main/webapp/WEB-INF/view/employeeHome.jsp diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/employeeView.jsp b/spring-mvc-java-2/src/main/webapp/WEB-INF/view/employeeView.jsp similarity index 100% rename from spring-mvc-simple/src/main/webapp/WEB-INF/views/employeeView.jsp rename to spring-mvc-java-2/src/main/webapp/WEB-INF/view/employeeView.jsp diff --git a/spring-mvc-java-2/src/main/webapp/WEB-INF/web.xml b/spring-mvc-java-2/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..86a24e7646 --- /dev/null +++ b/spring-mvc-java-2/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,22 @@ + + + Spring MVC Application 2 + + + mvc + + org.springframework.web.servlet.DispatcherServlet + + + contextConfigLocation + /WEB-INF/mvc-servlet.xml + + 1 + + + + mvc + / + + \ No newline at end of file diff --git a/spring-mvc-java-2/src/main/webapp/resources/hello.css b/spring-mvc-java-2/src/main/webapp/resources/hello.css new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-mvc-java-2/src/test/java/com/baeldung/cache/CacheControlControllerIntegrationTest.java b/spring-mvc-java-2/src/test/java/com/baeldung/cache/CacheControlControllerIntegrationTest.java new file mode 100644 index 0000000000..1e34dd182b --- /dev/null +++ b/spring-mvc-java-2/src/test/java/com/baeldung/cache/CacheControlControllerIntegrationTest.java @@ -0,0 +1,81 @@ +package com.baeldung.cache; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +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.result.MockMvcResultHandlers; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.http.HttpHeaders.IF_UNMODIFIED_SINCE; + +@ExtendWith(SpringExtension.class) +@WebAppConfiguration +@ContextConfiguration(classes = {CacheWebConfig.class, CacheWebConfig.class}) +public class CacheControlControllerIntegrationTest { + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + @BeforeEach + void setup() throws Exception { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + void whenResponseBody_thenReturnCacheHeader() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/hello/baeldung")) + .andDo(MockMvcResultHandlers.print()) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.header() + .string("Cache-Control","max-age=60, must-revalidate, no-transform")); + } + + @Test + void whenViewName_thenReturnCacheHeader() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/home/baeldung")) + .andDo(MockMvcResultHandlers.print()) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.header().string("Cache-Control","max-age=60, must-revalidate, no-transform")) + .andExpect(MockMvcResultMatchers.view().name("home")); + } + + @Test + void whenStaticResources_thenReturnCacheHeader() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/resources/hello.css")) + .andDo(MockMvcResultHandlers.print()) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.header().string("Cache-Control","max-age=60, must-revalidate, no-transform")); + } + + @Test + void whenInterceptor_thenReturnCacheHeader() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/login/baeldung")) + .andDo(MockMvcResultHandlers.print()) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.header().string("Cache-Control","max-age=60, must-revalidate, no-transform")); + } + + @Test + void whenValidate_thenReturnCacheHeader() throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.add(IF_UNMODIFIED_SINCE, "Tue, 04 Feb 2020 19:57:25 GMT"); + this.mockMvc.perform(MockMvcRequestBuilders.get("/productInfo/baeldung").headers(headers)) + .andDo(MockMvcResultHandlers.print()) + .andExpect(MockMvcResultMatchers.status().is(304)); + } + + + + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java b/spring-mvc-java-2/src/test/java/com/baeldung/matrix/EmployeeMvcIntegrationTest.java similarity index 81% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java rename to spring-mvc-java-2/src/test/java/com/baeldung/matrix/EmployeeMvcIntegrationTest.java index 86420a5fbd..c061c1efc7 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java +++ b/spring-mvc-java-2/src/test/java/com/baeldung/matrix/EmployeeMvcIntegrationTest.java @@ -1,11 +1,7 @@ -package com.baeldung.web.controller; - -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.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; +package com.baeldung.matrix; +import com.baeldung.matrix.config.MatrixWebConfig; +import com.baeldung.matrix.controller.EmployeeController; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,11 +14,13 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.spring.web.config.WebConfig; +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.*; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = WebConfig.class) +@ContextConfiguration(classes = { MatrixWebConfig.class, EmployeeController.class }) public class EmployeeMvcIntegrationTest { @Autowired diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java b/spring-mvc-java-2/src/test/java/com/baeldung/matrix/EmployeeNoMvcIntegrationTest.java similarity index 86% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java rename to spring-mvc-java-2/src/test/java/com/baeldung/matrix/EmployeeNoMvcIntegrationTest.java index e84c20c973..2ca70cc0b9 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java +++ b/spring-mvc-java-2/src/test/java/com/baeldung/matrix/EmployeeNoMvcIntegrationTest.java @@ -1,5 +1,8 @@ -package com.baeldung.web.controller; +package com.baeldung.matrix; +import com.baeldung.matrix.config.MatrixWebConfig; +import com.baeldung.matrix.controller.EmployeeController; +import com.baeldung.matrix.model.Employee; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -9,12 +12,9 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; -import com.baeldung.model.Employee; -import com.baeldung.spring.web.config.WebConfig; - @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = WebConfig.class) +@ContextConfiguration(classes = { MatrixWebConfig.class, EmployeeController.class }) public class EmployeeNoMvcIntegrationTest { @Autowired diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 7088162496..877d92901a 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -7,17 +7,10 @@ This module contains articles about Spring MVC with Java configuration The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Introduction to Pointcut Expressions in Spring](https://www.baeldung.com/spring-aop-pointcut-tutorial) -- [Introduction to Advice Types in Spring](https://www.baeldung.com/spring-aop-advice-tutorial) - [Integration Testing in Spring](https://www.baeldung.com/integration-testing-in-spring) -- [A Quick Guide to Spring MVC Matrix Variables](https://www.baeldung.com/spring-mvc-matrix-variables) -- [Intro to WebSockets with Spring](https://www.baeldung.com/websockets-spring) - [File Upload with Spring MVC](https://www.baeldung.com/spring-file-upload) - [Introduction to HtmlUnit](https://www.baeldung.com/htmlunit) - [Upload and Display Excel Files with Spring MVC](https://www.baeldung.com/spring-mvc-excel-files) - [web.xml vs Initializer with Spring](https://www.baeldung.com/spring-xml-vs-java-config) -- [Spring MVC @PathVariable with a dot (.) gets truncated](https://www.baeldung.com/spring-mvc-pathvariable-dot) -- [A Quick Example of Spring Websockets’ @SendToUser Annotation](https://www.baeldung.com/spring-websockets-sendtouser) -- [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) -- [The HttpMediaTypeNotAcceptableException in Spring MVC](https://www.baeldung.com/spring-httpmediatypenotacceptable) +- [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 7d0afd85ec..9e3457aa8a 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -26,12 +26,12 @@ javax.servlet javax.servlet-api - 4.0.1 + ${javax.version} javax.servlet.jsp javax.servlet.jsp-api - 2.3.3 + ${javax-servlet-api.version} javax.servlet @@ -48,24 +48,11 @@ jackson-databind ${jackson.version} - - - - org.aspectj - aspectjrt - 1.9.1 - - - org.aspectj - aspectjweaver - 1.9.1 - - net.sourceforge.htmlunit htmlunit - 2.32 + ${htmlunit.version} commons-logging @@ -82,6 +69,12 @@ commons-io ${commons-io.version} + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + @@ -99,7 +92,7 @@ com.jayway.jsonpath json-path test - 2.4.0 + ${json-path.version} org.springframework.boot @@ -120,18 +113,6 @@ hibernate-validator ${hibernate-validator.version} - - - - - com.google.code.gson - gson - 2.8.5 - - - org.springframework.boot - spring-boot-starter-websocket - org.glassfish javax.el @@ -262,6 +243,7 @@ 3.5 1.3.2 2.5 + 1.4 2.2.0 @@ -283,6 +265,10 @@ 3.16-beta1 3.0.1-b09 + 4.0.1 + 2.3.3 + 2.32 + 2.4.0 com.baeldung.SpringMVCApplication diff --git a/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java b/spring-mvc-java/src/main/java/com/baeldung/accessparamsjs/App.java similarity index 100% rename from spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java rename to spring-mvc-java/src/main/java/com/baeldung/accessparamsjs/App.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/accessparamsjs/Controller.java b/spring-mvc-java/src/main/java/com/baeldung/accessparamsjs/Controller.java new file mode 100644 index 0000000000..157dcf54da --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/accessparamsjs/Controller.java @@ -0,0 +1,32 @@ +package com.baeldung.accessparamsjs; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; + +import java.util.Map; + +/** + * Sample rest controller for the tutorial article + * "Access Spring MVC Model object in JavaScript". + * + * @author Andrew Shcherbakov + * + */ +@RestController +public class Controller { + + /** + * Define two model objects (one integer and one string) and pass them to the view. + * + * @param model + * @return + */ + @RequestMapping("/index") + public ModelAndView thymeleafView(Map model) { + model.put("number", 1234); + model.put("message", "Hello from Spring MVC"); + return new ModelAndView("thymeleaf/index"); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/dao/FooDao.java b/spring-mvc-java/src/main/java/com/baeldung/dao/FooDao.java deleted file mode 100644 index 1d28b082ec..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/dao/FooDao.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.dao; - -import com.baeldung.aop.annotations.Loggable; -import com.baeldung.model.Foo; -import org.springframework.stereotype.Repository; - -@Repository -public class FooDao { - - public String findById(Long id) { - return "Bazz"; - } - - @Loggable - public Foo create(Long id, String name) { - return new Foo(id, name); - } - - public Foo merge(Foo foo) { - return foo; - } -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/Employee.java b/spring-mvc-java/src/main/java/com/baeldung/model/Employee.java deleted file mode 100644 index fb0a452219..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/model/Employee.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.model; - -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -public class Employee { - - private long id; - private String name; - private String contactNumber; - private String workingArea; - - public Employee() { - super(); - } - - public Employee(final long id, final String name, final String contactNumber, final String workingArea) { - this.id = id; - this.name = name; - this.contactNumber = contactNumber; - this.workingArea = workingArea; - } - - 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; - } - - public String getWorkingArea() { - return workingArea; - } - - public void setWorkingArea(final String workingArea) { - this.workingArea = workingArea; - } - - @Override - public String toString() { - return "Employee [id=" + id + ", name=" + name + ", contactNumber=" + contactNumber + ", workingArea=" + workingArea + "]"; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/Foo.java b/spring-mvc-java/src/main/java/com/baeldung/model/Foo.java deleted file mode 100644 index 01f5f43f60..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/model/Foo.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.model; - -import com.baeldung.aop.annotations.Entity; - -@Entity -public class Foo { - private Long id; - private String name; - - public Foo(Long id, String name) { - this.id = id; - this.name = name; - } - - @Override - public String toString() { - return "Foo{" + "id=" + id + ", name='" + name + '\'' + '}'; - } -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/Message.java b/spring-mvc-java/src/main/java/com/baeldung/model/Message.java deleted file mode 100644 index 76d53e132a..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/model/Message.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.model; - -public class Message { - - private String from; - private String text; - - public String getText() { - return text; - } - - public String getFrom() { - return from; - } -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/CustomWebMvcConfigurationSupport.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/CustomWebMvcConfigurationSupport.java deleted file mode 100644 index 4a9f6a3431..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/CustomWebMvcConfigurationSupport.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.spring.web.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -@Configuration -public class CustomWebMvcConfigurationSupport extends WebMvcConfigurationSupport { - - @Bean - public RequestMappingHandlerMapping requestMappingHandlerMapping() { - RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping(); - handlerMapping.setUseSuffixPatternMatch(false); - return handlerMapping; - } -} 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 new file mode 100644 index 0000000000..3623217130 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.web.config; + +import javax.servlet.MultipartConfigElement; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.support.GenericWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class MainWebAppInitializer implements WebApplicationInitializer { + + private String TMP_FOLDER = "/tmp"; + private int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; + + @Override + public void onStartup(ServletContext sc) throws ServletException { + + ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet( + new GenericWebApplicationContext())); + + appServlet.setLoadOnStartup(1); + + 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/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 96e300464b..768fda1c4a 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 @@ -12,6 +12,7 @@ import org.springframework.context.support.ResourceBundleMessageSource; 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.EnableWebMvc; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; @@ -121,4 +122,11 @@ public class WebConfig implements WebMvcConfigurer { public ExcelPOIHelper excelPOIHelper() { return new ExcelPOIHelper(); } + + @Bean(name = "multipartResolver") + public CommonsMultipartResolver multipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(100000); + return multipartResolver; + } } \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SiteController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/SiteController.java deleted file mode 100644 index 3867380665..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SiteController.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.web.controller; - -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@RequestMapping("/site") -public class SiteController { - - @RequestMapping(value = "/{firstValue}/{secondValue}", method = RequestMethod.GET) - public String requestWithError(@PathVariable("firstValue") String firstValue, - @PathVariable("secondValue") String secondValue) { - - return firstValue + " - " + secondValue; - } - - @RequestMapping(value = "/{firstValue}/{secondValue:.+}", method = RequestMethod.GET) - public String requestWithRegex(@PathVariable("firstValue") String firstValue, - @PathVariable("secondValue") String secondValue) { - - return firstValue + " - " + secondValue; - } - - @RequestMapping(value = "/{firstValue}/{secondValue}/", method = RequestMethod.GET) - public String requestWithSlash(@PathVariable("firstValue") String firstValue, - @PathVariable("secondValue") String secondValue) { - - return firstValue + " - " + secondValue; - } -} diff --git a/spring-boot-mvc/src/main/resources/templates/thymeleaf/index.html b/spring-mvc-java/src/main/resources/templates/thymeleaf/index.html similarity index 100% rename from spring-boot-mvc/src/main/resources/templates/thymeleaf/index.html rename to spring-mvc-java/src/main/resources/templates/thymeleaf/index.html diff --git a/spring-boot-mvc/src/main/webapp/js/jquery.js b/spring-mvc-java/src/main/webapp/js/jquery.js similarity index 100% rename from spring-boot-mvc/src/main/webapp/js/jquery.js rename to spring-mvc-java/src/main/webapp/js/jquery.js diff --git a/spring-boot-mvc/src/main/webapp/js/script-async-jquery.js b/spring-mvc-java/src/main/webapp/js/script-async-jquery.js similarity index 100% rename from spring-boot-mvc/src/main/webapp/js/script-async-jquery.js rename to spring-mvc-java/src/main/webapp/js/script-async-jquery.js diff --git a/spring-boot-mvc/src/main/webapp/js/script-async.js b/spring-mvc-java/src/main/webapp/js/script-async.js similarity index 100% rename from spring-boot-mvc/src/main/webapp/js/script-async.js rename to spring-mvc-java/src/main/webapp/js/script-async.js diff --git a/spring-boot-mvc/src/main/webapp/js/script.js b/spring-mvc-java/src/main/webapp/js/script.js similarity index 100% rename from spring-boot-mvc/src/main/webapp/js/script.js rename to spring-mvc-java/src/main/webapp/js/script.js diff --git a/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java deleted file mode 100644 index 8943ecb548..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.config.TestConfig; - -@RunWith(SpringRunner.class) -@ContextConfiguration(classes = {TestConfig.class}) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - - } -} diff --git a/spring-boot-mvc/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java similarity index 100% rename from spring-boot-mvc/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java rename to spring-mvc-java/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java index 2dc62a20f6..f05d34b654 100644 --- a/spring-boot-mvc/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java @@ -1,7 +1,5 @@ package com.baeldung.accessparamsjs; -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; @@ -12,6 +10,8 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/TestConfig.java deleted file mode 100644 index 641513a24a..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/config/TestConfig.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.config; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; - -@Configuration -@ComponentScan(basePackages = { "com.baeldung.dao", "com.baeldung.aop", "com.baeldung.events" }) -@EnableAspectJAutoProxy -public class TestConfig { -} 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 079ea3e5cd..3d34a46791 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 @@ -32,7 +32,7 @@ public class GreetControllerIntegrationTest { private MockMvc mockMvc; - private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; + private static final String CONTENT_TYPE = "application/json"; @Before public void setup() throws Exception { diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java index 0475bd933d..eacd256438 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java @@ -16,7 +16,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; public class GreetControllerUnitTest { private MockMvc mockMvc; - private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; + private static final String CONTENT_TYPE = "application/json"; @Before public void setup() { diff --git a/spring-mvc-simple-2/README.md b/spring-mvc-simple-2/README.md deleted file mode 100644 index 3d240531ae..0000000000 --- a/spring-mvc-simple-2/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Spring MVC Simple 2 - -This module contains articles about Spring MVC - -## Relevant articles: -- [How to Read HTTP Headers in Spring REST Controllers](https://www.baeldung.com/spring-rest-http-headers) -- [A Custom Data Binder in Spring MVC](https://www.baeldung.com/spring-mvc-custom-data-binder) -- [Validating Lists in a Spring Controller](https://www.baeldung.com/spring-validate-list-controller) -- [Spring Validation Message Interpolation](https://www.baeldung.com/spring-validation-message-interpolation) -- [Using a Slash Character in Spring URLs](https://www.baeldung.com/spring-slash-character-in-url) -- [Using Enums as Request Parameters in Spring](https://www.baeldung.com/spring-enum-request-param) -- [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter) -- [Guide to Flash Attributes in a Spring Web Application](https://www.baeldung.com/spring-web-flash-attributes) -- More articles: [[<-- prev]](/spring-mvc-simple) diff --git a/spring-mvc-simple-2/pom.xml b/spring-mvc-simple-2/pom.xml deleted file mode 100644 index 307e8bc94b..0000000000 --- a/spring-mvc-simple-2/pom.xml +++ /dev/null @@ -1,151 +0,0 @@ - - - 4.0.0 - spring-mvc-simple-2 - spring-mvc-simple-2 - war - Demo project for Spring Boot - - - com.baeldung - parent-boot-2 - 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-thymeleaf - provided - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - 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.springframework.cloud - spring-cloud-context - ${springcloud.version} - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - - - ${project.artifactId} - - - src/main/resources - true - - **/conf.properties - - - - - - - - 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 - 2.0.2.RELEASE - 4.5.8 - - - diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/Application.java b/spring-mvc-simple-2/src/main/java/org/baeldung/boot/Application.java deleted file mode 100644 index c1b6558b26..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -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-mvc-simple-2/src/main/java/org/baeldung/boot/config/WebConfig.java b/spring-mvc-simple-2/src/main/java/org/baeldung/boot/config/WebConfig.java deleted file mode 100644 index 6373553837..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/config/WebConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.baeldung.boot.config; - -import java.util.List; - -import org.baeldung.boot.converter.GenericBigDecimalConverter; -import org.baeldung.boot.converter.StringToAbstractEntityConverterFactory; -import org.baeldung.boot.converter.StringToEmployeeConverter; -import org.baeldung.boot.converter.StringToEnumConverter; -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; - -@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.addConverter(new StringToEnumConverter()); - registry.addConverterFactory(new StringToAbstractEntityConverterFactory()); - registry.addConverter(new GenericBigDecimalConverter()); - } -} diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java deleted file mode 100644 index f756a25f67..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java +++ /dev/null @@ -1,34 +0,0 @@ -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-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java deleted file mode 100644 index e00d0ad312..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java +++ /dev/null @@ -1,13 +0,0 @@ -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-mvc-simple-2/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java deleted file mode 100644 index 762d237156..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java +++ /dev/null @@ -1,15 +0,0 @@ -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-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Bar.java b/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Bar.java deleted file mode 100644 index 724f5e4bca..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Bar.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.boot.domain; - -public class Bar extends AbstractEntity { - - private int value; - - public Bar(long id) { - super(id); - } - - public Bar(long id, int value) { - super(id); - this.value = value; - } - - public int getValue() { - return value; - } - - public void setValue(int value) { - this.value = value; - } - - @Override - public String toString() { - return "Bar [value=" + value + ", id=" + id + "]"; - } - -} diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Employee.java b/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Employee.java deleted file mode 100644 index 8242e53200..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Employee.java +++ /dev/null @@ -1,37 +0,0 @@ -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-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Foo.java b/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Foo.java deleted file mode 100644 index a2ff354e59..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Foo.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.baeldung.boot.domain; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; -public class Foo extends AbstractEntity { - - private String name; - - public Foo(long id) { - super(id); - name = randomAlphanumeric(4); - } - - public Foo(long id, String name) { - super(id); - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return "Foo [name=" + name + ", id=" + id + "]"; - } - -} diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Modes.java b/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Modes.java deleted file mode 100644 index dcba064e8c..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/domain/Modes.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.baeldung.boot.domain; - -public enum Modes { - - ALPHA, BETA; -} diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java b/spring-mvc-simple-2/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java deleted file mode 100644 index d897e17afe..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -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-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/HttpRequestDemoConfig.java b/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/HttpRequestDemoConfig.java deleted file mode 100644 index 9194bcf27c..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/HttpRequestDemoConfig.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.cachedrequest; - -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.WebMvcConfigurer; -/** - * To initialize the WebApplication, Please see - * {@link org.baeldung.spring.config.MainWebAppInitializer} - */ - -@EnableWebMvc -@Configuration -@ComponentScan(basePackages = "org.baeldung.cachedrequest") -public class HttpRequestDemoConfig implements WebMvcConfigurer { - -} \ No newline at end of file diff --git a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/Person.java b/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/Person.java deleted file mode 100644 index 594b6f2360..0000000000 --- a/spring-mvc-simple-2/src/main/java/org/baeldung/cachedrequest/Person.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.baeldung.cachedrequest; - -public class Person { - private String firstName; - - private String lastName; - - private int age; - - public Person() { - } - - public Person(String firstName, String lastName, int age) { - this.firstName = firstName; - this.lastName = lastName; - this.age = age; - } - - 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; - } - - @Override - public String toString() { - return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}'; - } -} diff --git a/spring-mvc-simple-2/src/test/java/com/baeldung/SpringBootApplicationIntegrationTest.java b/spring-mvc-simple-2/src/test/java/com/baeldung/SpringBootApplicationIntegrationTest.java deleted file mode 100644 index 7190c4f427..0000000000 --- a/spring-mvc-simple-2/src/test/java/com/baeldung/SpringBootApplicationIntegrationTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung; - -import org.baeldung.boot.Application; -import org.baeldung.boot.domain.Modes; -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.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import java.nio.charset.Charset; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class) -@WebAppConfiguration -public class SpringBootApplicationIntegrationTest { - - @Autowired - private WebApplicationContext webApplicationContext; - - private MockMvc mockMvc; - - @Before - public void setupMockMvc() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - } - - @Test - public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - - mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4))); - } - - @Test - public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); - } - - @Test - public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$.id", equalTo(1))); - } - - @Test - public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); - } -} \ No newline at end of file diff --git a/spring-mvc-simple/README.md b/spring-mvc-simple/README.md deleted file mode 100644 index ae03fedf3c..0000000000 --- a/spring-mvc-simple/README.md +++ /dev/null @@ -1,15 +0,0 @@ -## Spring MVC Simple - -This module contains articles about Spring MVC - -## Relevant articles: - -- [HandlerAdapters in Spring MVC](https://www.baeldung.com/spring-mvc-handler-adapters) -- [Template Engines for Spring](https://www.baeldung.com/spring-template-engines) -- [Spring 5 and Servlet 4 – The PushBuilder](https://www.baeldung.com/spring-5-push) -- [Servlet Redirect vs Forward](https://www.baeldung.com/servlet-redirect-forward) -- [Apache Tiles Integration with Spring MVC](https://www.baeldung.com/spring-mvc-apache-tiles) -- [Guide to Spring Email](https://www.baeldung.com/spring-email) -- [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405) -- [Spring @RequestParam Annotation](https://www.baeldung.com/spring-request-param) -- More articles: [[more -->]](/spring-mvc-simple-2) \ No newline at end of file diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml deleted file mode 100644 index 539e81307a..0000000000 --- a/spring-mvc-simple/pom.xml +++ /dev/null @@ -1,185 +0,0 @@ - - - 4.0.0 - spring-mvc-simple - 0.0.1-SNAPSHOT - spring-mvc-simple - war - - - com.baeldung - parent-spring-5 - 0.0.1-SNAPSHOT - ../parent-spring-5 - - - - - org.springframework - spring-oxm - ${spring.version} - - - com.sun.mail - javax.mail - ${javax.mail.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.hibernate - hibernate-validator - ${hibernate-validator.version} - - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - org.springframework - spring-tx - ${spring.version} - - - - - org.thymeleaf - thymeleaf - ${org.thymeleaf-version} - - - org.thymeleaf - thymeleaf-spring4 - ${org.thymeleaf-version} - - - - - org.freemarker - freemarker - ${freemarker.version} - - - org.springframework - spring-context-support - ${spring.version} - - - - - org.codehaus.groovy - groovy-templates - ${groovy.version} - - - - - de.neuland-bfi - spring-jade4j - ${jade.version} - - - - org.apache.tiles - tiles-jsp - ${apache-tiles.version} - - - - - org.springframework - spring-test - ${spring.version} - test - - - com.rometools - rome - ${rome.version} - - - com.thoughtworks.xstream - xstream - ${xstream.version} - - - com.github.scribejava - scribejava-apis - ${scribejava.version} - - - org.json - json - ${json.version} - - - org.apache.maven.surefire - surefire-logger-api - ${maven-surefire-plugin.version} - - test - true - - - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - src/main/webapp - springMvcSimple - false - ${deploy-path} - - - - - spring-mvc-simple - - - - 1.8 - 1.8 - 2.21.0 - 2.3.2-b02 - 4.0.0 - 6.0.10.Final - enter-location-of-server - 1.3.2 - 3.0.7.RELEASE - 2.4.12 - 2.3.27-incubating - 1.2.5 - 1.9.0 - 1.4.9 - 5.1.0 - 20180130 - 3.0.8 - 1.6.1 - - - 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 deleted file mode 100644 index 941a984684..0000000000 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.baeldung.spring.configuration; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -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.WebMvcConfigurer; -import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -import com.baeldung.spring.controller.rss.ArticleRssFeedViewResolver; -import com.baeldung.spring.controller.rss.JsonChannelHttpMessageConverter; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator", "com.baeldung.spring.mail", "com.baeldung.spring.service" }) -public class ApplicationConfiguration implements WebMvcConfigurer { - - @Override - public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Bean - public ContentNegotiatingViewResolver viewResolver(ContentNegotiationManager cnManager) { - ContentNegotiatingViewResolver cnvResolver = new ContentNegotiatingViewResolver(); - cnvResolver.setContentNegotiationManager(cnManager); - List resolvers = new ArrayList<>(); - - InternalResourceViewResolver bean = new InternalResourceViewResolver("/WEB-INF/views/",".jsp"); - ArticleRssFeedViewResolver articleRssFeedViewResolver = new ArticleRssFeedViewResolver(); - - resolvers.add(bean); - resolvers.add(articleRssFeedViewResolver); - - cnvResolver.setViewResolvers(resolvers); - return cnvResolver; - } - - @Bean - public MultipartResolver multipartResolver() { - CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); - multipartResolver.setMaxUploadSize(5242880); - return multipartResolver; - } - - @Override - public void configureMessageConverters(List> converters) { - converters.add(new StringHttpMessageConverter()); - converters.add(new RssChannelHttpMessageConverter()); - converters.add(new JsonChannelHttpMessageConverter()); - } - - @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/WebInitializer.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java deleted file mode 100644 index 74094a11c7..0000000000 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.spring.configuration; - -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -public class WebInitializer implements WebApplicationInitializer { - - public void onStartup(ServletContext container) throws ServletException { - - AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); - ctx.register(ApplicationConfiguration.class); - // ctx.register(ThymeleafConfiguration.class); - // ctx.register(FreemarkerConfiguration.class); - // ctx.register(GroovyConfiguration.class); - // 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)); - - ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx)); - - servlet.setLoadOnStartup(1); - servlet.addMapping("/"); - } -} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/MailController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/MailController.java deleted file mode 100644 index 16d1202eef..0000000000 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/MailController.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.baeldung.spring.controller; - -import com.baeldung.spring.mail.EmailServiceImpl; -import com.baeldung.spring.domain.MailObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.mail.SimpleMailMessage; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.Errors; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -@Controller -@RequestMapping("/mail") -public class MailController { - - @Autowired - public EmailServiceImpl emailService; - - @Value("${attachment.invoice}") - private String attachmentPath; - - @Autowired - public SimpleMailMessage template; - - private static final Map> labels; - - static { - labels = new HashMap<>(); - - //Simple email - Map props = new HashMap<>(); - props.put("headerText", "Send Simple Email"); - props.put("messageLabel", "Message"); - props.put("additionalInfo", ""); - labels.put("send", props); - - //Email with template - props = new HashMap<>(); - props.put("headerText", "Send Email Using Template"); - props.put("messageLabel", "Template Parameter"); - props.put("additionalInfo", - "The parameter value will be added to the following message template:
" + - "This is the test email template for your email:
'Template Parameter'
" - ); - labels.put("sendTemplate", props); - - //Email with attachment - props = new HashMap<>(); - props.put("headerText", "Send Email With Attachment"); - props.put("messageLabel", "Message"); - 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, - HttpServletRequest request) { - String action = request.getRequestURL().substring( - request.getRequestURL().lastIndexOf("/") + 1 - ); - Map props = labels.get(action); - Set keys = props.keySet(); - Iterator iterator = keys.iterator(); - while (iterator.hasNext()) { - String key = iterator.next(); - model.addAttribute(key, props.get(key)); - } - - model.addAttribute("mailObject", new MailObject()); - return "mail/send"; - } - - @RequestMapping(value = "/send", method = RequestMethod.POST) - public String createMail(Model model, - @ModelAttribute("mailObject") @Valid MailObject mailObject, - Errors errors) { - if (errors.hasErrors()) { - return "mail/send"; - } - emailService.sendSimpleMessage(mailObject.getTo(), - mailObject.getSubject(), mailObject.getText()); - - return "redirect:/home"; - } - - @RequestMapping(value = "/sendTemplate", method = RequestMethod.POST) - public String createMailWithTemplate(Model model, - @ModelAttribute("mailObject") @Valid MailObject mailObject, - Errors errors) { - if (errors.hasErrors()) { - return "mail/send"; - } - emailService.sendSimpleMessageUsingTemplate(mailObject.getTo(), - mailObject.getSubject(), - template, - mailObject.getText()); - - return "redirect:/home"; - } - - @RequestMapping(value = "/sendAttachment", method = RequestMethod.POST) - public String createMailWithAttachment(Model model, - @ModelAttribute("mailObject") @Valid MailObject mailObject, - Errors errors) { - if (errors.hasErrors()) { - return "mail/send"; - } - emailService.sendMessageWithAttachment( - mailObject.getTo(), - mailObject.getSubject(), - mailObject.getText(), - attachmentPath - ); - - return "redirect:/home"; - } -} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/MailObject.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/MailObject.java deleted file mode 100644 index aceaf685fa..0000000000 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/MailObject.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.spring.domain; - -import javax.validation.constraints.Email; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; - -/** - * Created by Olga on 7/20/2016. - */ -public class MailObject { - @Email - @NotNull - @Size(min = 1, message = "Please, set an email address to send the message to it") - private String to; - private String subject; - private String text; - - public String getTo() { - return to; - } - - public void setTo(String to) { - this.to = to; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } -} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/mail/EmailService.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/mail/EmailService.java deleted file mode 100644 index 43d7378227..0000000000 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/mail/EmailService.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.spring.mail; - -import org.springframework.mail.SimpleMailMessage; - -/** - * Created by Olga on 8/22/2016. - */ -public interface EmailService { - void sendSimpleMessage(String to, - String subject, - String text); - void sendSimpleMessageUsingTemplate(String to, - String subject, - SimpleMailMessage template, - String ...templateArgs); - void sendMessageWithAttachment(String to, - String subject, - String text, - String pathToAttachment); -} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java deleted file mode 100644 index 039b970d8e..0000000000 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.spring.mail; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.FileSystemResource; -import org.springframework.mail.MailException; -import org.springframework.mail.SimpleMailMessage; -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; - -/** - * Created by Olga on 7/15/2016. - */ -@Component -public class EmailServiceImpl implements EmailService { - - @Autowired - public JavaMailSender emailSender; - - public void sendSimpleMessage(String to, String subject, String text) { - try { - SimpleMailMessage message = new SimpleMailMessage(); - message.setTo(to); - message.setSubject(subject); - message.setText(text); - - emailSender.send(message); - } catch (MailException exception) { - exception.printStackTrace(); - } - } - - @Override - public void sendSimpleMessageUsingTemplate(String to, - String subject, - SimpleMailMessage template, - String ...templateArgs) { - String text = String.format(template.getText(), templateArgs); - sendSimpleMessage(to, subject, text); - } - - @Override - public void sendMessageWithAttachment(String to, - String subject, - String text, - String pathToAttachment) { - try { - MimeMessage message = emailSender.createMimeMessage(); - // pass 'true' to the constructor to create a multipart message - MimeMessageHelper helper = new MimeMessageHelper(message, true); - - helper.setTo(to); - helper.setSubject(subject); - helper.setText(text); - - FileSystemResource file = new FileSystemResource(new File(pathToAttachment)); - helper.addAttachment("Invoice", file); - - emailSender.send(message); - } catch (MessagingException e) { - e.printStackTrace(); - } - } -} diff --git a/spring-mvc-simple/src/main/resources/application.properties b/spring-mvc-simple/src/main/resources/application.properties deleted file mode 100644 index 9a804c07d8..0000000000 --- a/spring-mvc-simple/src/main/resources/application.properties +++ /dev/null @@ -1,22 +0,0 @@ -#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/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java deleted file mode 100644 index ab0b23c4a5..0000000000 --- a/spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -import com.baeldung.spring.configuration.ApplicationConfiguration; - - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes={ApplicationConfiguration.class}) -@WebAppConfiguration -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} - diff --git a/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java index 22a4486aa7..a27cacba53 100644 --- a/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-mvc-views/README.md b/spring-mvc-views/README.md new file mode 100644 index 0000000000..7aa05699f3 --- /dev/null +++ b/spring-mvc-views/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Spring MVC Themes](https://www.baeldung.com/spring-mvc-themes) diff --git a/spring-mvc-views/src/main/java/com/baeldung/config/SecurityConfig.java b/spring-mvc-views/src/main/java/com/baeldung/config/SecurityConfig.java deleted file mode 100644 index 2e0a413cf3..0000000000 --- a/spring-mvc-views/src/main/java/com/baeldung/config/SecurityConfig.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -import javax.sql.DataSource; - -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - DataSource dataSource; - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.jdbcAuthentication() - .passwordEncoder(passwordEncoder()) - .dataSource(dataSource); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - - http.csrf() - .disable() - .authorizeRequests() - .antMatchers("/anonymous*").anonymous() - .antMatchers("/login*").permitAll() - .anyRequest().authenticated() - .and() - .formLogin() - .and() - .logout() - .logoutUrl("/logout.do") - .invalidateHttpSession(true) - .clearAuthentication(true); - } - - @Override - public void configure(WebSecurity web) throws Exception { - web.ignoring().antMatchers("/themes/**"); - } - -} diff --git a/spring-mvc-views/src/main/java/com/baeldung/config/WebInitializer.java b/spring-mvc-views/src/main/java/com/baeldung/config/WebInitializer.java deleted file mode 100644 index 5516fb7b3c..0000000000 --- a/spring-mvc-views/src/main/java/com/baeldung/config/WebInitializer.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.config; - -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -public class WebInitializer implements WebApplicationInitializer { - @Override - public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException { - AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.register(DataSourceConfig.class); - context.register(ThemeMVCConfig.class); - - - servletContext.addListener(new ContextLoaderListener(context)); - servletContext.setInitParameter("spring.profiles.active", "database"); - - ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context)); - - servlet.setLoadOnStartup(1); - servlet.addMapping("/"); - - } -} diff --git a/spring-mvc-views/src/main/java/com/baeldung/repository/UserPreferenceRepository.java b/spring-mvc-views/src/main/java/com/baeldung/repository/UserPreferenceRepository.java deleted file mode 100644 index 77e5da0498..0000000000 --- a/spring-mvc-views/src/main/java/com/baeldung/repository/UserPreferenceRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.domain.UserPreference; -import org.springframework.data.repository.PagingAndSortingRepository; - -public interface UserPreferenceRepository extends PagingAndSortingRepository { -} diff --git a/spring-mvc-views/src/main/java/com/baeldung/config/DataSourceConfig.java b/spring-mvc-views/src/main/java/com/baeldung/themes/config/DataSourceConfig.java similarity index 94% rename from spring-mvc-views/src/main/java/com/baeldung/config/DataSourceConfig.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/config/DataSourceConfig.java index 803c30f29d..3b1abfd459 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/config/DataSourceConfig.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/config/DataSourceConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.config; +package com.baeldung.themes.config; import org.springframework.context.annotation.Bean; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; @@ -27,7 +27,7 @@ public class DataSourceConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource); - em.setPackagesToScan("com.baeldung.domain"); + em.setPackagesToScan("com.baeldung.themes.domain"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); return em; } diff --git a/spring-mvc-views/src/main/java/com/baeldung/config/InitSecurity.java b/spring-mvc-views/src/main/java/com/baeldung/themes/config/InitSecurity.java similarity index 82% rename from spring-mvc-views/src/main/java/com/baeldung/config/InitSecurity.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/config/InitSecurity.java index 2bf659f476..929e49cb79 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/config/InitSecurity.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/config/InitSecurity.java @@ -1,4 +1,4 @@ -package com.baeldung.config; +package com.baeldung.themes.config; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; diff --git a/spring-mvc-views/src/main/java/com/baeldung/themes/config/SecurityConfig.java b/spring-mvc-views/src/main/java/com/baeldung/themes/config/SecurityConfig.java new file mode 100644 index 0000000000..78a52d4f8b --- /dev/null +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/config/SecurityConfig.java @@ -0,0 +1,56 @@ +package com.baeldung.themes.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +import javax.sql.DataSource; + +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + DataSource dataSource; + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .passwordEncoder(passwordEncoder()) + .dataSource(dataSource); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + + http.csrf() + .disable() + .authorizeRequests() + .antMatchers("/anonymous*").anonymous() + .antMatchers("/login*").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .and() + .logout() + .logoutUrl("/logout.do") + .invalidateHttpSession(true) + .clearAuthentication(true); + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/themes/**"); + } + +} diff --git a/spring-mvc-views/src/main/java/com/baeldung/config/ThemeMVCConfig.java b/spring-mvc-views/src/main/java/com/baeldung/themes/config/ThemeMVCConfig.java similarity index 94% rename from spring-mvc-views/src/main/java/com/baeldung/config/ThemeMVCConfig.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/config/ThemeMVCConfig.java index 86f6f54195..1d3f94258e 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/config/ThemeMVCConfig.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/config/ThemeMVCConfig.java @@ -1,6 +1,6 @@ -package com.baeldung.config; +package com.baeldung.themes.config; -import com.baeldung.theme.resolver.UserPreferenceThemeResolver; +import com.baeldung.themes.resolver.UserPreferenceThemeResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; diff --git a/spring-mvc-views/src/main/java/com/baeldung/themes/config/WebInitializer.java b/spring-mvc-views/src/main/java/com/baeldung/themes/config/WebInitializer.java new file mode 100644 index 0000000000..3fbe8d043d --- /dev/null +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/config/WebInitializer.java @@ -0,0 +1,28 @@ +package com.baeldung.themes.config; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class WebInitializer implements WebApplicationInitializer { + @Override + public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.register(DataSourceConfig.class); + context.register(ThemeMVCConfig.class); + + + servletContext.addListener(new ContextLoaderListener(context)); + servletContext.setInitParameter("spring.profiles.active", "database"); + + ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context)); + + servlet.setLoadOnStartup(1); + servlet.addMapping("/"); + + } +} diff --git a/spring-mvc-views/src/main/java/com/baeldung/controllers/AppController.java b/spring-mvc-views/src/main/java/com/baeldung/themes/controllers/AppController.java similarity index 85% rename from spring-mvc-views/src/main/java/com/baeldung/controllers/AppController.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/controllers/AppController.java index 31343492e1..ed398fa60a 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/controllers/AppController.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/controllers/AppController.java @@ -1,4 +1,4 @@ -package com.baeldung.controllers; +package com.baeldung.themes.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/spring-mvc-views/src/main/java/com/baeldung/domain/UserPreference.java b/spring-mvc-views/src/main/java/com/baeldung/themes/domain/UserPreference.java similarity index 93% rename from spring-mvc-views/src/main/java/com/baeldung/domain/UserPreference.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/domain/UserPreference.java index 81034de947..89f8ea1a36 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/domain/UserPreference.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/domain/UserPreference.java @@ -1,4 +1,4 @@ -package com.baeldung.domain; +package com.baeldung.themes.domain; import javax.persistence.Entity; import javax.persistence.Id; diff --git a/spring-mvc-views/src/main/java/com/baeldung/themes/repository/UserPreferenceRepository.java b/spring-mvc-views/src/main/java/com/baeldung/themes/repository/UserPreferenceRepository.java new file mode 100644 index 0000000000..d4e4ff0a5e --- /dev/null +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/repository/UserPreferenceRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.themes.repository; + +import com.baeldung.themes.domain.UserPreference; +import org.springframework.data.repository.PagingAndSortingRepository; + +public interface UserPreferenceRepository extends PagingAndSortingRepository { +} diff --git a/spring-mvc-views/src/main/java/com/baeldung/theme/resolver/UserPreferenceThemeResolver.java b/spring-mvc-views/src/main/java/com/baeldung/themes/resolver/UserPreferenceThemeResolver.java similarity index 95% rename from spring-mvc-views/src/main/java/com/baeldung/theme/resolver/UserPreferenceThemeResolver.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/resolver/UserPreferenceThemeResolver.java index 4c59734d41..ff160110fd 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/theme/resolver/UserPreferenceThemeResolver.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/resolver/UserPreferenceThemeResolver.java @@ -1,7 +1,7 @@ -package com.baeldung.theme.resolver; +package com.baeldung.themes.resolver; -import com.baeldung.domain.UserPreference; -import com.baeldung.repository.UserPreferenceRepository; +import com.baeldung.themes.domain.UserPreference; +import com.baeldung.themes.repository.UserPreferenceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; diff --git a/spring-mvc-webflow/src/main/java/org/baeldung/servlet/WebInitializer.java b/spring-mvc-webflow/src/main/java/org/baeldung/servlet/WebInitializer.java index 2f52cad804..fc0adb558d 100644 --- a/spring-mvc-webflow/src/main/java/org/baeldung/servlet/WebInitializer.java +++ b/spring-mvc-webflow/src/main/java/org/baeldung/servlet/WebInitializer.java @@ -1,9 +1,9 @@ -package org.baeldung.servlet; +package com.baeldung.servlet; import javax.servlet.ServletRegistration.Dynamic; -import org.baeldung.spring.WebFlowConfig; -import org.baeldung.spring.WebMvcConfig; +import com.baeldung.spring.WebFlowConfig; +import com.baeldung.spring.WebMvcConfig; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { diff --git a/spring-mvc-webflow/src/main/java/org/baeldung/spring/WebFlowConfig.java b/spring-mvc-webflow/src/main/java/org/baeldung/spring/WebFlowConfig.java index 3d2de2a014..d42996bbaf 100644 --- a/spring-mvc-webflow/src/main/java/org/baeldung/spring/WebFlowConfig.java +++ b/spring-mvc-webflow/src/main/java/org/baeldung/spring/WebFlowConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import java.util.Collections; 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 46bf322f1d..acaa11638d 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 @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; diff --git a/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java index 122dc18bad..d58ddae6b8 100644 --- a/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java @@ -1,7 +1,7 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.spring.WebFlowConfig; -import org.baeldung.spring.WebMvcConfig; +import com.baeldung.spring.WebFlowConfig; +import com.baeldung.spring.WebMvcConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index e93b426119..4812d5c979 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -92,6 +92,36 @@ ${spring-boot.version} test + + + + org.crashub + crash.embed.spring + ${crash.version} + + + org.crashub + crash.cli + ${crash.version} + + + org.crashub + crash.connectors.telnet + ${crash.version} + + + log4j + log4j + + + + + + + org.codehaus.groovy + groovy + ${groovy.version} + @@ -138,6 +168,9 @@ 1.6.1 + 1.3.2 + 3.0.0-rc-3 + diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/crash/commands/message.groovy b/spring-mvc-xml/src/main/webapp/WEB-INF/crash/commands/message.groovy new file mode 100644 index 0000000000..d66ab13d96 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/crash/commands/message.groovy @@ -0,0 +1,14 @@ +import org.crsh.cli.Command; +import org.crsh.cli.Usage; +import org.crsh.cli.Option; + +class message { + + @Usage("show my own message") + @Command + Object main(@Usage("custom message") @Option(names=["m","message"]) String message) { + if (message == null) + message = "No message given..."; + return message; + } +} \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/crash/commands/message2.java b/spring-mvc-xml/src/main/webapp/WEB-INF/crash/commands/message2.java new file mode 100644 index 0000000000..d1ead88024 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/crash/commands/message2.java @@ -0,0 +1,14 @@ +import org.crsh.command.BaseCommand; +import org.crsh.cli.Usage; +import org.crsh.cli.Command; +import org.crsh.cli.Option; + +public class message2 extends BaseCommand { + @Usage("show my own message using java") + @Command + public Object main(@Usage("custom message") @Option(names = { "m", "message" }) String message) { + if (message == null) + message = "No message given..."; + return message; + } +} \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/crash/crash.properties b/spring-mvc-xml/src/main/webapp/WEB-INF/crash/crash.properties new file mode 100644 index 0000000000..f9ad0d7cf6 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/crash/crash.properties @@ -0,0 +1 @@ +crash.telnet.port=50001 diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/crash/telnet.properties b/spring-mvc-xml/src/main/webapp/WEB-INF/crash/telnet.properties new file mode 100644 index 0000000000..99071d09ff --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/crash/telnet.properties @@ -0,0 +1,65 @@ +############################ +# Telnet daemon properties # +############################ + +##################### +# Terminals Section # +##################### + +# List of terminals available and defined below +terminals=vt100,ansi,windoof,xterm + +# vt100 implementation and aliases +term.vt100.class=net.wimpi.telnetd.io.terminal.vt100 +term.vt100.aliases=default,vt100-am,vt102,dec-vt100 + +# ansi implementation and aliases +term.ansi.class=net.wimpi.telnetd.io.terminal.ansi +term.ansi.aliases=color-xterm,xterm-color,vt320,vt220,linux,screen + +# windoof implementation and aliases +term.windoof.class=net.wimpi.telnetd.io.terminal.Windoof +term.windoof.aliases= + +# xterm implementation and aliases +term.xterm.class=net.wimpi.telnetd.io.terminal.xterm +term.xterm.aliases= + +################## +# Shells Section # +################## + +# List of shells available and defined below +shells=simple + +# shell implementations +shell.simple.class=org.crsh.telnet.term.TelnetHandler + +##################### +# Listeners Section # +##################### +listeners=std + + +# std listener specific properties + +#Basic listener and connection management settings (port is commented because CRaSH configures it) +# std.port=5000 +std.floodprotection=5 +std.maxcon=25 + + +# Timeout Settings for connections (ms) +std.time_to_warning=3600000 +std.time_to_timedout=60000 + +# Housekeeping thread active every 1 secs +std.housekeepinginterval=1000 + +std.inputmode=character + +# Login shell +std.loginshell=simple + +# Connection filter class +std.connectionfilter=none \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml index 5c8fa611ed..126fea996e 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -52,4 +52,15 @@ + + + + + + 5000 + + + diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml index 6ff435b84b..4a3d6cb321 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml @@ -21,6 +21,9 @@ org.springframework.web.context.ContextLoaderListener + + org.crsh.plugin.WebPluginLifeCycle + diff --git a/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java index 27dcb83bd4..62e34859ee 100644 --- a/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-reactive-kotlin/README.md b/spring-reactive-kotlin/README.md index 629f7e7f58..d6ce3b7645 100644 --- a/spring-reactive-kotlin/README.md +++ b/spring-reactive-kotlin/README.md @@ -4,3 +4,4 @@ This module contains articles about reactive Kotlin ### Relevant Articles: - [Spring Webflux with Kotlin](https://www.baeldung.com/spring-webflux-kotlin) +- [Kotlin Reactive Microservice With Spring Boot](https://www.baeldung.com/spring-boot-kotlin-reactive-microservice) diff --git a/spring-reactive-kotlin/pom.xml b/spring-reactive-kotlin/pom.xml index 3a693837df..cbb143f6ec 100644 --- a/spring-reactive-kotlin/pom.xml +++ b/spring-reactive-kotlin/pom.xml @@ -5,6 +5,7 @@ spring-reactive-kotlin spring-reactive-kotlin Demo project for Spring Boot + jar @@ -23,6 +24,18 @@ org.springframework.boot spring-boot-starter-webflux + + org.springframework.boot.experimental + spring-boot-starter-data-r2dbc + + + org.springframework.boot + spring-boot-starter-actuator + + + io.r2dbc + r2dbc-h2 + com.fasterxml.jackson.module jackson-module-kotlin @@ -38,21 +51,95 @@ reactor-test test + + + org.springframework.boot.experimental + spring-boot-test-autoconfigure-r2dbc + test + + + io.projectreactor + reactor-test + test + + + + + + org.springframework.boot.experimental + spring-boot-bom-r2dbc + 0.1.0.M3 + pom + import + + + + + src/main/kotlin + src/test/kotlin kotlin-maven-plugin + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + org.jetbrains.kotlin ${kotlin.version} -Xjsr305=strict + 1.8 + + spring + jpa + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-maven-noarg + ${kotlin.version} + + + + 1.8 + 1.3.70 + 2.2.5.RELEASE + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt new file mode 100644 index 0000000000..c70057b5de --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt @@ -0,0 +1,11 @@ +package com.baeldung.bootmicroservice + +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication + +@SpringBootApplication +class HealthTrackerApplication + +fun main(args: Array) { + runApplication(*args) +} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt new file mode 100644 index 0000000000..b14682cc5c --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt @@ -0,0 +1,28 @@ +package com.baeldung.bootmicroservice.config; + +import org.springframework.context.annotation.Configuration +import org.springframework.data.r2dbc.core.DatabaseClient + +@Configuration +class DBConfiguration(db: DatabaseClient) { + init { + val initDb = db.execute { + """ CREATE TABLE IF NOT EXISTS profile ( + id SERIAL PRIMARY KEY, + first_name VARCHAR(20) NOT NULL, + last_name VARCHAR(20) NOT NULL, + birth_date DATE NOT NULL + ); + CREATE TABLE IF NOT EXISTS health_record( + id SERIAL PRIMARY KEY, + profile_id LONG NOT NULL, + temperature DECIMAL NOT NULL, + blood_pressure DECIMAL NOT NULL, + heart_rate DECIMAL, + date DATE NOT NULL + ); + """ + } + initDb.then().subscribe() + } +} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt new file mode 100644 index 0000000000..620f187b7b --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt @@ -0,0 +1,44 @@ +package com.baeldung.bootmicroservice.controller + +import com.baeldung.bootmicroservice.model.AverageHealthStatus +import com.baeldung.bootmicroservice.model.HealthRecord +import com.baeldung.bootmicroservice.repository.HealthRecordRepository +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.RestController +import reactor.core.publisher.Mono + +@RestController +class HealthRecordController(val repository: HealthRecordRepository) { + + @PostMapping("/health/{profileId}/record") + fun storeHealthRecord(@PathVariable("profileId") profileId: Long, @RequestBody record: HealthRecord): Mono = + repository.save(HealthRecord(null + , profileId + , record.temperature + , record.bloodPressure + , record.heartRate + , record.date)) + + @GetMapping("/health/{profileId}/avg") + fun fetchHealthRecordAverage(@PathVariable("profileId") profileId: Long): Mono = + repository.findByProfileId(profileId) + .reduce( + AverageHealthStatus(0, 0.0, 0.0, 0.0) + , { s, r -> + AverageHealthStatus(s.cnt + 1 + , s.temperature + r.temperature + , s.bloodPressure + r.bloodPressure + , s.heartRate + r.heartRate + ) + } + ).map { s -> + AverageHealthStatus(s.cnt + , if (s.cnt != 0) s.temperature / s.cnt else 0.0 + , if (s.cnt != 0) s.bloodPressure / s.cnt else 0.0 + , if (s.cnt != 0) s.heartRate / s.cnt else 0.0) + } + +} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt new file mode 100644 index 0000000000..1dc3bcdc50 --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt @@ -0,0 +1,15 @@ +package com.baeldung.bootmicroservice.controller + +import com.baeldung.bootmicroservice.model.Profile +import com.baeldung.bootmicroservice.repository.ProfileRepository +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RestController +import reactor.core.publisher.Mono + +@RestController +class ProfileController(val repository: ProfileRepository) { + + @PostMapping("/profile") + fun save(@RequestBody profile: Profile): Mono = repository.save(profile) +} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt new file mode 100644 index 0000000000..3141146b9c --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt @@ -0,0 +1,3 @@ +package com.baeldung.bootmicroservice.model; + +class AverageHealthStatus(var cnt: Int, var temperature: Double, var bloodPressure: Double, var heartRate: Double) diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt new file mode 100644 index 0000000000..71c534027f --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt @@ -0,0 +1,8 @@ +package com.baeldung.bootmicroservice.model + +import org.springframework.data.annotation.Id +import org.springframework.data.relational.core.mapping.Table +import java.time.LocalDate + +@Table +data class HealthRecord(@Id var id: Long?, var profileId: Long?, var temperature: Double, var bloodPressure: Double, var heartRate: Double, var date: LocalDate) \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt new file mode 100644 index 0000000000..cbb7e675ea --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt @@ -0,0 +1,8 @@ +package com.baeldung.bootmicroservice.model + +import org.springframework.data.annotation.Id +import org.springframework.data.relational.core.mapping.Table +import java.time.LocalDateTime + +@Table +data class Profile(@Id var id:Long?, var firstName : String, var lastName : String, var birthDate: LocalDateTime) \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt new file mode 100644 index 0000000000..8cc91f06e4 --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt @@ -0,0 +1,13 @@ +package com.baeldung.bootmicroservice.repository + +import com.baeldung.bootmicroservice.model.HealthRecord +import org.springframework.data.r2dbc.repository.Query +import org.springframework.data.repository.reactive.ReactiveCrudRepository +import org.springframework.stereotype.Repository +import reactor.core.publisher.Flux + +@Repository +interface HealthRecordRepository: ReactiveCrudRepository { + @Query("select p.* from health_record p where p.profile_id = :profileId ") + fun findByProfileId(profileId: Long): Flux +} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt new file mode 100644 index 0000000000..eee8c5fcbe --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt @@ -0,0 +1,8 @@ +package com.baeldung.bootmicroservice.repository + +import com.baeldung.bootmicroservice.model.Profile +import org.springframework.data.repository.reactive.ReactiveCrudRepository +import org.springframework.stereotype.Repository + +@Repository +interface ProfileRepository: ReactiveCrudRepository \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/resources/application.yml b/spring-reactive-kotlin/src/main/resources/application.yml new file mode 100644 index 0000000000..d75683f905 --- /dev/null +++ b/spring-reactive-kotlin/src/main/resources/application.yml @@ -0,0 +1 @@ +management.endpoints.web.exposure.include: health,metrics \ No newline at end of file diff --git a/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt b/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt new file mode 100644 index 0000000000..51481af3d7 --- /dev/null +++ b/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt @@ -0,0 +1,51 @@ +package com.baeldung.bootmicroservice.controller; + +import com.baeldung.bootmicroservice.model.Profile +import com.fasterxml.jackson.databind.ObjectMapper +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.http.MediaType +import org.springframework.test.web.reactive.server.WebTestClient +import java.time.LocalDateTime + +@SpringBootTest +class ProfileControllerTest { + @Autowired + lateinit var controller: ProfileController + + @Autowired + lateinit var mapper: ObjectMapper ; + + lateinit var client: WebTestClient + lateinit var profile: String + + @BeforeEach + fun setup() { + client = WebTestClient.bindToController(controller).build() + profile = mapper.writeValueAsString(Profile(null, "kotlin", "reactive", LocalDateTime.now())) + } + + @Test + fun whenRequestProfile_thenStatusShouldBeOk() { + client.post() + .uri("/profile") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(profile) + .exchange() + .expectStatus().isOk + } + + @Test + fun whenRequestProfile_thenIdShouldBeNotNull() { + client.post() + .uri("/profile") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(profile) + .exchange() + .expectBody() + .jsonPath("$.id") + .isNotEmpty + } +} diff --git a/spring-reactor/README.md b/spring-reactor/README.md index b92478f6fb..f8cf2898f1 100644 --- a/spring-reactor/README.md +++ b/spring-reactor/README.md @@ -4,4 +4,4 @@ This module contains articles about Spring Reactor ## Relevant articles: -- [Introduction to Spring Reactor](https://www.baeldung.com/spring-reactor) +- [Introduction to Project Reactor Bus](https://www.baeldung.com/reactor-bus) diff --git a/spring-reactor/src/main/java/com/baeldung/Application.java b/spring-reactor/src/main/java/com/baeldung/Application.java deleted file mode 100644 index 9030d41d26..0000000000 --- a/spring-reactor/src/main/java/com/baeldung/Application.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -import com.baeldung.consumer.NotificationConsumer; - -import reactor.bus.EventBus; - -import static reactor.bus.selector.Selectors.$; - -@Configuration -@EnableAutoConfiguration -@ComponentScan -@Import(Config.class) -public class Application implements CommandLineRunner { - - @Autowired - private EventBus eventBus; - - @Autowired - private NotificationConsumer notificationConsumer; - - @Override - public void run(String... args) throws Exception { - eventBus.on($("notificationConsumer"), notificationConsumer); - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-reactor/src/main/java/com/baeldung/Config.java b/spring-reactor/src/main/java/com/baeldung/Config.java deleted file mode 100644 index 28f40dda02..0000000000 --- a/spring-reactor/src/main/java/com/baeldung/Config.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import reactor.Environment; -import reactor.bus.EventBus; - -@Configuration -public class Config { - - @Bean - Environment env() { - return Environment.initializeIfEmpty().assignErrorJournal(); - } - - @Bean - EventBus createEventBus(Environment env) { - return EventBus.create(env, Environment.THREAD_POOL); - } - -} diff --git a/spring-reactor/src/main/java/com/baeldung/reactorbus/Config.java b/spring-reactor/src/main/java/com/baeldung/reactorbus/Config.java new file mode 100644 index 0000000000..f849215dc4 --- /dev/null +++ b/spring-reactor/src/main/java/com/baeldung/reactorbus/Config.java @@ -0,0 +1,20 @@ +package com.baeldung.reactorbus; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import reactor.Environment; +import reactor.bus.EventBus; + +@Configuration +public class Config { + + @Bean + public Environment env() { + return Environment.initializeIfEmpty().assignErrorJournal(); + } + + @Bean + public EventBus createEventBus(Environment env) { + return EventBus.create(env, Environment.THREAD_POOL); + } +} diff --git a/spring-reactor/src/main/java/com/baeldung/reactorbus/NotificationApplication.java b/spring-reactor/src/main/java/com/baeldung/reactorbus/NotificationApplication.java new file mode 100644 index 0000000000..b315e6ce25 --- /dev/null +++ b/spring-reactor/src/main/java/com/baeldung/reactorbus/NotificationApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.reactorbus; + +import com.baeldung.reactorbus.consumer.NotificationConsumer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import reactor.bus.EventBus; + +import static reactor.bus.selector.Selectors.$; + +@SpringBootApplication +public class NotificationApplication implements CommandLineRunner { + + @Autowired + private EventBus eventBus; + + @Autowired + private NotificationConsumer notificationConsumer; + + @Override + public void run(String... args) throws Exception { + eventBus.on($("notificationConsumer"), notificationConsumer); + } + + public static void main(String[] args) { + SpringApplication.run(NotificationApplication.class, args); + } +} diff --git a/spring-reactor/src/main/java/com/baeldung/consumer/NotificationConsumer.java b/spring-reactor/src/main/java/com/baeldung/reactorbus/consumer/NotificationConsumer.java similarity index 80% rename from spring-reactor/src/main/java/com/baeldung/consumer/NotificationConsumer.java rename to spring-reactor/src/main/java/com/baeldung/reactorbus/consumer/NotificationConsumer.java index ca6a5b4303..d9d2586187 100644 --- a/spring-reactor/src/main/java/com/baeldung/consumer/NotificationConsumer.java +++ b/spring-reactor/src/main/java/com/baeldung/reactorbus/consumer/NotificationConsumer.java @@ -1,10 +1,10 @@ -package com.baeldung.consumer; +package com.baeldung.reactorbus.consumer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import com.baeldung.doman.NotificationData; -import com.baeldung.service.NotificationService; +import com.baeldung.reactorbus.domain.NotificationData; +import com.baeldung.reactorbus.service.NotificationService; import reactor.bus.Event; import reactor.fn.Consumer; diff --git a/spring-reactor/src/main/java/com/baeldung/controller/NotificationController.java b/spring-reactor/src/main/java/com/baeldung/reactorbus/controller/NotificationController.java similarity index 89% rename from spring-reactor/src/main/java/com/baeldung/controller/NotificationController.java rename to spring-reactor/src/main/java/com/baeldung/reactorbus/controller/NotificationController.java index 8665f247b0..62a7b38662 100644 --- a/spring-reactor/src/main/java/com/baeldung/controller/NotificationController.java +++ b/spring-reactor/src/main/java/com/baeldung/reactorbus/controller/NotificationController.java @@ -1,11 +1,11 @@ -package com.baeldung.controller; +package com.baeldung.reactorbus.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; -import com.baeldung.doman.NotificationData; +import com.baeldung.reactorbus.domain.NotificationData; import reactor.bus.Event; import reactor.bus.EventBus; diff --git a/spring-reactor/src/main/java/com/baeldung/doman/NotificationData.java b/spring-reactor/src/main/java/com/baeldung/reactorbus/domain/NotificationData.java similarity index 94% rename from spring-reactor/src/main/java/com/baeldung/doman/NotificationData.java rename to spring-reactor/src/main/java/com/baeldung/reactorbus/domain/NotificationData.java index d6d7b02949..65d3559541 100644 --- a/spring-reactor/src/main/java/com/baeldung/doman/NotificationData.java +++ b/spring-reactor/src/main/java/com/baeldung/reactorbus/domain/NotificationData.java @@ -1,4 +1,4 @@ -package com.baeldung.doman; +package com.baeldung.reactorbus.domain; public class NotificationData { diff --git a/spring-reactor/src/main/java/com/baeldung/reactorbus/service/NotificationService.java b/spring-reactor/src/main/java/com/baeldung/reactorbus/service/NotificationService.java new file mode 100644 index 0000000000..dfcd03ed68 --- /dev/null +++ b/spring-reactor/src/main/java/com/baeldung/reactorbus/service/NotificationService.java @@ -0,0 +1,9 @@ +package com.baeldung.reactorbus.service; + +import com.baeldung.reactorbus.domain.NotificationData; + +public interface NotificationService { + + void initiateNotification(NotificationData notificationData) throws InterruptedException; + +} diff --git a/spring-reactor/src/main/java/com/baeldung/service/impl/NotificationServiceimpl.java b/spring-reactor/src/main/java/com/baeldung/reactorbus/service/impl/NotificationServiceimpl.java similarity index 75% rename from spring-reactor/src/main/java/com/baeldung/service/impl/NotificationServiceimpl.java rename to spring-reactor/src/main/java/com/baeldung/reactorbus/service/impl/NotificationServiceimpl.java index bf37741f6a..aa305caaad 100644 --- a/spring-reactor/src/main/java/com/baeldung/service/impl/NotificationServiceimpl.java +++ b/spring-reactor/src/main/java/com/baeldung/reactorbus/service/impl/NotificationServiceimpl.java @@ -1,9 +1,9 @@ -package com.baeldung.service.impl; +package com.baeldung.reactorbus.service.impl; import org.springframework.stereotype.Service; -import com.baeldung.doman.NotificationData; -import com.baeldung.service.NotificationService; +import com.baeldung.reactorbus.domain.NotificationData; +import com.baeldung.reactorbus.service.NotificationService; @Service public class NotificationServiceimpl implements NotificationService { diff --git a/spring-reactor/src/main/java/com/baeldung/service/NotificationService.java b/spring-reactor/src/main/java/com/baeldung/service/NotificationService.java deleted file mode 100644 index f653b2162f..0000000000 --- a/spring-reactor/src/main/java/com/baeldung/service/NotificationService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.service; - -import com.baeldung.doman.NotificationData; - -public interface NotificationService { - - void initiateNotification(NotificationData notificationData) throws InterruptedException; - -} diff --git a/spring-reactor/src/test/java/com/baeldung/DataLoaderLiveTest.java b/spring-reactor/src/test/java/com/baeldung/DataLoaderLiveTest.java deleted file mode 100644 index 5833bc277c..0000000000 --- a/spring-reactor/src/test/java/com/baeldung/DataLoaderLiveTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.springframework.web.client.RestTemplate; - -public class DataLoaderLiveTest { - - @Test - public void exampleTest() { - RestTemplate restTemplate = new RestTemplate(); - restTemplate.getForObject("http://localhost:8080/startNotification/10", String.class); - } - -} diff --git a/spring-reactor/src/test/java/com/baeldung/SpringContextTest.java b/spring-reactor/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..68b6018433 --- /dev/null +++ b/spring-reactor/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.reactorbus.NotificationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NotificationApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-reactor/src/test/java/com/baeldung/reactorbus/NotificationApplicationIntegrationTest.java b/spring-reactor/src/test/java/com/baeldung/reactorbus/NotificationApplicationIntegrationTest.java new file mode 100644 index 0000000000..0adea21fd4 --- /dev/null +++ b/spring-reactor/src/test/java/com/baeldung/reactorbus/NotificationApplicationIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.reactorbus; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class NotificationApplicationIntegrationTest { + + @LocalServerPort + private int port; + + @Test + public void givenAppStarted_whenNotificationTasksSubmitted_thenProcessed() { + RestTemplate restTemplate = new RestTemplate(); + restTemplate.getForObject("http://localhost:" + port + "/startNotification/10", String.class); + } +} diff --git a/spring-reactor/src/test/java/org/baeldung/SpringContextTest.java b/spring-reactor/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 5e68a8e64f..0000000000 --- a/spring-reactor/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} 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 index 1f6181a365..20680d5880 100644 --- a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml @@ -31,7 +31,7 @@ com.caucho hessian - 4.0.38 + ${hessian.version} @@ -58,5 +58,8 @@ + + 4.0.38 + \ No newline at end of file diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 1c6ab77a2d..1d50b4c76c 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -74,7 +74,7 @@ 19.0 - org.baeldung.web.main.Application + com.baeldung.web.main.Application diff --git a/spring-rest-angular/src/main/java/com/baeldung/web/dao/StudentRepository.java b/spring-rest-angular/src/main/java/com/baeldung/web/dao/StudentRepository.java new file mode 100644 index 0000000000..b69cf6f552 --- /dev/null +++ b/spring-rest-angular/src/main/java/com/baeldung/web/dao/StudentRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.web.dao; + +import com.baeldung.web.entity.Student; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface StudentRepository extends JpaRepository +{ + +} diff --git a/spring-rest-angular/src/main/java/com/baeldung/web/entity/Student.java b/spring-rest-angular/src/main/java/com/baeldung/web/entity/Student.java new file mode 100644 index 0000000000..849b35cf24 --- /dev/null +++ b/spring-rest-angular/src/main/java/com/baeldung/web/entity/Student.java @@ -0,0 +1,69 @@ +package com.baeldung.web.entity; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Student implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public Student() { + } + + public Student(long id, String name, String gender, Integer age) { + super(); + this.id = id; + this.name = name; + this.gender = gender; + this.age = age; + } + + @Id + private long id; + @Column(nullable = false) + private String name; + @Column(nullable = false) + private String gender; + @Column(nullable = false) + private Integer age; + + 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 getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + +} diff --git a/spring-rest-angular/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-angular/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java new file mode 100644 index 0000000000..ae9c4543ec --- /dev/null +++ b/spring-rest-angular/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java @@ -0,0 +1,26 @@ +package com.baeldung.web.exception; + +public class MyResourceNotFoundException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 4088649120307193208L; + + public MyResourceNotFoundException() { + super(); + } + + public MyResourceNotFoundException(final String message, final Throwable cause) { + super(message, cause); + } + + public MyResourceNotFoundException(final String message) { + super(message); + } + + public MyResourceNotFoundException(final Throwable cause) { + super(cause); + } + +} diff --git a/spring-rest-angular/src/main/java/com/baeldung/web/main/Application.java b/spring-rest-angular/src/main/java/com/baeldung/web/main/Application.java new file mode 100644 index 0000000000..1f3f0aec39 --- /dev/null +++ b/spring-rest-angular/src/main/java/com/baeldung/web/main/Application.java @@ -0,0 +1,25 @@ +package com.baeldung.web.main; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.web.filter.ShallowEtagHeaderFilter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@SpringBootApplication +@EnableAutoConfiguration +@Import(PersistenceConfig.class) +public class Application implements WebMvcConfigurer { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { + return new ShallowEtagHeaderFilter(); + } + +} diff --git a/spring-rest-angular/src/main/java/com/baeldung/web/main/PersistenceConfig.java b/spring-rest-angular/src/main/java/com/baeldung/web/main/PersistenceConfig.java new file mode 100644 index 0000000000..b964c753d2 --- /dev/null +++ b/spring-rest-angular/src/main/java/com/baeldung/web/main/PersistenceConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.web.main; + +import javax.sql.DataSource; + +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +@EnableJpaRepositories("com.baeldung.web.dao") +@ComponentScan(basePackages = { "com.baeldung.web" }) +@EntityScan("com.baeldung.web.entity") +@Configuration +public class PersistenceConfig { + + @Bean + public JdbcTemplate getJdbcTemplate() { + return new JdbcTemplate(dataSource()); + } + + @Bean + public DataSource dataSource() { + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); + EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL).build(); + return db; + } + +} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java b/spring-rest-angular/src/main/java/com/baeldung/web/rest/StudentDirectoryRestController.java similarity index 83% rename from spring-rest-angular/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java rename to spring-rest-angular/src/main/java/com/baeldung/web/rest/StudentDirectoryRestController.java index dc295a3d97..6197279384 100644 --- a/spring-rest-angular/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java +++ b/spring-rest-angular/src/main/java/com/baeldung/web/rest/StudentDirectoryRestController.java @@ -1,8 +1,8 @@ -package org.baeldung.web.rest; +package com.baeldung.web.rest; -import org.baeldung.web.entity.Student; -import org.baeldung.web.exception.MyResourceNotFoundException; -import org.baeldung.web.service.StudentService; +import com.baeldung.web.entity.Student; +import com.baeldung.web.exception.MyResourceNotFoundException; +import com.baeldung.web.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/spring-rest-angular/src/main/java/com/baeldung/web/service/IOperations.java b/spring-rest-angular/src/main/java/com/baeldung/web/service/IOperations.java new file mode 100644 index 0000000000..60cb4382f4 --- /dev/null +++ b/spring-rest-angular/src/main/java/com/baeldung/web/service/IOperations.java @@ -0,0 +1,9 @@ +package com.baeldung.web.service; + +import org.springframework.data.domain.Page; + +public interface IOperations { + + public Page findPaginated(final int page, final int size); + +} diff --git a/spring-rest-angular/src/main/java/com/baeldung/web/service/StudentService.java b/spring-rest-angular/src/main/java/com/baeldung/web/service/StudentService.java new file mode 100644 index 0000000000..65eb791904 --- /dev/null +++ b/spring-rest-angular/src/main/java/com/baeldung/web/service/StudentService.java @@ -0,0 +1,7 @@ +package com.baeldung.web.service; + +import com.baeldung.web.entity.Student; + +public interface StudentService extends IOperations { + +} diff --git a/spring-rest-angular/src/main/java/com/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular/src/main/java/com/baeldung/web/service/StudentServiceImpl.java new file mode 100644 index 0000000000..cacb0e7840 --- /dev/null +++ b/spring-rest-angular/src/main/java/com/baeldung/web/service/StudentServiceImpl.java @@ -0,0 +1,21 @@ +package com.baeldung.web.service; + +import com.baeldung.web.dao.StudentRepository; +import com.baeldung.web.entity.Student; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +@Service +public class StudentServiceImpl implements StudentService { + + @Autowired + private StudentRepository dao; + + @Override + public Page findPaginated(int page, int size) { + return dao.findAll(PageRequest.of(page, size)); + } + +} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/dao/StudentRepository.java b/spring-rest-angular/src/main/java/org/baeldung/web/dao/StudentRepository.java deleted file mode 100644 index 566d95da00..0000000000 --- a/spring-rest-angular/src/main/java/org/baeldung/web/dao/StudentRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.web.dao; - -import org.baeldung.web.entity.Student; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface StudentRepository extends JpaRepository -{ - -} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/entity/Student.java b/spring-rest-angular/src/main/java/org/baeldung/web/entity/Student.java deleted file mode 100644 index 0a0b60d87d..0000000000 --- a/spring-rest-angular/src/main/java/org/baeldung/web/entity/Student.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.baeldung.web.entity; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; - -@Entity -public class Student implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public Student() { - } - - public Student(long id, String name, String gender, Integer age) { - super(); - this.id = id; - this.name = name; - this.gender = gender; - this.age = age; - } - - @Id - private long id; - @Column(nullable = false) - private String name; - @Column(nullable = false) - private String gender; - @Column(nullable = false) - private Integer age; - - 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 getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - -} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-angular/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java deleted file mode 100644 index 740caec59e..0000000000 --- a/spring-rest-angular/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.web.exception; - -public class MyResourceNotFoundException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = 4088649120307193208L; - - public MyResourceNotFoundException() { - super(); - } - - public MyResourceNotFoundException(final String message, final Throwable cause) { - super(message, cause); - } - - public MyResourceNotFoundException(final String message) { - super(message); - } - - public MyResourceNotFoundException(final Throwable cause) { - super(cause); - } - -} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java b/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java deleted file mode 100644 index fd10643c53..0000000000 --- a/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung.web.main; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -import org.springframework.web.filter.ShallowEtagHeaderFilter; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@SpringBootApplication -@EnableAutoConfiguration -@Import(PersistenceConfig.class) -public class Application implements WebMvcConfigurer { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - - @Bean - public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { - return new ShallowEtagHeaderFilter(); - } - -} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/main/PersistenceConfig.java b/spring-rest-angular/src/main/java/org/baeldung/web/main/PersistenceConfig.java deleted file mode 100644 index 0fc6b74892..0000000000 --- a/spring-rest-angular/src/main/java/org/baeldung/web/main/PersistenceConfig.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.baeldung.web.main; - -import javax.sql.DataSource; - -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; - -@EnableJpaRepositories("org.baeldung.web.dao") -@ComponentScan(basePackages = { "org.baeldung.web" }) -@EntityScan("org.baeldung.web.entity") -@Configuration -public class PersistenceConfig { - - @Bean - public JdbcTemplate getJdbcTemplate() { - return new JdbcTemplate(dataSource()); - } - - @Bean - public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL).build(); - return db; - } - -} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/service/IOperations.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/IOperations.java deleted file mode 100644 index 2176c0bb70..0000000000 --- a/spring-rest-angular/src/main/java/org/baeldung/web/service/IOperations.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.web.service; - -import org.springframework.data.domain.Page; - -public interface IOperations { - - public Page findPaginated(final int page, final int size); - -} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentService.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentService.java deleted file mode 100644 index 1b194f76e2..0000000000 --- a/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentService.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.baeldung.web.service; - -import org.baeldung.web.entity.Student; - -public interface StudentService extends IOperations { - -} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentServiceImpl.java deleted file mode 100644 index c7bcdc5bd5..0000000000 --- a/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentServiceImpl.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.web.service; - -import org.baeldung.web.dao.StudentRepository; -import org.baeldung.web.entity.Student; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.stereotype.Service; - -@Service -public class StudentServiceImpl implements StudentService { - - @Autowired - private StudentRepository dao; - - @Override - public Page findPaginated(int page, int size) { - return dao.findAll(new PageRequest(page, size)); - } - -} diff --git a/spring-rest-angular/src/test/java/com/baeldung/SpringContextTest.java b/spring-rest-angular/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ee8c553c76 --- /dev/null +++ b/spring-rest-angular/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import com.baeldung.web.main.Application; +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(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java b/spring-rest-angular/src/test/java/com/baeldung/web/service/StudentServiceIntegrationTest.java similarity index 97% rename from spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java rename to spring-rest-angular/src/test/java/com/baeldung/web/service/StudentServiceIntegrationTest.java index 1473d44b92..654c4ef647 100644 --- a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java +++ b/spring-rest-angular/src/test/java/com/baeldung/web/service/StudentServiceIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.service; +package com.baeldung.web.service; import static io.restassured.RestAssured.given; import static org.hamcrest.core.Is.is; @@ -6,7 +6,7 @@ import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.hamcrest.core.IsEqual.equalTo; import org.apache.commons.lang3.RandomStringUtils; -import org.baeldung.web.main.Application; +import com.baeldung.web.main.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 9136ce43eb..0000000000 --- a/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.web.main.Application; -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(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/CompressingClientHttpRequestInterceptor.java b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/CompressingClientHttpRequestInterceptor.java similarity index 96% rename from spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/CompressingClientHttpRequestInterceptor.java rename to spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/CompressingClientHttpRequestInterceptor.java index 7d5326246d..78b77256af 100644 --- a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/CompressingClientHttpRequestInterceptor.java +++ b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/CompressingClientHttpRequestInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.rest.compress; +package com.baeldung.spring.rest.compress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/GzipUtils.java b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/GzipUtils.java similarity index 96% rename from spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/GzipUtils.java rename to spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/GzipUtils.java index 75420ca6d8..b9731535b2 100644 --- a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/GzipUtils.java +++ b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/GzipUtils.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.rest.compress; +package com.baeldung.spring.rest.compress; import org.apache.commons.codec.Charsets; import org.apache.commons.io.IOUtils; diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/JettyWebServerConfiguration.java b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/JettyWebServerConfiguration.java similarity index 96% rename from spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/JettyWebServerConfiguration.java rename to spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/JettyWebServerConfiguration.java index 784814b04d..8de8e5b523 100644 --- a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/JettyWebServerConfiguration.java +++ b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/JettyWebServerConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.rest.compress; +package com.baeldung.spring.rest.compress; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.gzip.GzipHandler; diff --git a/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/Message.java b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/Message.java new file mode 100644 index 0000000000..24272a4fca --- /dev/null +++ b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/Message.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.rest.compress; + +public class Message { + + private String text; + + public Message() { + } + + public Message(String text) { + this.text = text; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("Message {"); + sb.append("text='").append(text).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/MessageController.java b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/MessageController.java similarity index 96% rename from spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/MessageController.java rename to spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/MessageController.java index 657c3cfec8..2fc2ca8272 100644 --- a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/MessageController.java +++ b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/MessageController.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.rest.compress; +package com.baeldung.spring.rest.compress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/RestTemplateConfiguration.java b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/RestTemplateConfiguration.java similarity index 92% rename from spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/RestTemplateConfiguration.java rename to spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/RestTemplateConfiguration.java index e1d0f985d9..c1e3c89ae9 100644 --- a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/RestTemplateConfiguration.java +++ b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/RestTemplateConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.rest.compress; +package com.baeldung.spring.rest.compress; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/SpringCompressRequestApplication.java b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/SpringCompressRequestApplication.java similarity index 90% rename from spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/SpringCompressRequestApplication.java rename to spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/SpringCompressRequestApplication.java index 3082e3c277..9b1b71979d 100644 --- a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/SpringCompressRequestApplication.java +++ b/spring-rest-compress/src/main/java/com/baeldung/spring/rest/compress/SpringCompressRequestApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.rest.compress; +package com.baeldung.spring.rest.compress; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/Message.java b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/Message.java deleted file mode 100644 index d3450b227c..0000000000 --- a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/Message.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.spring.rest.compress; - -public class Message { - - private String text; - - public Message() { - } - - public Message(String text) { - this.text = text; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("Message {"); - sb.append("text='").append(text).append('\''); - sb.append('}'); - return sb.toString(); - } -} diff --git a/spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/GzipUtilsUnitTest.java b/spring-rest-compress/src/test/java/com/baeldung/spring/rest/compress/GzipUtilsUnitTest.java similarity index 92% rename from spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/GzipUtilsUnitTest.java rename to spring-rest-compress/src/test/java/com/baeldung/spring/rest/compress/GzipUtilsUnitTest.java index d238c9ec7c..431758d358 100644 --- a/spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/GzipUtilsUnitTest.java +++ b/spring-rest-compress/src/test/java/com/baeldung/spring/rest/compress/GzipUtilsUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.rest.compress; +package com.baeldung.spring.rest.compress; import org.junit.Test; diff --git a/spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/MessageControllerUnitTest.java b/spring-rest-compress/src/test/java/com/baeldung/spring/rest/compress/MessageControllerUnitTest.java similarity index 97% rename from spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/MessageControllerUnitTest.java rename to spring-rest-compress/src/test/java/com/baeldung/spring/rest/compress/MessageControllerUnitTest.java index 9658204917..50b2b7ccd7 100644 --- a/spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/MessageControllerUnitTest.java +++ b/spring-rest-compress/src/test/java/com/baeldung/spring/rest/compress/MessageControllerUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.rest.compress; +package com.baeldung.spring.rest.compress; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-rest-hal-browser/pom.xml b/spring-rest-hal-browser/pom.xml index 94ce837b27..adef8bf2b0 100644 --- a/spring-rest-hal-browser/pom.xml +++ b/spring-rest-hal-browser/pom.xml @@ -19,25 +19,25 @@ org.springframework.boot spring-boot-starter-web - 2.0.3.RELEASE + ${spring-boot.version} org.springframework.boot spring-boot-starter-data-jpa - 2.0.3.RELEASE + ${spring-boot.version} org.springframework.data spring-data-rest-hal-browser - 3.0.8.RELEASE + ${spring-data.version} com.h2database h2 - 1.4.197 + ${h2.version} @@ -47,11 +47,19 @@ org.apache.maven.plugins maven-compiler-plugin - 1.8 - 1.8 + ${source.version} + ${target.version} + + 2.0.3.RELEASE + 3.0.8.RELEASE + 1.4.197 + 1.8 + 1.8 + + \ No newline at end of file diff --git a/spring-rest-http/README.md b/spring-rest-http/README.md index 51f5ed4000..35793cb281 100644 --- a/spring-rest-http/README.md +++ b/spring-rest-http/README.md @@ -10,5 +10,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide to UriComponentsBuilder in Spring](https://www.baeldung.com/spring-uricomponentsbuilder) - [How to Set a Header on a Response with Spring 5](https://www.baeldung.com/spring-response-header) - The tests contained for this article rely on the sample application within the [spring-resttemplate](/spring-resttemplate) module - [Returning Custom Status Codes from Spring Controllers](https://www.baeldung.com/spring-mvc-controller-custom-http-status-code) -- [Spring @RequestMapping](https://www.baeldung.com/spring-requestmapping) -- [Guide to DeferredResult in Spring](https://www.baeldung.com/spring-deferred-result) \ No newline at end of file +- [Spring RequestMapping](https://www.baeldung.com/spring-requestmapping) +- [Guide to DeferredResult in Spring](https://www.baeldung.com/spring-deferred-result) +- [Using JSON Patch in Spring REST APIs](https://www.baeldung.com/spring-rest-json-patch) diff --git a/spring-rest-http/pom.xml b/spring-rest-http/pom.xml index c5c6b8d44c..32d2804220 100644 --- a/spring-rest-http/pom.xml +++ b/spring-rest-http/pom.xml @@ -41,12 +41,18 @@ org.springframework.boot spring-boot-starter-test + + com.github.java-json-tools + json-patch + ${jsonpatch.version} + 1.4.9 + 1.12 diff --git a/spring-rest-http/src/main/java/com/baeldung/CustomerSpringBootRestApplication.java b/spring-rest-http/src/main/java/com/baeldung/CustomerSpringBootRestApplication.java new file mode 100644 index 0000000000..2995d4d0dc --- /dev/null +++ b/spring-rest-http/src/main/java/com/baeldung/CustomerSpringBootRestApplication.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CustomerSpringBootRestApplication { + + public static void main(String[] args) { + SpringApplication.run(CustomerSpringBootRestApplication.class, args); + } +} diff --git a/spring-rest-http/src/main/java/com/baeldung/config/MvcConfig.java b/spring-rest-http/src/main/java/com/baeldung/config/MvcConfig.java index ea2c536757..6e8b41bbed 100644 --- a/spring-rest-http/src/main/java/com/baeldung/config/MvcConfig.java +++ b/spring-rest-http/src/main/java/com/baeldung/config/MvcConfig.java @@ -21,7 +21,7 @@ import java.util.List; */ @Configuration @EnableWebMvc -@ComponentScan({ "com.baeldung.web", "com.baeldung.requestmapping" }) +@ComponentScan({ "com.baeldung.web.controller.status", "com.baeldung.requestmapping" }) public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { diff --git a/spring-rest-http/src/main/java/com/baeldung/model/Customer.java b/spring-rest-http/src/main/java/com/baeldung/model/Customer.java new file mode 100644 index 0000000000..e65446c389 --- /dev/null +++ b/spring-rest-http/src/main/java/com/baeldung/model/Customer.java @@ -0,0 +1,79 @@ +package com.baeldung.model; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public class Customer { + private String id; + private String telephone; + private List favorites; + private Map communicationPreferences; + + public Customer() { + } + + public Customer(String id, String telephone, List favorites, Map communicationPreferences) { + this(telephone, favorites, communicationPreferences); + this.id = id; + } + + public Customer(String telephone, List favorites, Map communicationPreferences) { + this.telephone = telephone; + this.favorites = favorites; + this.communicationPreferences = communicationPreferences; + } + + public static Customer fromCustomer(Customer customer) { + return new Customer(customer.getId(), customer.getTelephone(), customer.getFavorites(), customer.getCommunicationPreferences()); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTelephone() { + return telephone; + } + + public void setTelephone(String telephone) { + this.telephone = telephone; + } + + public Map getCommunicationPreferences() { + return communicationPreferences; + } + + public void setCommunicationPreferences(Map communicationPreferences) { + this.communicationPreferences = communicationPreferences; + } + + public List getFavorites() { + return favorites; + } + + public void setFavorites(List favorites) { + this.favorites = favorites; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Customer)) { + return false; + } + Customer customer = (Customer) o; + return Objects.equals(id, customer.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } +} diff --git a/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java b/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java index 90012ed054..cafd9a38e3 100644 --- a/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java +++ b/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java @@ -1,6 +1,8 @@ package com.baeldung.requestmapping; +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.bind.annotation.PathVariable; @@ -70,7 +72,7 @@ public class FooMappingExamplesController { @RequestMapping(value = "/foos", produces = { "application/json", "application/xml" }) @ResponseBody - public String getFoosAsJsonFromREST() { + public String getFoosAsJsonFromBrowser() { return "Get some Foos with Header New"; } @@ -103,8 +105,8 @@ public class FooMappingExamplesController { // --- Ambiguous Mapping @GetMapping(value = "foos/duplicate" ) - public String duplicate() { - return "Duplicate"; + public ResponseEntity duplicate() { + return new ResponseEntity<>("Duplicate", HttpStatus.OK); } // uncomment for exception of type java.lang.IllegalStateException: Ambiguous mapping @@ -114,14 +116,14 @@ public class FooMappingExamplesController { // return "Duplicate"; // } - @GetMapping(value = "foos/duplicate/xml", produces = MediaType.APPLICATION_XML_VALUE) - public String duplicateXml() { - return "Duplicate Xml"; + @GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_XML_VALUE) + public ResponseEntity duplicateXml() { + return new ResponseEntity<>("Duplicate", HttpStatus.OK); } - @GetMapping(value = "foos/duplicate/json", produces = MediaType.APPLICATION_JSON_VALUE) - public String duplicateJson() { - return "Duplicate Json"; + @GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity duplicateJson() { + return new ResponseEntity<>("{\"message\":\"Duplicate\"}", HttpStatus.OK); } } \ No newline at end of file diff --git a/spring-rest-http/src/main/java/com/baeldung/service/CustomerIdGenerator.java b/spring-rest-http/src/main/java/com/baeldung/service/CustomerIdGenerator.java new file mode 100644 index 0000000000..f4afb79852 --- /dev/null +++ b/spring-rest-http/src/main/java/com/baeldung/service/CustomerIdGenerator.java @@ -0,0 +1,6 @@ +package com.baeldung.service; + +public interface CustomerIdGenerator { + int generateNextId(); +} + diff --git a/spring-rest-http/src/main/java/com/baeldung/service/CustomerService.java b/spring-rest-http/src/main/java/com/baeldung/service/CustomerService.java new file mode 100644 index 0000000000..51a6bc7474 --- /dev/null +++ b/spring-rest-http/src/main/java/com/baeldung/service/CustomerService.java @@ -0,0 +1,14 @@ +package com.baeldung.service; + +import com.baeldung.model.Customer; + +import java.util.Optional; + +public interface CustomerService { + + Customer createCustomer(Customer customer); + + Optional findCustomer(String id); + + void updateCustomer(Customer customer); +} diff --git a/spring-rest-http/src/main/java/com/baeldung/service/impl/CustomerIdGeneratorImpl.java b/spring-rest-http/src/main/java/com/baeldung/service/impl/CustomerIdGeneratorImpl.java new file mode 100644 index 0000000000..471fe880b8 --- /dev/null +++ b/spring-rest-http/src/main/java/com/baeldung/service/impl/CustomerIdGeneratorImpl.java @@ -0,0 +1,17 @@ +package com.baeldung.service.impl; + +import com.baeldung.service.CustomerIdGenerator; + +import org.springframework.stereotype.Component; + +import java.util.concurrent.atomic.AtomicInteger; + +@Component +public class CustomerIdGeneratorImpl implements CustomerIdGenerator { + private static final AtomicInteger SEQUENCE = new AtomicInteger(); + + @Override + public int generateNextId() { + return SEQUENCE.incrementAndGet(); + } +} diff --git a/spring-rest-http/src/main/java/com/baeldung/service/impl/CustomerServiceImpl.java b/spring-rest-http/src/main/java/com/baeldung/service/impl/CustomerServiceImpl.java new file mode 100644 index 0000000000..c57e95deed --- /dev/null +++ b/spring-rest-http/src/main/java/com/baeldung/service/impl/CustomerServiceImpl.java @@ -0,0 +1,42 @@ +package com.baeldung.service.impl; + +import com.baeldung.model.Customer; +import com.baeldung.service.CustomerIdGenerator; +import com.baeldung.service.CustomerService; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@Service +public class CustomerServiceImpl implements CustomerService { + private CustomerIdGenerator customerIdGenerator; + private List customers = new ArrayList<>(); + + @Autowired + public CustomerServiceImpl(CustomerIdGenerator customerIdGenerator) { + this.customerIdGenerator = customerIdGenerator; + } + + @Override + public Customer createCustomer(Customer customer) { + customer.setId(Integer.toString(customerIdGenerator.generateNextId())); + customers.add(customer); + return customer; + } + + @Override + public Optional findCustomer(String id) { + return customers.stream() + .filter(customer -> customer.getId().equals(id)) + .findFirst(); + } + + @Override + public void updateCustomer(Customer customer) { + customers.set(customers.indexOf(customer), customer); + } +} diff --git a/spring-rest-http/src/main/java/com/baeldung/web/controller/customer/CustomerRestController.java b/spring-rest-http/src/main/java/com/baeldung/web/controller/customer/CustomerRestController.java new file mode 100644 index 0000000000..edae10de27 --- /dev/null +++ b/spring-rest-http/src/main/java/com/baeldung/web/controller/customer/CustomerRestController.java @@ -0,0 +1,69 @@ +package com.baeldung.web.controller.customer; + +import com.baeldung.model.Customer; +import com.baeldung.service.CustomerService; +import com.baeldung.web.exception.CustomerNotFoundException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.fge.jsonpatch.JsonPatch; +import com.github.fge.jsonpatch.JsonPatchException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PatchMapping; +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 org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.net.URI; + +import javax.validation.Valid; + +@RestController +@RequestMapping(value = "/customers") +public class CustomerRestController { + private CustomerService customerService; + private ObjectMapper objectMapper = new ObjectMapper(); + + @Autowired + public CustomerRestController(CustomerService customerService) { + this.customerService = customerService; + } + + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity createCustomer(@RequestBody Customer customer) { + Customer customerCreated = customerService.createCustomer(customer); + URI location = ServletUriComponentsBuilder.fromCurrentRequest() + .path("/{id}") + .buildAndExpand(customerCreated.getId()) + .toUri(); + return ResponseEntity.created(location).build(); + } + + @PatchMapping(path = "/{id}", consumes = "application/json-patch+json") + public ResponseEntity updateCustomer(@PathVariable String id, + @RequestBody JsonPatch patch) { + try { + Customer customer = customerService.findCustomer(id).orElseThrow(CustomerNotFoundException::new); + Customer customerPatched = applyPatchToCustomer(patch, customer); + customerService.updateCustomer(customerPatched); + + return ResponseEntity.ok(customerPatched); + } catch (CustomerNotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } catch (JsonPatchException | JsonProcessingException e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } + } + + private Customer applyPatchToCustomer(JsonPatch patch, Customer targetCustomer) throws JsonPatchException, JsonProcessingException { + JsonNode patched = patch.apply(objectMapper.convertValue(targetCustomer, JsonNode.class)); + return objectMapper.treeToValue(patched, Customer.class); + } +} diff --git a/spring-rest-http/src/main/java/com/baeldung/web/exception/CustomerNotFoundException.java b/spring-rest-http/src/main/java/com/baeldung/web/exception/CustomerNotFoundException.java new file mode 100644 index 0000000000..c843696402 --- /dev/null +++ b/spring-rest-http/src/main/java/com/baeldung/web/exception/CustomerNotFoundException.java @@ -0,0 +1,5 @@ +package com.baeldung.web.exception; + +public class CustomerNotFoundException extends RuntimeException { + +} diff --git a/spring-rest-http/src/test/java/com/baeldung/requestmapping/FooMappingExamplesControllerUnitTest.java b/spring-rest-http/src/test/java/com/baeldung/requestmapping/FooMappingExamplesControllerUnitTest.java new file mode 100644 index 0000000000..388b4b7354 --- /dev/null +++ b/spring-rest-http/src/test/java/com/baeldung/requestmapping/FooMappingExamplesControllerUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.requestmapping; + +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.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringRunner.class) +@WebMvcTest(FooMappingExamplesController.class) +public class FooMappingExamplesControllerUnitTest { + + @Autowired + private MockMvc mvc; + + @Test + public void givenAcceptsJson_whenGetDuplicate_thenJsonResponseReturned() throws Exception { + mvc.perform(get("/ex/foos/duplicate") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("{\"message\":\"Duplicate\"}")); + } + + @Test + public void givenAcceptsXml_whenGetDuplicate_thenXmlResponseReturned() throws Exception { + mvc.perform(get("/ex/foos/duplicate") + .accept(MediaType.APPLICATION_XML)) + .andExpect(status().isOk()) + .andExpect(content().string("Duplicate")); + } +} diff --git a/spring-rest-http/src/test/java/com/baeldung/service/impl/CustomerIdGeneratorImplUnitTest.java b/spring-rest-http/src/test/java/com/baeldung/service/impl/CustomerIdGeneratorImplUnitTest.java new file mode 100644 index 0000000000..a855c1cda2 --- /dev/null +++ b/spring-rest-http/src/test/java/com/baeldung/service/impl/CustomerIdGeneratorImplUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.service.impl; + +import com.baeldung.service.CustomerIdGenerator; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CustomerIdGeneratorImplUnitTest { + + @Test + public void givenIdGeneratedPreviously_whenGenerated_thenIdIsIncremented(){ + CustomerIdGenerator customerIdGenerator = new CustomerIdGeneratorImpl(); + int firstId = customerIdGenerator.generateNextId(); + assertThat(customerIdGenerator.generateNextId()).isEqualTo(++firstId); + } +} diff --git a/spring-rest-http/src/test/java/com/baeldung/service/impl/CustomerServiceImplUnitTest.java b/spring-rest-http/src/test/java/com/baeldung/service/impl/CustomerServiceImplUnitTest.java new file mode 100644 index 0000000000..27f0b35714 --- /dev/null +++ b/spring-rest-http/src/test/java/com/baeldung/service/impl/CustomerServiceImplUnitTest.java @@ -0,0 +1,94 @@ +package com.baeldung.service.impl; + + +import com.baeldung.model.Customer; +import com.baeldung.service.CustomerIdGenerator; +import com.baeldung.service.CustomerService; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.HashMap; +import java.util.Map; + + +import static com.baeldung.model.Customer.fromCustomer; +import static java.util.Arrays.asList; +import static java.util.Optional.empty; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; + +@RunWith(MockitoJUnitRunner.class) +public class CustomerServiceImplUnitTest { + + @Mock + private CustomerIdGenerator mockCustomerIdGenerator; + + private CustomerService customerService; + + @Before + public void setup() { + customerService = new CustomerServiceImpl(mockCustomerIdGenerator); + } + + @Test + public void whenCustomerIsCreated_thenNewCustomerDetailsAreCorrect() { + Map communicationPreferences = new HashMap<>(); + communicationPreferences.put("post", true); + communicationPreferences.put("email", true); + Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences); + given(mockCustomerIdGenerator.generateNextId()).willReturn(1); + + Customer newCustomer = customerService.createCustomer(customer); + + assertThat(newCustomer.getId()).isEqualTo("1"); + assertThat(newCustomer.getTelephone()).isEqualTo("001-555-1234"); + assertThat(newCustomer.getFavorites()).containsExactly("Milk", "Eggs"); + assertThat(newCustomer.getCommunicationPreferences()).isEqualTo(communicationPreferences); + } + + @Test + public void givenNonExistentCustomer_whenCustomerIsLookedUp_thenCustomerCanNotBeFound() { + assertThat(customerService.findCustomer("CUST12345")).isEqualTo(empty()); + } + + @Test + public void whenCustomerIsCreated_thenCustomerCanBeFound() { + Map communicationPreferences = new HashMap<>(); + communicationPreferences.put("post", true); + communicationPreferences.put("email", true); + Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences); + given(mockCustomerIdGenerator.generateNextId()).willReturn(7890); + + customerService.createCustomer(customer); + Customer lookedUpCustomer = customerService.findCustomer("7890").get(); + + assertThat(lookedUpCustomer.getId()).isEqualTo("7890"); + assertThat(lookedUpCustomer.getTelephone()).isEqualTo("001-555-1234"); + assertThat(lookedUpCustomer.getFavorites()).containsExactly("Milk", "Eggs"); + assertThat(lookedUpCustomer.getCommunicationPreferences()).isEqualTo(communicationPreferences); + } + + @Test + public void whenCustomerUpdated_thenDetailsUpdatedCorrectly() { + given(mockCustomerIdGenerator.generateNextId()).willReturn(7890); + Map communicationPreferences = new HashMap<>(); + communicationPreferences.put("post", true); + communicationPreferences.put("email", true); + Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences); + Customer newCustomer = customerService.createCustomer(customer); + + Customer customerWithUpdates = fromCustomer(newCustomer); + customerWithUpdates.setTelephone("001-555-6789"); + customerService.updateCustomer(customerWithUpdates); + Customer lookedUpCustomer = customerService.findCustomer("7890").get(); + + assertThat(lookedUpCustomer.getId()).isEqualTo("7890"); + assertThat(lookedUpCustomer.getTelephone()).isEqualTo("001-555-6789"); + assertThat(lookedUpCustomer.getFavorites()).containsExactly("Milk", "Eggs"); + assertThat(lookedUpCustomer.getCommunicationPreferences()).isEqualTo(communicationPreferences); + } +} \ No newline at end of file diff --git a/spring-rest-http/src/test/java/com/baeldung/web/controller/customer/CustomerRestControllerIntegrationTest.java b/spring-rest-http/src/test/java/com/baeldung/web/controller/customer/CustomerRestControllerIntegrationTest.java new file mode 100644 index 0000000000..535bcb1904 --- /dev/null +++ b/spring-rest-http/src/test/java/com/baeldung/web/controller/customer/CustomerRestControllerIntegrationTest.java @@ -0,0 +1,72 @@ +package com.baeldung.web.controller.customer; + +import com.baeldung.model.Customer; +import com.baeldung.service.CustomerService; + +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.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.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static java.util.Collections.emptyList; +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class CustomerRestControllerIntegrationTest { + + @Autowired + private CustomerService customerService; + + @Autowired + private TestRestTemplate testRestTemplate; + + @Before + public void setup() { + testRestTemplate.getRestTemplate().setRequestFactory(new HttpComponentsClientHttpRequestFactory()); + } + + @Test + public void givenExistingCustomer_whenPatched_thenOnlyPatchedFieldsUpdated() { + Map communicationPreferences = new HashMap<>(); + communicationPreferences.put("post", true); + communicationPreferences.put("email", true); + Customer newCustomer = new Customer("001-555-1234", Arrays.asList("Milk", "Eggs"), + communicationPreferences); + Customer customer = customerService.createCustomer(newCustomer); + + + String patchBody = "[ { \"op\": \"replace\", \"path\": \"/telephone\", \"value\": \"001-555-5678\" },\n" + + "{\"op\": \"add\", \"path\": \"/favorites/0\", \"value\": \"Bread\" }]"; + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.valueOf("application/json-patch+json")); + ResponseEntity patchResponse + = testRestTemplate.exchange("/customers/{id}", + HttpMethod.PATCH, + new HttpEntity<>(patchBody, headers), + Customer.class, + customer.getId()); + + Customer customerPatched = patchResponse.getBody(); + assertThat(patchResponse.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(customerPatched.getId()).isEqualTo(customer.getId()); + assertThat(customerPatched.getTelephone()).isEqualTo("001-555-5678"); + assertThat(customerPatched.getCommunicationPreferences().get("post")).isTrue(); + assertThat(customerPatched.getCommunicationPreferences().get("email")).isTrue(); + assertThat(customerPatched.getFavorites()).containsExactly("Bread", "Milk", "Eggs"); + } +} diff --git a/spring-rest-http/src/test/java/com/baeldung/web/controller/customer/CustomerRestControllerUnitTest.java b/spring-rest-http/src/test/java/com/baeldung/web/controller/customer/CustomerRestControllerUnitTest.java new file mode 100644 index 0000000000..6b1293e2c1 --- /dev/null +++ b/spring-rest-http/src/test/java/com/baeldung/web/controller/customer/CustomerRestControllerUnitTest.java @@ -0,0 +1,101 @@ +package com.baeldung.web.controller.customer; + +import com.baeldung.model.Customer; +import com.baeldung.service.CustomerService; + +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.boot.test.mock.mockito.MockBean; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.HashMap; +import java.util.Map; + +import static java.util.Arrays.asList; +import static java.util.Optional.empty; +import static java.util.Optional.of; +import static org.hamcrest.CoreMatchers.is; +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern; +import static org.springframework.http.MediaType.APPLICATION_JSON; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureMockMvc +public class CustomerRestControllerUnitTest { + + private static final String APPLICATION_JSON_PATCH_JSON = "application/json-patch+json"; + + @Autowired + private MockMvc mvc; + + @MockBean + private CustomerService mockCustomerService; + + @Autowired + ApplicationContext context; + + @Test + public void whenCustomerCreated_then201ReturnedWithNewCustomerLocation() throws Exception { + Map communicationPreferences = new HashMap<>(); + communicationPreferences.put("post", true); + communicationPreferences.put("email", true); + Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences); + + Customer persistedCustomer = Customer.fromCustomer(customer); + persistedCustomer.setId("1"); + + given(mockCustomerService.createCustomer(customer)).willReturn(persistedCustomer); + + String createCustomerRequestBody = "{" + + "\"telephone\": \"001-555-1234\",\n" + + "\"favorites\": [\"Milk\", \"Eggs\"],\n" + + "\"communicationPreferences\": {\"post\":true, \"email\":true}\n" + + "}"; + mvc.perform(post("/customers") + .contentType(APPLICATION_JSON) + .content(createCustomerRequestBody)) + .andExpect(status().isCreated()) + .andExpect(redirectedUrlPattern("http://*/customers/1")); + } + + @Test + public void givenNonExistentCustomer_whenPatched_then404Returned() throws Exception { + given(mockCustomerService.findCustomer("1")).willReturn(empty()); + + String patchInstructions = "[{\"op\":\"replace\",\"path\": \"/telephone\",\"value\":\"001-555-5678\"}]"; + mvc.perform(patch("/customers/1") + .contentType(APPLICATION_JSON_PATCH_JSON) + .content(patchInstructions)) + .andExpect(status().isNotFound()); + } + + @Test + public void givenExistingCustomer_whenPatched_thenReturnPatchedCustomer() throws Exception { + Map communicationPreferences = new HashMap<>(); + communicationPreferences.put("post", true); + communicationPreferences.put("email", true); + Customer customer = new Customer("1", "001-555-1234", asList("Milk", "Eggs"), communicationPreferences); + + given(mockCustomerService.findCustomer("1")).willReturn(of(customer)); + + String patchInstructions = "[{\"op\":\"replace\",\"path\": \"/telephone\",\"value\":\"001-555-5678\"}]"; + mvc.perform(patch("/customers/1") + .contentType(APPLICATION_JSON_PATCH_JSON) + .content(patchInstructions)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is("1"))) + .andExpect(jsonPath("$.telephone", is("001-555-5678"))) + .andExpect(jsonPath("$.favorites", is(asList("Milk", "Eggs")))) + .andExpect(jsonPath("$.communicationPreferences", is(communicationPreferences))); + } +} diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index 25b149367e..2423528743 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -206,15 +206,9 @@ test - - - - - - org.hamcrest - hamcrest-library + hamcrest test diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index 59f7a94b8d..291053c87f 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -139,12 +139,7 @@ org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library + hamcrest test diff --git a/spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java b/spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java index db7cb66f87..0e8f9caf03 100644 --- a/spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java @@ -331,7 +331,7 @@ public final class FooProtos { return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.web.dto.FooProtos.Foo.class, com.baeldung.web.dto.FooProtos.Foo.Builder.class); } - // Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder() + // Construct using com.baeldung.web.dto.FooProtos.Foo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } @@ -581,7 +581,7 @@ public final class FooProtos { private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { - java.lang.String[] descriptorData = { "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024org.baeldung.web" + ".dtoB\tFooProtos" }; + java.lang.String[] descriptorData = { "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024com.baeldung.web" + ".dtoB\tFooProtos" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors(com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; diff --git a/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 5e68a8e64f..0000000000 --- a/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-rest-testing/pom.xml b/spring-rest-testing/pom.xml index dcd8b677be..d807459cad 100644 --- a/spring-rest-testing/pom.xml +++ b/spring-rest-testing/pom.xml @@ -177,14 +177,9 @@ test - - - - - org.hamcrest - hamcrest-library + hamcrest test diff --git a/spring-rest-testing/src/main/java/com/baeldung/persistence/IOperations.java b/spring-rest-testing/src/main/java/com/baeldung/persistence/IOperations.java new file mode 100644 index 0000000000..73100ec64f --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/persistence/IOperations.java @@ -0,0 +1,22 @@ +package com.baeldung.persistence; + +import java.io.Serializable; +import java.util.List; + +public interface IOperations { + + // read - one + + T findOne(final long id); + + // read - all + + List findAll(); + + // write + + T create(final T entity); + + T update(final T entity); + +} diff --git a/spring-rest-testing/src/main/java/com/baeldung/persistence/dao/IFooDao.java b/spring-rest-testing/src/main/java/com/baeldung/persistence/dao/IFooDao.java new file mode 100644 index 0000000000..8d47d2eb42 --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/persistence/dao/IFooDao.java @@ -0,0 +1,11 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.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-rest-testing/src/main/java/com/baeldung/persistence/model/Foo.java b/spring-rest-testing/src/main/java/com/baeldung/persistence/model/Foo.java new file mode 100644 index 0000000000..9af3d07bed --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/persistence/model/Foo.java @@ -0,0 +1,83 @@ +package com.baeldung.persistence.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false) + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + 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; + } + + // + + @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-rest-testing/src/main/java/com/baeldung/persistence/model/User.java b/spring-rest-testing/src/main/java/com/baeldung/persistence/model/User.java new file mode 100644 index 0000000000..dbc2b9360f --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/persistence/model/User.java @@ -0,0 +1,94 @@ +package com.baeldung.persistence.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String firstName; + + private String lastName; + + private String email; + + private int age; + + public User() { + super(); + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(final String username) { + email = username; + } + + public int getAge() { + return age; + } + + public void setAge(final int age) { + this.age = age; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final User user = (User) obj; + return email.equals(user.email); + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); + return builder.toString(); + } + +} \ No newline at end of file diff --git a/spring-rest-testing/src/main/java/com/baeldung/persistence/service/IFooService.java b/spring-rest-testing/src/main/java/com/baeldung/persistence/service/IFooService.java new file mode 100644 index 0000000000..15330550a1 --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/persistence/service/IFooService.java @@ -0,0 +1,10 @@ +package com.baeldung.persistence.service; + +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.IOperations; + +public interface IFooService extends IOperations { + + Foo retrieveByName(String name); + +} diff --git a/spring-rest-testing/src/main/java/com/baeldung/persistence/service/common/AbstractService.java b/spring-rest-testing/src/main/java/com/baeldung/persistence/service/common/AbstractService.java new file mode 100644 index 0000000000..5a5d9d6241 --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/persistence/service/common/AbstractService.java @@ -0,0 +1,45 @@ +package com.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import com.baeldung.persistence.IOperations; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.transaction.annotation.Transactional; + +import com.google.common.collect.Lists; + +@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()); + } + + // write + + @Override + public T create(final T entity) { + return getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + protected abstract PagingAndSortingRepository getDao(); + +} diff --git a/spring-rest-testing/src/main/java/com/baeldung/persistence/service/impl/FooService.java b/spring-rest-testing/src/main/java/com/baeldung/persistence/service/impl/FooService.java new file mode 100644 index 0000000000..92fb6c28a0 --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/persistence/service/impl/FooService.java @@ -0,0 +1,37 @@ +package com.baeldung.persistence.service.impl; + +import com.baeldung.persistence.dao.IFooDao; +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IFooService; +import com.baeldung.persistence.service.common.AbstractService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@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); + } + +} diff --git a/spring-rest-testing/src/main/java/com/baeldung/spring/Application.java b/spring-rest-testing/src/main/java/com/baeldung/spring/Application.java new file mode 100644 index 0000000000..c35c4d7e5e --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/spring/Application.java @@ -0,0 +1,41 @@ +package com.baeldung.spring; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.context.request.RequestContextListener; + +/** + * Main Application Class - uses Spring Boot. Just run this as a normal Java + * class to run up a Jetty Server (on http://localhost:8082/spring-rest-full) + * + */ +@EnableScheduling +@EnableAutoConfiguration +@ComponentScan("com.baeldung") +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + @Override + public void onStartup(ServletContext sc) throws ServletException { + // Manages the lifecycle of the root application context + sc.addListener(new RequestContextListener()); + } + + public static void main(final String[] args) { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/spring-rest-testing/src/main/java/com/baeldung/spring/PersistenceConfig.java b/spring-rest-testing/src/main/java/com/baeldung/spring/PersistenceConfig.java new file mode 100644 index 0000000000..4a4b9eee3f --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -0,0 +1,85 @@ +package com.baeldung.spring; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) +@ComponentScan({ "com.baeldung.persistence" }) +// @ImportResource("classpath*:springDataPersistenceConfig.xml") +@EnableJpaRepositories(basePackages = "com.baeldung.persistence.dao") +public class PersistenceConfig { + + @Autowired + private Environment env; + + public PersistenceConfig() { + super(); + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + // vendorAdapter.set + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); + + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + +} \ No newline at end of file diff --git a/spring-rest-testing/src/main/java/com/baeldung/spring/WebConfig.java b/spring-rest-testing/src/main/java/com/baeldung/spring/WebConfig.java new file mode 100644 index 0000000000..e35acb0bf0 --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/spring/WebConfig.java @@ -0,0 +1,36 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@ComponentScan("com.baeldung.web") +@EnableWebMvc +public class WebConfig implements WebMvcConfigurer { + + public WebConfig() { + super(); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setPrefix("/WEB-INF/view/"); + viewResolver.setSuffix(".jsp"); + return viewResolver; + } + + // API + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/graph.html"); + registry.addViewController("/homepage.html"); + } + +} \ No newline at end of file diff --git a/spring-rest-testing/src/main/java/com/baeldung/web/controller/FooController.java b/spring-rest-testing/src/main/java/com/baeldung/web/controller/FooController.java new file mode 100644 index 0000000000..b5350c33c1 --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/web/controller/FooController.java @@ -0,0 +1,80 @@ +package com.baeldung.web.controller; + +import java.util.List; + +import javax.servlet.http.HttpServletResponse; + +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IFooService; +import com.baeldung.web.util.RestPreconditions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +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.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +import com.google.common.base.Preconditions; + +@Controller +@RequestMapping(value = "/auth/foos") +public class FooController { + + @Autowired + private IFooService service; + + public FooController() { + super(); + } + + // API + + @RequestMapping(method = RequestMethod.GET, value = "/count") + @ResponseBody + @ResponseStatus(value = HttpStatus.OK) + public long count() { + return 2l; + } + + // read - one + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { + final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); + + return resourceById; + } + + // read - all + + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public List findAll() { + return service.findAll(); + } + + // write + + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { + Preconditions.checkNotNull(resource); + final Foo foo = service.create(resource); + + return foo; + } + + @RequestMapping(method = RequestMethod.HEAD) + @ResponseStatus(HttpStatus.OK) + public void head(final HttpServletResponse resp) { + resp.setContentType(MediaType.APPLICATION_JSON_VALUE); + resp.setHeader("bar", "baz"); + } + +} diff --git a/spring-rest-testing/src/main/java/com/baeldung/web/controller/HomeController.java b/spring-rest-testing/src/main/java/com/baeldung/web/controller/HomeController.java new file mode 100644 index 0000000000..c82911211a --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/web/controller/HomeController.java @@ -0,0 +1,14 @@ +package com.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping(value = "/") +public class HomeController { + + public String index() { + return "homepage"; + } + +} diff --git a/spring-rest-testing/src/main/java/com/baeldung/web/controller/RootController.java b/spring-rest-testing/src/main/java/com/baeldung/web/controller/RootController.java new file mode 100644 index 0000000000..005f6f023b --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/web/controller/RootController.java @@ -0,0 +1,52 @@ +package com.baeldung.web.controller; + +import java.util.Map; + +import com.baeldung.web.metric.IActuatorMetricService; +import com.baeldung.web.metric.IMetricService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping(value = "/auth/") +public class RootController { + + @Autowired + private IMetricService metricService; + + @Autowired + private IActuatorMetricService actMetricService; + + public RootController() { + super(); + } + + // API + + @RequestMapping(value = "/metric", method = RequestMethod.GET) + @ResponseBody + public Map getMetric() { + return metricService.getFullMetric(); + } + + @RequestMapping(value = "/status-metric", method = RequestMethod.GET) + @ResponseBody + public Map getStatusMetric() { + return metricService.getStatusMetric(); + } + + @RequestMapping(value = "/metric-graph", method = RequestMethod.GET) + @ResponseBody + public Object[][] drawMetric() { + final Object[][] result = metricService.getGraphData(); + for (int i = 1; i < result[0].length; i++) { + result[0][i] = result[0][i].toString(); + } + return result; + } + + +} diff --git a/spring-rest-testing/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-testing/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java new file mode 100644 index 0000000000..fd002efc28 --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java @@ -0,0 +1,21 @@ +package com.baeldung.web.exception; + +public final class MyResourceNotFoundException extends RuntimeException { + + public MyResourceNotFoundException() { + super(); + } + + public MyResourceNotFoundException(final String message, final Throwable cause) { + super(message, cause); + } + + public MyResourceNotFoundException(final String message) { + super(message); + } + + public MyResourceNotFoundException(final Throwable cause) { + super(cause); + } + +} diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java b/spring-rest-testing/src/main/java/com/baeldung/web/metric/ActuatorMetricService.java similarity index 99% rename from spring-rest-testing/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java rename to spring-rest-testing/src/main/java/com/baeldung/web/metric/ActuatorMetricService.java index 4dcec17b9e..8c26fa04a0 100644 --- a/spring-rest-testing/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java +++ b/spring-rest-testing/src/main/java/com/baeldung/web/metric/ActuatorMetricService.java @@ -1,4 +1,4 @@ -package org.baeldung.web.metric; +package com.baeldung.web.metric; import java.text.SimpleDateFormat; import java.util.ArrayList; diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java b/spring-rest-testing/src/main/java/com/baeldung/web/metric/CustomActuatorMetricService.java similarity index 98% rename from spring-rest-testing/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java rename to spring-rest-testing/src/main/java/com/baeldung/web/metric/CustomActuatorMetricService.java index cf30686e52..ee17825b7c 100644 --- a/spring-rest-testing/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java +++ b/spring-rest-testing/src/main/java/com/baeldung/web/metric/CustomActuatorMetricService.java @@ -1,4 +1,4 @@ -package org.baeldung.web.metric; +package com.baeldung.web.metric; import java.text.SimpleDateFormat; import java.util.ArrayList; diff --git a/spring-rest-testing/src/main/java/com/baeldung/web/metric/IActuatorMetricService.java b/spring-rest-testing/src/main/java/com/baeldung/web/metric/IActuatorMetricService.java new file mode 100644 index 0000000000..60bb43ee00 --- /dev/null +++ b/spring-rest-testing/src/main/java/com/baeldung/web/metric/IActuatorMetricService.java @@ -0,0 +1,5 @@ +package com.baeldung.web.metric; + +public interface IActuatorMetricService { + Object[][] getGraphData(); +} diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java b/spring-rest-testing/src/main/java/com/baeldung/web/metric/ICustomActuatorMetricService.java similarity index 79% rename from spring-rest-testing/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java rename to spring-rest-testing/src/main/java/com/baeldung/web/metric/ICustomActuatorMetricService.java index 19ab7164ac..5126252e27 100644 --- a/spring-rest-testing/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java +++ b/spring-rest-testing/src/main/java/com/baeldung/web/metric/ICustomActuatorMetricService.java @@ -1,4 +1,4 @@ -package org.baeldung.web.metric; +package com.baeldung.web.metric; public interface ICustomActuatorMetricService { diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/metric/IMetricService.java b/spring-rest-testing/src/main/java/com/baeldung/web/metric/IMetricService.java similarity index 86% rename from spring-rest-testing/src/main/java/org/baeldung/web/metric/IMetricService.java rename to spring-rest-testing/src/main/java/com/baeldung/web/metric/IMetricService.java index 902d6ac811..b8dfa60215 100644 --- a/spring-rest-testing/src/main/java/org/baeldung/web/metric/IMetricService.java +++ b/spring-rest-testing/src/main/java/com/baeldung/web/metric/IMetricService.java @@ -1,4 +1,4 @@ -package org.baeldung.web.metric; +package com.baeldung.web.metric; import java.util.Map; diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/metric/MetricFilter.java b/spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricFilter.java similarity index 98% rename from spring-rest-testing/src/main/java/org/baeldung/web/metric/MetricFilter.java rename to spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricFilter.java index 6c2fb0cb39..dee63b226f 100644 --- a/spring-rest-testing/src/main/java/org/baeldung/web/metric/MetricFilter.java +++ b/spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricFilter.java @@ -1,4 +1,4 @@ -package org.baeldung.web.metric; +package com.baeldung.web.metric; import javax.servlet.Filter; import javax.servlet.FilterChain; diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/metric/MetricService.java b/spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricService.java similarity index 99% rename from spring-rest-testing/src/main/java/org/baeldung/web/metric/MetricService.java rename to spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricService.java index 086068ad8f..fd3cccab3e 100644 --- a/spring-rest-testing/src/main/java/org/baeldung/web/metric/MetricService.java +++ b/spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricService.java @@ -1,4 +1,4 @@ -package org.baeldung.web.metric; +package com.baeldung.web.metric; import java.text.SimpleDateFormat; import java.util.Date; diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/util/RestPreconditions.java b/spring-rest-testing/src/main/java/com/baeldung/web/util/RestPreconditions.java similarity index 93% rename from spring-rest-testing/src/main/java/org/baeldung/web/util/RestPreconditions.java rename to spring-rest-testing/src/main/java/com/baeldung/web/util/RestPreconditions.java index 4f2dedcfa0..93a4ef6a33 100644 --- a/spring-rest-testing/src/main/java/org/baeldung/web/util/RestPreconditions.java +++ b/spring-rest-testing/src/main/java/com/baeldung/web/util/RestPreconditions.java @@ -1,9 +1,8 @@ -package org.baeldung.web.util; +package com.baeldung.web.util; +import com.baeldung.web.exception.MyResourceNotFoundException; import org.springframework.http.HttpStatus; -import org.baeldung.web.exception.MyResourceNotFoundException; - /** * Simple static methods to be called at the start of your own methods to verify correct arguments and state. If the Precondition fails, an {@link HttpStatus} code is thrown */ diff --git a/spring-rest-testing/src/main/java/org/baeldung/persistence/IOperations.java b/spring-rest-testing/src/main/java/org/baeldung/persistence/IOperations.java deleted file mode 100644 index 0b617bf7ab..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/persistence/IOperations.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.persistence; - -import java.io.Serializable; -import java.util.List; - -public interface IOperations { - - // read - one - - T findOne(final long id); - - // read - all - - List findAll(); - - // write - - T create(final T entity); - - T update(final T entity); - -} diff --git a/spring-rest-testing/src/main/java/org/baeldung/persistence/dao/IFooDao.java b/spring-rest-testing/src/main/java/org/baeldung/persistence/dao/IFooDao.java deleted file mode 100644 index 230abd0d5f..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/persistence/dao/IFooDao.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.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-rest-testing/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-rest-testing/src/main/java/org/baeldung/persistence/model/Foo.java deleted file mode 100644 index 8e1dee33e8..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/persistence/model/Foo.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.baeldung.persistence.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Foo implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - @Column(nullable = false) - private String name; - - public Foo() { - super(); - } - - public Foo(final String name) { - super(); - - 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; - } - - // - - @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-rest-testing/src/main/java/org/baeldung/persistence/model/User.java b/spring-rest-testing/src/main/java/org/baeldung/persistence/model/User.java deleted file mode 100644 index 670d4a2e74..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/persistence/model/User.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.baeldung.persistence.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String firstName; - - private String lastName; - - private String email; - - private int age; - - public User() { - super(); - } - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(final String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(final String lastName) { - this.lastName = lastName; - } - - public String getEmail() { - return email; - } - - public void setEmail(final String username) { - email = username; - } - - public int getAge() { - return age; - } - - public void setAge(final int age) { - this.age = age; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((email == null) ? 0 : email.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final User user = (User) obj; - return email.equals(user.email); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); - return builder.toString(); - } - -} \ No newline at end of file diff --git a/spring-rest-testing/src/main/java/org/baeldung/persistence/service/IFooService.java b/spring-rest-testing/src/main/java/org/baeldung/persistence/service/IFooService.java deleted file mode 100644 index 60d607b9ef..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/persistence/service/IFooService.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.persistence.service; - -import org.baeldung.persistence.IOperations; -import org.baeldung.persistence.model.Foo; - -public interface IFooService extends IOperations { - - Foo retrieveByName(String name); - -} diff --git a/spring-rest-testing/src/main/java/org/baeldung/persistence/service/common/AbstractService.java b/spring-rest-testing/src/main/java/org/baeldung/persistence/service/common/AbstractService.java deleted file mode 100644 index ceefbbe0e3..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/persistence/service/common/AbstractService.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.baeldung.persistence.service.common; - -import java.io.Serializable; -import java.util.List; - -import org.baeldung.persistence.IOperations; -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.transaction.annotation.Transactional; - -import com.google.common.collect.Lists; - -@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()); - } - - // write - - @Override - public T create(final T entity) { - return getDao().save(entity); - } - - @Override - public T update(final T entity) { - return getDao().save(entity); - } - - protected abstract PagingAndSortingRepository getDao(); - -} diff --git a/spring-rest-testing/src/main/java/org/baeldung/persistence/service/impl/FooService.java b/spring-rest-testing/src/main/java/org/baeldung/persistence/service/impl/FooService.java deleted file mode 100644 index 32fe1bd7e0..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/persistence/service/impl/FooService.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.baeldung.persistence.service.impl; - -import org.baeldung.persistence.dao.IFooDao; -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; -import org.baeldung.persistence.service.common.AbstractService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@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); - } - -} diff --git a/spring-rest-testing/src/main/java/org/baeldung/spring/Application.java b/spring-rest-testing/src/main/java/org/baeldung/spring/Application.java deleted file mode 100644 index ca72a4ef56..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/spring/Application.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.spring; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.web.context.request.RequestContextListener; - -/** - * Main Application Class - uses Spring Boot. Just run this as a normal Java - * class to run up a Jetty Server (on http://localhost:8082/spring-rest-full) - * - */ -@EnableScheduling -@EnableAutoConfiguration -@ComponentScan("org.baeldung") -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(Application.class); - } - - @Override - public void onStartup(ServletContext sc) throws ServletException { - // Manages the lifecycle of the root application context - sc.addListener(new RequestContextListener()); - } - - public static void main(final String[] args) { - SpringApplication.run(Application.class, args); - } - -} \ No newline at end of file diff --git a/spring-rest-testing/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-rest-testing/src/main/java/org/baeldung/spring/PersistenceConfig.java deleted file mode 100644 index f3a87b189e..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.baeldung.spring; - -import java.util.Properties; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.google.common.base.Preconditions; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) -@ComponentScan({ "org.baeldung.persistence" }) -// @ImportResource("classpath*:springDataPersistenceConfig.xml") -@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") -public class PersistenceConfig { - - @Autowired - private Environment env; - - public PersistenceConfig() { - super(); - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - // vendorAdapter.set - em.setJpaVendorAdapter(vendorAdapter); - em.setJpaProperties(additionalProperties()); - - return em; - } - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - public PlatformTransactionManager transactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); - - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - final Properties additionalProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); - return hibernateProperties; - } - -} \ No newline at end of file diff --git a/spring-rest-testing/src/main/java/org/baeldung/spring/WebConfig.java b/spring-rest-testing/src/main/java/org/baeldung/spring/WebConfig.java deleted file mode 100644 index a0db08d93d..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/spring/WebConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -@ComponentScan("org.baeldung.web") -@EnableWebMvc -public class WebConfig implements WebMvcConfigurer { - - public WebConfig() { - super(); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/WEB-INF/view/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } - - // API - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - registry.addViewController("/graph.html"); - registry.addViewController("/homepage.html"); - } - -} \ No newline at end of file diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-testing/src/main/java/org/baeldung/web/controller/FooController.java deleted file mode 100644 index caaf422410..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/web/controller/FooController.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.baeldung.web.controller; - -import java.util.List; - -import javax.servlet.http.HttpServletResponse; - -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; -import org.baeldung.web.util.RestPreconditions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -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.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; - -import com.google.common.base.Preconditions; - -@Controller -@RequestMapping(value = "/auth/foos") -public class FooController { - - @Autowired - private IFooService service; - - public FooController() { - super(); - } - - // API - - @RequestMapping(method = RequestMethod.GET, value = "/count") - @ResponseBody - @ResponseStatus(value = HttpStatus.OK) - public long count() { - return 2l; - } - - // read - one - - @RequestMapping(value = "/{id}", method = RequestMethod.GET) - @ResponseBody - public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { - final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); - - return resourceById; - } - - // read - all - - @RequestMapping(method = RequestMethod.GET) - @ResponseBody - public List findAll() { - return service.findAll(); - } - - // write - - @RequestMapping(method = RequestMethod.POST) - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { - Preconditions.checkNotNull(resource); - final Foo foo = service.create(resource); - - return foo; - } - - @RequestMapping(method = RequestMethod.HEAD) - @ResponseStatus(HttpStatus.OK) - public void head(final HttpServletResponse resp) { - resp.setContentType(MediaType.APPLICATION_JSON_VALUE); - resp.setHeader("bar", "baz"); - } - -} diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-rest-testing/src/main/java/org/baeldung/web/controller/HomeController.java deleted file mode 100644 index 9c4d14cae3..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/web/controller/HomeController.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.web.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping(value = "/") -public class HomeController { - - public String index() { - return "homepage"; - } - -} diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/controller/RootController.java b/spring-rest-testing/src/main/java/org/baeldung/web/controller/RootController.java deleted file mode 100644 index a66f3d1893..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/web/controller/RootController.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.baeldung.web.controller; - -import java.util.Map; - -import org.baeldung.web.metric.IActuatorMetricService; -import org.baeldung.web.metric.IMetricService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -@Controller -@RequestMapping(value = "/auth/") -public class RootController { - - @Autowired - private IMetricService metricService; - - @Autowired - private IActuatorMetricService actMetricService; - - public RootController() { - super(); - } - - // API - - @RequestMapping(value = "/metric", method = RequestMethod.GET) - @ResponseBody - public Map getMetric() { - return metricService.getFullMetric(); - } - - @RequestMapping(value = "/status-metric", method = RequestMethod.GET) - @ResponseBody - public Map getStatusMetric() { - return metricService.getStatusMetric(); - } - - @RequestMapping(value = "/metric-graph", method = RequestMethod.GET) - @ResponseBody - public Object[][] drawMetric() { - final Object[][] result = metricService.getGraphData(); - for (int i = 1; i < result[0].length; i++) { - result[0][i] = result[0][i].toString(); - } - return result; - } - - -} diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-testing/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java deleted file mode 100644 index 14b61f9832..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.web.exception; - -public final class MyResourceNotFoundException extends RuntimeException { - - public MyResourceNotFoundException() { - super(); - } - - public MyResourceNotFoundException(final String message, final Throwable cause) { - super(message, cause); - } - - public MyResourceNotFoundException(final String message) { - super(message); - } - - public MyResourceNotFoundException(final Throwable cause) { - super(cause); - } - -} diff --git a/spring-rest-testing/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java b/spring-rest-testing/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java deleted file mode 100644 index 191d347070..0000000000 --- a/spring-rest-testing/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.web.metric; - -public interface IActuatorMetricService { - Object[][] getGraphData(); -} diff --git a/spring-rest-testing/src/main/resources/springDataPersistenceConfig.xml b/spring-rest-testing/src/main/resources/springDataPersistenceConfig.xml index d6d0ec6e47..5ea2d9c05b 100644 --- a/spring-rest-testing/src/main/resources/springDataPersistenceConfig.xml +++ b/spring-rest-testing/src/main/resources/springDataPersistenceConfig.xml @@ -7,6 +7,6 @@ http://www.springframework.org/schema/data/jpa/spring-jpa.xsd" > - + \ No newline at end of file diff --git a/spring-rest-testing/src/main/webapp/WEB-INF/web.xml b/spring-rest-testing/src/main/webapp/WEB-INF/web.xml index 5f90c3519f..7129b6b4af 100644 --- a/spring-rest-testing/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest-testing/src/main/webapp/WEB-INF/web.xml @@ -16,7 +16,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring @@ -37,7 +37,7 @@ metricFilter - org.baeldung.web.metric.MetricFilter + com.baeldung.web.metric.MetricFilter diff --git a/spring-rest-testing/src/test/java/com/baeldung/Consts.java b/spring-rest-testing/src/test/java/com/baeldung/Consts.java new file mode 100644 index 0000000000..e33efd589e --- /dev/null +++ b/spring-rest-testing/src/test/java/com/baeldung/Consts.java @@ -0,0 +1,5 @@ +package com.baeldung; + +public interface Consts { + int APPLICATION_PORT = 8082; +} diff --git a/spring-rest-testing/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-testing/src/test/java/com/baeldung/SpringContextIntegrationTest.java similarity index 86% rename from spring-rest-testing/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-rest-testing/src/test/java/com/baeldung/SpringContextIntegrationTest.java index 35939c992f..155e05b106 100644 --- a/spring-rest-testing/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-rest-testing/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.spring.Application; +import com.baeldung.spring.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-rest-testing/src/test/java/com/baeldung/SpringContextTest.java b/spring-rest-testing/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e023254719 --- /dev/null +++ b/spring-rest-testing/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import com.baeldung.spring.Application; +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(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-testing/src/test/java/com/baeldung/persistence/PersistenceTestSuite.java b/spring-rest-testing/src/test/java/com/baeldung/persistence/PersistenceTestSuite.java new file mode 100644 index 0000000000..77c74b15e4 --- /dev/null +++ b/spring-rest-testing/src/test/java/com/baeldung/persistence/PersistenceTestSuite.java @@ -0,0 +1,16 @@ +package com.baeldung.persistence; + +import com.baeldung.persistence.service.FooServicePersistenceIntegrationTest; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ + // @formatter:off + + FooServicePersistenceIntegrationTest.class + +}) // +public class PersistenceTestSuite { + +} diff --git a/spring-rest-testing/src/test/java/org/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java b/spring-rest-testing/src/test/java/com/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java similarity index 97% rename from spring-rest-testing/src/test/java/org/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java rename to spring-rest-testing/src/test/java/com/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java index 79889e0f9e..e66e9d49e2 100644 --- a/spring-rest-testing/src/test/java/org/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java +++ b/spring-rest-testing/src/test/java/com/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.service; +package com.baeldung.persistence.service; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.hamcrest.Matchers.hasItem; @@ -11,9 +11,9 @@ import static org.junit.Assert.assertThat; import java.io.Serializable; import java.util.List; -import org.baeldung.persistence.IOperations; -import org.baeldung.persistence.model.Foo; -import org.baeldung.util.IDUtil; +import com.baeldung.util.IDUtil; +import com.baeldung.persistence.IOperations; +import com.baeldung.persistence.model.Foo; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Test; diff --git a/spring-rest-testing/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/spring-rest-testing/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..24f46b9c8f --- /dev/null +++ b/spring-rest-testing/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java @@ -0,0 +1,76 @@ +package com.baeldung.persistence.service; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertNotNull; + +import com.baeldung.persistence.IOperations; +import com.baeldung.persistence.model.Foo; +import com.baeldung.spring.PersistenceConfig; +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.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.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-rest-testing/src/test/java/org/baeldung/util/IDUtil.java b/spring-rest-testing/src/test/java/com/baeldung/util/IDUtil.java similarity index 96% rename from spring-rest-testing/src/test/java/org/baeldung/util/IDUtil.java rename to spring-rest-testing/src/test/java/com/baeldung/util/IDUtil.java index 85ab623e5f..45e72e046d 100644 --- a/spring-rest-testing/src/test/java/org/baeldung/util/IDUtil.java +++ b/spring-rest-testing/src/test/java/com/baeldung/util/IDUtil.java @@ -1,4 +1,4 @@ -package org.baeldung.util; +package com.baeldung.util; import java.util.Random; diff --git a/spring-rest-testing/src/test/java/org/baeldung/Consts.java b/spring-rest-testing/src/test/java/org/baeldung/Consts.java deleted file mode 100644 index e5f0be160f..0000000000 --- a/spring-rest-testing/src/test/java/org/baeldung/Consts.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung; - -public interface Consts { - int APPLICATION_PORT = 8082; -} diff --git a/spring-rest-testing/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-testing/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 8debddc40a..0000000000 --- a/spring-rest-testing/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.Application; -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(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-rest-testing/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java b/spring-rest-testing/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java deleted file mode 100644 index fb0fd00bb5..0000000000 --- a/spring-rest-testing/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.persistence; - -import org.baeldung.persistence.service.FooServicePersistenceIntegrationTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - // @formatter:off - - FooServicePersistenceIntegrationTest.class - -}) // -public class PersistenceTestSuite { - -} diff --git a/spring-rest-testing/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/spring-rest-testing/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java deleted file mode 100644 index 089d2d13a2..0000000000 --- a/spring-rest-testing/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertNotNull; - -import org.baeldung.persistence.IOperations; -import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.PersistenceConfig; -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.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.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-resttemplate/pom.xml b/spring-resttemplate/pom.xml index 0b5d0b20d0..05660f5210 100644 --- a/spring-resttemplate/pom.xml +++ b/spring-resttemplate/pom.xml @@ -125,17 +125,12 @@ junit junit - 4.12 + ${junit.version} org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library + hamcrest test @@ -162,10 +157,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + ${maven.version} - 1.8 - 1.8 + ${source.version} + ${target.version} @@ -308,6 +303,10 @@ 3.4.1 3.5.11 + 1.8 + 1.8 + 4.12 + 3.7.0 diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java similarity index 92% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java index 9a361e92c9..3e4d1ffa00 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate; +package com.baeldung.resttemplate; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java similarity index 95% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java index a39994ae67..bef8af3725 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java similarity index 89% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java index 5e8220d064..75ce02ea04 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import org.springframework.boot.web.client.RestTemplateCustomizer; import org.springframework.web.client.RestTemplate; diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/FooController.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/FooController.java new file mode 100644 index 0000000000..dbef16b592 --- /dev/null +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/FooController.java @@ -0,0 +1,124 @@ +package com.baeldung.resttemplate.configuration; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +import java.net.URI; +import java.util.Collection; +import java.util.Map; + +import com.baeldung.resttemplate.web.dto.Foo; +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.PathVariable; +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.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; + +@Controller +public class FooController { + + private Map fooRepository = Maps.newHashMap(ImmutableMap.of(1L, new Foo(1L, randomAlphabetic(4)))); + + public FooController() { + super(); + } + + @RequestMapping(method = RequestMethod.GET, value = "/foos") + @ResponseBody + public Collection findListOfFoo() { + return fooRepository.values(); + } + + // API - read + + @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") + @ResponseBody + public Foo findById(@PathVariable final long id) throws HttpClientErrorException { + Foo foo = fooRepository.get(id); + + if (foo == null) { + throw new HttpClientErrorException(HttpStatus.NOT_FOUND); + } else { + return foo; + } + } + + // API - write + + @RequestMapping(method = RequestMethod.PUT, value = "/foos/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { + fooRepository.put(id, foo); + return foo; + } + + @RequestMapping(method = RequestMethod.PATCH, value = "/foos/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo patchFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { + fooRepository.put(id, foo); + return foo; + } + + @RequestMapping(method = RequestMethod.POST, value = "/foos") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public ResponseEntity postFoo(@RequestBody final Foo foo) { + + fooRepository.put(foo.getId(), foo); + final URI location = ServletUriComponentsBuilder + .fromCurrentServletMapping() + .path("/foos/{id}") + .build() + .expand(foo.getId()) + .toUri(); + + final HttpHeaders headers = new HttpHeaders(); + headers.setLocation(location); + + final ResponseEntity entity = new ResponseEntity(foo, headers, HttpStatus.CREATED); + return entity; + } + + @RequestMapping(method = RequestMethod.HEAD, value = "/foos") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo headFoo() { + return new Foo(1, randomAlphabetic(4)); + } + + @RequestMapping(method = RequestMethod.POST, value = "/foos/new") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo createFoo(@RequestBody final Foo foo) { + fooRepository.put(foo.getId(), foo); + return foo; + } + + @RequestMapping(method = RequestMethod.DELETE, value = "/foos/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public long deleteFoo(@PathVariable final long id) { + fooRepository.remove(id); + return id; + } + + @RequestMapping(method = RequestMethod.POST, value = "/foos/form") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public String submitFoo(@RequestParam("id") String id) { + return id; + } + +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/HelloController.java similarity index 95% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/HelloController.java index ee404db4f8..854ca1a1c1 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/HelloController.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/SpringConfig.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/SpringConfig.java new file mode 100644 index 0000000000..7866a4abcd --- /dev/null +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/SpringConfig.java @@ -0,0 +1,29 @@ +package com.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; +import org.springframework.web.client.RestTemplate; + +@Configuration +@EnableAutoConfiguration +@ComponentScan("com.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/com/baeldung/resttemplate/lists/service/EmployeeService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java index 226134787f..8a1773483a 100644 --- a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java @@ -7,7 +7,7 @@ import com.baeldung.resttemplate.lists.dto.Employee; import java.util.ArrayList; import java.util.List; -@Service +@Service("EmployeeListService") public class EmployeeService { public List getAllEmployees() diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/controller/PersonAPI.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java similarity index 88% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/controller/PersonAPI.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java index b1b56ec2f3..b3131cc00c 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/controller/PersonAPI.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java @@ -1,9 +1,9 @@ -package org.baeldung.resttemplate.web.controller; +package com.baeldung.resttemplate.web.controller; import javax.servlet.http.HttpServletResponse; -import org.baeldung.resttemplate.web.dto.Person; -import org.baeldung.resttemplate.web.service.PersonService; +import com.baeldung.resttemplate.web.service.PersonService; +import com.baeldung.resttemplate.web.dto.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Foo.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Foo.java new file mode 100644 index 0000000000..ede91dab1a --- /dev/null +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Foo.java @@ -0,0 +1,45 @@ +package com.baeldung.resttemplate.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/com/baeldung/resttemplate/web/dto/Person.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Person.java new file mode 100644 index 0000000000..11e56fc6e2 --- /dev/null +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Person.java @@ -0,0 +1,32 @@ +package com.baeldung.resttemplate.web.dto; + +public class Person { + private Integer id; + private String name; + + public Person() { + + } + + public Person(Integer id, String name) { + this.id = id; + this.name = 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-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/NotFoundException.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/NotFoundException.java new file mode 100644 index 0000000000..8eb217978c --- /dev/null +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/NotFoundException.java @@ -0,0 +1,4 @@ +package com.baeldung.resttemplate.web.exception; + +public class NotFoundException extends RuntimeException { +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java similarity index 92% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java index 214de38746..02260438c7 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java @@ -1,8 +1,8 @@ -package org.baeldung.resttemplate.web.handler; +package com.baeldung.resttemplate.web.handler; import java.io.IOException; -import org.baeldung.resttemplate.web.exception.NotFoundException; +import com.baeldung.resttemplate.web.exception.NotFoundException; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.stereotype.Component; diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Bar.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Bar.java new file mode 100644 index 0000000000..7f8902e2fc --- /dev/null +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Bar.java @@ -0,0 +1,22 @@ +package com.baeldung.resttemplate.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/com/baeldung/resttemplate/web/model/Employee.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Employee.java new file mode 100644 index 0000000000..bb1ad8cbfa --- /dev/null +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Employee.java @@ -0,0 +1,47 @@ +package com.baeldung.resttemplate.web.model; + +import java.util.Objects; + +public class Employee { + + private String id; + private String name; + + public Employee(String id, String name) { + this.id = id; + this.name = name; + } + + public Employee() { + } + + 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; + } + + @Override public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Employee employee = (Employee) o; + return Objects.equals(id, employee.id); + } + + @Override public int hashCode() { + + return Objects.hash(id); + } +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/BarConsumerService.java similarity index 80% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/BarConsumerService.java index 54a66ea591..485143b0a1 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/BarConsumerService.java @@ -1,7 +1,7 @@ -package org.baeldung.resttemplate.web.service; +package com.baeldung.resttemplate.web.service; -import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; -import org.baeldung.resttemplate.web.model.Bar; +import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.model.Bar; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Service; diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java new file mode 100644 index 0000000000..18dff3db1b --- /dev/null +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java @@ -0,0 +1,29 @@ +package com.baeldung.resttemplate.web.service; + +import com.baeldung.resttemplate.web.model.Employee; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +@Service +public class EmployeeService { + + static final String EMP_URL_PREFIX = "http://localhost:8080/employee"; + static final String URL_SEP = "/"; + + private static final Logger logger = LoggerFactory.getLogger(EmployeeService.class); + + @Autowired + private RestTemplate restTemplate; + + public Employee getEmployee(String id) { + + ResponseEntity resp = restTemplate.getForEntity("http://localhost:8080/employee/" + id, + Employee.class); + return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null; + } +} diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java new file mode 100644 index 0000000000..e91d2adc5c --- /dev/null +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java @@ -0,0 +1,10 @@ +package com.baeldung.resttemplate.web.service; + +import com.baeldung.resttemplate.web.dto.Person; + +public interface PersonService { + + public Person saveUpdatePerson(Person person); + + public Person findPersonById(Integer id); +} \ No newline at end of file diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java new file mode 100644 index 0000000000..d7a1bfc2db --- /dev/null +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java @@ -0,0 +1,19 @@ +package com.baeldung.resttemplate.web.service; + +import com.baeldung.resttemplate.web.dto.Person; +import org.springframework.stereotype.Component; + +@Component +public class PersonServiceImpl implements PersonService { + + @Override + public Person saveUpdatePerson(Person person) { + return person; + } + + @Override + public Person findPersonById(Integer id) { + return new Person(id, "John"); + } + +} diff --git a/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java index 11ea5b70c9..5c385edb07 100644 --- a/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java +++ b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java @@ -20,7 +20,7 @@ import com.baeldung.sampleapp.web.dto.Foo; import com.baeldung.sampleapp.web.exception.ResourceNotFoundException; @Controller -@RequestMapping(value = "/foos") +@RequestMapping(value = "/foo") public class MyFooController { private final Map myfoos; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java deleted file mode 100644 index a9d400b199..0000000000 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.baeldung.resttemplate.configuration; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; - -import java.net.URI; -import java.util.Collection; -import java.util.Map; - -import org.baeldung.resttemplate.web.dto.Foo; -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.PathVariable; -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.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; - -@Controller -public class FooController { - - private Map fooRepository = Maps.newHashMap(ImmutableMap.of(1L, new Foo(1L, randomAlphabetic(4)))); - - public FooController() { - super(); - } - - @RequestMapping(method = RequestMethod.GET, value = "/foos") - @ResponseBody - public Collection findListOfFoo() { - return fooRepository.values(); - } - - // API - read - - @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") - @ResponseBody - public Foo findById(@PathVariable final long id) throws HttpClientErrorException { - Foo foo = fooRepository.get(id); - - if (foo == null) { - throw new HttpClientErrorException(HttpStatus.NOT_FOUND); - } else { - return foo; - } - } - - // API - write - - @RequestMapping(method = RequestMethod.PUT, value = "/foos/{id}") - @ResponseStatus(HttpStatus.OK) - @ResponseBody - public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { - fooRepository.put(id, foo); - return foo; - } - - @RequestMapping(method = RequestMethod.PATCH, value = "/foos/{id}") - @ResponseStatus(HttpStatus.OK) - @ResponseBody - public Foo patchFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { - fooRepository.put(id, foo); - return foo; - } - - @RequestMapping(method = RequestMethod.POST, value = "/foos") - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public ResponseEntity postFoo(@RequestBody final Foo foo) { - - fooRepository.put(foo.getId(), foo); - final URI location = ServletUriComponentsBuilder - .fromCurrentServletMapping() - .path("/foos/{id}") - .build() - .expand(foo.getId()) - .toUri(); - - final HttpHeaders headers = new HttpHeaders(); - headers.setLocation(location); - - final ResponseEntity entity = new ResponseEntity(foo, headers, HttpStatus.CREATED); - return entity; - } - - @RequestMapping(method = RequestMethod.HEAD, value = "/foos") - @ResponseStatus(HttpStatus.OK) - @ResponseBody - public Foo headFoo() { - return new Foo(1, randomAlphabetic(4)); - } - - @RequestMapping(method = RequestMethod.POST, value = "/foos/new") - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Foo createFoo(@RequestBody final Foo foo) { - fooRepository.put(foo.getId(), foo); - return foo; - } - - @RequestMapping(method = RequestMethod.DELETE, value = "/foos/{id}") - @ResponseStatus(HttpStatus.OK) - @ResponseBody - public long deleteFoo(@PathVariable final long id) { - fooRepository.remove(id); - return id; - } - - @RequestMapping(method = RequestMethod.POST, value = "/foos/form") - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public String submitFoo(@RequestParam("id") String id) { - return id; - } - -} 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 deleted file mode 100644 index 966d5bcaa1..0000000000 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java +++ /dev/null @@ -1,33 +0,0 @@ -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; -import org.springframework.web.client.RestTemplate; - -@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()); - } - - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } -} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java deleted file mode 100644 index ed0a42c429..0000000000 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.baeldung.resttemplate.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/resttemplate/web/dto/Person.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Person.java deleted file mode 100644 index 4b7679638f..0000000000 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Person.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.baeldung.resttemplate.web.dto; - -public class Person { - private Integer id; - private String name; - - public Person() { - - } - - public Person(Integer id, String name) { - this.id = id; - this.name = 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-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java deleted file mode 100644 index 3e606e9314..0000000000 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.baeldung.resttemplate.web.exception; - -public class NotFoundException extends RuntimeException { -} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java deleted file mode 100644 index cf5279697f..0000000000 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.resttemplate.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/resttemplate/web/model/Employee.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Employee.java deleted file mode 100644 index a9b84a77b4..0000000000 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Employee.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.baeldung.resttemplate.web.model; - -import java.util.Date; -import java.util.Objects; - -public class Employee { - - private String id; - private String name; - - public Employee(String id, String name) { - this.id = id; - this.name = name; - } - - public Employee() { - } - - 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; - } - - @Override public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - Employee employee = (Employee) o; - return Objects.equals(id, employee.id); - } - - @Override public int hashCode() { - - return Objects.hash(id); - } -} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java deleted file mode 100644 index c6562fbc94..0000000000 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.resttemplate.web.service; - -import org.baeldung.resttemplate.web.model.Employee; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -@Service -public class EmployeeService { - - static final String EMP_URL_PREFIX = "http://localhost:8080/employee"; - static final String URL_SEP = "/"; - - private static final Logger logger = LoggerFactory.getLogger(EmployeeService.class); - - @Autowired - private RestTemplate restTemplate; - - public Employee getEmployee(String id) { - - ResponseEntity resp = restTemplate.getForEntity("http://localhost:8080/employee/" + id, - Employee.class); - return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null; - } -} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonService.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonService.java deleted file mode 100644 index c5ad39e101..0000000000 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonService.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.resttemplate.web.service; - -import org.baeldung.resttemplate.web.dto.Person; - -public interface PersonService { - - public Person saveUpdatePerson(Person person); - - public Person findPersonById(Integer id); -} \ No newline at end of file diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonServiceImpl.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonServiceImpl.java deleted file mode 100644 index 658e0fade0..0000000000 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonServiceImpl.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung.resttemplate.web.service; - -import org.baeldung.resttemplate.web.dto.Person; -import org.springframework.stereotype.Component; - -@Component -public class PersonServiceImpl implements PersonService { - - @Override - public Person saveUpdatePerson(Person person) { - return person; - } - - @Override - public Person findPersonById(Integer id) { - return new Person(id, "John"); - } - -} diff --git a/spring-resttemplate/src/main/java/com/baeldung/SpringContextTest.java b/spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/SpringContextTest.java rename to spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-resttemplate/src/test/java/com/baeldung/SpringTestConfig.java b/spring-resttemplate/src/test/java/com/baeldung/SpringTestConfig.java new file mode 100644 index 0000000000..c626d1021d --- /dev/null +++ b/spring-resttemplate/src/test/java/com/baeldung/SpringTestConfig.java @@ -0,0 +1,14 @@ +package com.baeldung; + +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.web.client.RestTemplate; + +@Configuration +@EnableAutoConfiguration +@ComponentScan("com.baeldung") +public class SpringTestConfig { + +} diff --git a/spring-resttemplate/src/test/java/com/baeldung/client/Consts.java b/spring-resttemplate/src/test/java/com/baeldung/client/Consts.java new file mode 100644 index 0000000000..b392c4d199 --- /dev/null +++ b/spring-resttemplate/src/test/java/com/baeldung/client/Consts.java @@ -0,0 +1,5 @@ +package com.baeldung.client; + +public interface Consts { + int APPLICATION_PORT = 8082; +} diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java similarity index 98% rename from spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java index 967c4a6188..9f4b3c9b35 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java @@ -1,10 +1,10 @@ -package org.baeldung.client; +package com.baeldung.client; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; -import org.baeldung.resttemplate.web.dto.Foo; +import com.baeldung.resttemplate.web.dto.Foo; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.web.client.TestRestTemplate; diff --git a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java similarity index 99% rename from spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java rename to spring-resttemplate/src/test/java/com/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java index 21639818db..eb5d01d06f 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate; +package com.baeldung.resttemplate; import org.assertj.core.api.Assertions; import org.junit.Assert; diff --git a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java similarity index 98% rename from spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java index 54e416d008..0dab124316 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java @@ -1,7 +1,7 @@ -package org.baeldung.resttemplate; +package com.baeldung.resttemplate; import static org.apache.commons.codec.binary.Base64.encodeBase64; -import static org.baeldung.client.Consts.APPLICATION_PORT; +import static com.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; @@ -14,8 +14,8 @@ import java.net.URI; import java.util.Arrays; import java.util.Set; -import org.baeldung.resttemplate.web.dto.Foo; -import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.dto.Foo; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpEntity; diff --git a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/postjson/PersonAPILiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java similarity index 95% rename from spring-resttemplate/src/test/java/org/baeldung/resttemplate/postjson/PersonAPILiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java index 1347cb0c7a..f1861ede92 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/postjson/PersonAPILiveTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.resttemplate.postjson; +package com.baeldung.resttemplate.postjson; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.URI; -import org.baeldung.resttemplate.RestTemplateConfigurationApplication; -import org.baeldung.resttemplate.web.dto.Person; +import com.baeldung.resttemplate.RestTemplateConfigurationApplication; +import com.baeldung.resttemplate.web.dto.Person; import org.json.JSONException; import org.json.JSONObject; import org.junit.BeforeClass; diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java similarity index 89% rename from spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java index 60069cea71..688b6e9d56 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.web.handler; +package com.baeldung.web.handler; -import org.baeldung.resttemplate.web.exception.NotFoundException; -import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; -import org.baeldung.resttemplate.web.model.Bar; +import com.baeldung.resttemplate.web.exception.NotFoundException; +import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.model.Bar; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java similarity index 88% rename from spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java index f93ba71666..ee01cb6a50 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.service; +package com.baeldung.web.service; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; @@ -6,9 +6,9 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat import java.net.URI; -import org.baeldung.SpringTestConfig; -import org.baeldung.resttemplate.web.model.Employee; -import org.baeldung.resttemplate.web.service.EmployeeService; +import com.baeldung.SpringTestConfig; +import com.baeldung.resttemplate.web.model.Employee; +import com.baeldung.resttemplate.web.service.EmployeeService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -16,6 +16,7 @@ import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -28,7 +29,7 @@ import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringRunner.class) -@ContextConfiguration(classes = SpringTestConfig.class) +@SpringBootTest(classes = SpringTestConfig.class) public class EmployeeServiceMockRestServiceServerUnitTest { private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceMockRestServiceServerUnitTest.class); diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java similarity index 84% rename from spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java index f4b391573a..6eb040414b 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java @@ -1,15 +1,13 @@ -package org.baeldung.web.service; +package com.baeldung.web.service; -import org.baeldung.resttemplate.web.model.Employee; -import org.baeldung.resttemplate.web.service.EmployeeService; +import com.baeldung.resttemplate.web.model.Employee; +import com.baeldung.resttemplate.web.service.EmployeeService; import org.junit.Assert; -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.runners.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java b/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e52d249f0b..0000000000 --- a/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.resttemplate.RestTemplateConfigurationApplication; -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(classes = RestTemplateConfigurationApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java b/spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java deleted file mode 100644 index 7c4bbb4e5e..0000000000 --- a/spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung; - -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.web.client.RestTemplate; - -@Configuration -@EnableAutoConfiguration -@ComponentScan("org.baeldung") -public class SpringTestConfig { - - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } - -} diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java b/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java deleted file mode 100644 index b40561d9c3..0000000000 --- a/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.client; - -public interface Consts { - int APPLICATION_PORT = 8082; -} diff --git a/spring-roo/pom.xml b/spring-roo/pom.xml index 456642b1f0..448574ed19 100644 --- a/spring-roo/pom.xml +++ b/spring-roo/pom.xml @@ -413,7 +413,7 @@ spring-roo-repository Spring Roo Repository - http://repo.spring.io/spring-roo + https://repo.spring.io/spring-roo diff --git a/spring-scheduling/README.md b/spring-scheduling/README.md index 2e3bb2b5e5..4ee306c0e0 100644 --- a/spring-scheduling/README.md +++ b/spring-scheduling/README.md @@ -1,6 +1,7 @@ ### Relevant articles: -- [A Guide to the Spring Task Scheduler](http://www.baeldung.com/spring-task-scheduler) +- [A Guide to the Spring Task Scheduler](https://www.baeldung.com/spring-task-scheduler) - [The @Scheduled Annotation in Spring](https://www.baeldung.com/spring-scheduled-tasks) -- [Guide to Spring Retry](http://www.baeldung.com/spring-retry) -- [How To Do @Async in Spring](http://www.baeldung.com/spring-async) - +- [Guide to Spring Retry](https://www.baeldung.com/spring-retry) +- [How To Do @Async in Spring](https://www.baeldung.com/spring-async) +- [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) +- [Remote Debugging with IntelliJ IDEA](https://www.baeldung.com/intellij-remote-debugging) diff --git a/spring-scheduling/pom.xml b/spring-scheduling/pom.xml index a337de39b7..b27f33196d 100644 --- a/spring-scheduling/pom.xml +++ b/spring-scheduling/pom.xml @@ -5,7 +5,7 @@ spring-scheduling 0.1-SNAPSHOT spring-scheduling - war + jar com.baeldung @@ -27,6 +27,10 @@ org.springframework spring-aspects + + org.springframework.boot + spring-boot-starter-web + javax.annotation javax.annotation-api diff --git a/spring-scheduling/src/main/java/org/baeldung/async/AsyncComponent.java b/spring-scheduling/src/main/java/com/baeldung/async/AsyncComponent.java similarity index 97% rename from spring-scheduling/src/main/java/org/baeldung/async/AsyncComponent.java rename to spring-scheduling/src/main/java/com/baeldung/async/AsyncComponent.java index 8503f75c8f..7d18b8b784 100644 --- a/spring-scheduling/src/main/java/org/baeldung/async/AsyncComponent.java +++ b/spring-scheduling/src/main/java/com/baeldung/async/AsyncComponent.java @@ -1,4 +1,4 @@ -package org.baeldung.async; +package com.baeldung.async; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; diff --git a/spring-scheduling/src/main/java/org/baeldung/async/CustomAsyncExceptionHandler.java b/spring-scheduling/src/main/java/com/baeldung/async/CustomAsyncExceptionHandler.java similarity index 95% rename from spring-scheduling/src/main/java/org/baeldung/async/CustomAsyncExceptionHandler.java rename to spring-scheduling/src/main/java/com/baeldung/async/CustomAsyncExceptionHandler.java index a7a177f8fe..ba95f000a2 100644 --- a/spring-scheduling/src/main/java/org/baeldung/async/CustomAsyncExceptionHandler.java +++ b/spring-scheduling/src/main/java/com/baeldung/async/CustomAsyncExceptionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.async; +package com.baeldung.async; import java.lang.reflect.Method; diff --git a/spring-scheduling/src/main/java/org/baeldung/async/config/SpringAsyncConfig.java b/spring-scheduling/src/main/java/com/baeldung/async/config/SpringAsyncConfig.java similarity index 89% rename from spring-scheduling/src/main/java/org/baeldung/async/config/SpringAsyncConfig.java rename to spring-scheduling/src/main/java/com/baeldung/async/config/SpringAsyncConfig.java index 0676258207..56fa643017 100644 --- a/spring-scheduling/src/main/java/org/baeldung/async/config/SpringAsyncConfig.java +++ b/spring-scheduling/src/main/java/com/baeldung/async/config/SpringAsyncConfig.java @@ -1,8 +1,8 @@ -package org.baeldung.async.config; +package com.baeldung.async.config; import java.util.concurrent.Executor; -import org.baeldung.async.CustomAsyncExceptionHandler; +import com.baeldung.async.CustomAsyncExceptionHandler; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -14,7 +14,7 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration @EnableAsync() -@ComponentScan("org.baeldung.async") +@ComponentScan("com.baeldung.async") public class SpringAsyncConfig implements AsyncConfigurer { @Bean(name = "threadPoolTaskExecutor") diff --git a/spring-scheduling/src/main/java/org/baeldung/scheduling/ScheduledAnnotationExample.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/ScheduledAnnotationExample.java similarity index 98% rename from spring-scheduling/src/main/java/org/baeldung/scheduling/ScheduledAnnotationExample.java rename to spring-scheduling/src/main/java/com/baeldung/scheduling/ScheduledAnnotationExample.java index 23bbee3bc3..892347d615 100644 --- a/spring-scheduling/src/main/java/org/baeldung/scheduling/ScheduledAnnotationExample.java +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/ScheduledAnnotationExample.java @@ -1,4 +1,4 @@ -package org.baeldung.scheduling; +package com.baeldung.scheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; diff --git a/spring-scheduling/src/main/java/org/baeldung/scheduling/SchedulingWithXmlConfig.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/SchedulingWithXmlConfig.java similarity index 93% rename from spring-scheduling/src/main/java/org/baeldung/scheduling/SchedulingWithXmlConfig.java rename to spring-scheduling/src/main/java/com/baeldung/scheduling/SchedulingWithXmlConfig.java index d7da9ac19c..54856442f4 100644 --- a/spring-scheduling/src/main/java/org/baeldung/scheduling/SchedulingWithXmlConfig.java +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/SchedulingWithXmlConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.scheduling; +package com.baeldung.scheduling; public class SchedulingWithXmlConfig { diff --git a/spring-scheduling/src/main/java/org/baeldung/scheduling/SpringSchedulingConfig.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/SpringSchedulingConfig.java similarity index 90% rename from spring-scheduling/src/main/java/org/baeldung/scheduling/SpringSchedulingConfig.java rename to spring-scheduling/src/main/java/com/baeldung/scheduling/SpringSchedulingConfig.java index 1d81fa0aa8..5d7f1cf88f 100644 --- a/spring-scheduling/src/main/java/org/baeldung/scheduling/SpringSchedulingConfig.java +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/SpringSchedulingConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.scheduling; +package com.baeldung.scheduling; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -9,7 +9,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableScheduling -@ComponentScan("org.baeldung.scheduling") +@ComponentScan("com.baeldung.scheduling") @PropertySource("classpath:springScheduled.properties") public class SpringSchedulingConfig { diff --git a/spring-scheduling/src/main/java/com/baeldung/scheduling/SpringSchedulingFixedRateConfig.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/SpringSchedulingFixedRateConfig.java deleted file mode 100644 index 6000f75ec2..0000000000 --- a/spring-scheduling/src/main/java/com/baeldung/scheduling/SpringSchedulingFixedRateConfig.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.scheduling; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.scheduling.annotation.EnableScheduling; - -@Configuration -@EnableScheduling -@ComponentScan("com.baeldung.scheduling") -public class SpringSchedulingFixedRateConfig { - -} \ No newline at end of file diff --git a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduleJobsByProfile.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduleJobsByProfile.java similarity index 91% rename from spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduleJobsByProfile.java rename to spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduleJobsByProfile.java index 33cd44331f..7783d0e6ff 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduleJobsByProfile.java +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduleJobsByProfile.java @@ -1,4 +1,4 @@ -package com.baeldung.scheduling; +package com.baeldung.scheduling.conditional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJob.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJob.java similarity index 91% rename from spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJob.java rename to spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJob.java index df7cefcd3c..b56cb9ed5b 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJob.java +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJob.java @@ -1,4 +1,4 @@ -package com.baeldung.scheduling; +package com.baeldung.scheduling.conditional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJobsWithBoolean.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithBoolean.java similarity index 94% rename from spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJobsWithBoolean.java rename to spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithBoolean.java index b03de61641..69c0efb7b2 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJobsWithBoolean.java +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithBoolean.java @@ -1,4 +1,4 @@ -package com.baeldung.scheduling; +package com.baeldung.scheduling.conditional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJobsWithConditional.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithConditional.java similarity index 93% rename from spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJobsWithConditional.java rename to spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithConditional.java index 081c8d990a..2a90300c20 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJobsWithConditional.java +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithConditional.java @@ -1,4 +1,4 @@ -package com.baeldung.scheduling; +package com.baeldung.scheduling.conditional; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJobsWithExpression.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithExpression.java similarity index 93% rename from spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJobsWithExpression.java rename to spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithExpression.java index 577a01f241..4842e649c7 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/ScheduledJobsWithExpression.java +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithExpression.java @@ -1,4 +1,4 @@ -package com.baeldung.scheduling; +package com.baeldung.scheduling.conditional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/SchedulingApplication.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/SchedulingApplication.java similarity index 89% rename from spring-boot-mvc/src/main/java/com/baeldung/scheduling/SchedulingApplication.java rename to spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/SchedulingApplication.java index 913e2137f8..4777230341 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/scheduling/SchedulingApplication.java +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/conditional/SchedulingApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.scheduling; +package com.baeldung.scheduling.conditional; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-scheduling/src/main/java/com/baeldung/springretry/AppConfig.java b/spring-scheduling/src/main/java/com/baeldung/springretry/AppConfig.java new file mode 100644 index 0000000000..e79beb370b --- /dev/null +++ b/spring-scheduling/src/main/java/com/baeldung/springretry/AppConfig.java @@ -0,0 +1,34 @@ +package com.baeldung.springretry; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.retry.annotation.EnableRetry; +import org.springframework.retry.backoff.FixedBackOffPolicy; +import org.springframework.retry.policy.SimpleRetryPolicy; +import org.springframework.retry.support.RetryTemplate; + +@Configuration +@ComponentScan(basePackages = "com.baeldung.springretry") +@EnableRetry +// Uncomment this two lines if we need XML configuration +// @EnableAspectJAutoProxy +// @ImportResource("classpath:/retryadvice.xml") +public class AppConfig { + + @Bean + public RetryTemplate retryTemplate() { + RetryTemplate retryTemplate = new RetryTemplate(); + + FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy(); + fixedBackOffPolicy.setBackOffPeriod(2000l); + retryTemplate.setBackOffPolicy(fixedBackOffPolicy); + + SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); + retryPolicy.setMaxAttempts(2); + retryTemplate.setRetryPolicy(retryPolicy); + + retryTemplate.registerListener(new DefaultListenerSupport()); + return retryTemplate; + } +} diff --git a/spring-scheduling/src/main/java/org/baeldung/springretry/DefaultListenerSupport.java b/spring-scheduling/src/main/java/com/baeldung/springretry/DefaultListenerSupport.java similarity index 96% rename from spring-scheduling/src/main/java/org/baeldung/springretry/DefaultListenerSupport.java rename to spring-scheduling/src/main/java/com/baeldung/springretry/DefaultListenerSupport.java index bc251b4c2f..0f9f1b6f0d 100644 --- a/spring-scheduling/src/main/java/org/baeldung/springretry/DefaultListenerSupport.java +++ b/spring-scheduling/src/main/java/com/baeldung/springretry/DefaultListenerSupport.java @@ -1,4 +1,4 @@ -package org.baeldung.springretry; +package com.baeldung.springretry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-scheduling/src/main/java/com/baeldung/springretry/MyService.java b/spring-scheduling/src/main/java/com/baeldung/springretry/MyService.java new file mode 100644 index 0000000000..409bf25845 --- /dev/null +++ b/spring-scheduling/src/main/java/com/baeldung/springretry/MyService.java @@ -0,0 +1,21 @@ +package com.baeldung.springretry; + +import java.sql.SQLException; + +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; + +public interface MyService { + + @Retryable + void retryService(); + + @Retryable(value = { SQLException.class }, maxAttempts = 2, backoff = @Backoff(delay = 5000)) + void retryServiceWithRecovery(String sql) throws SQLException; + + @Recover + void recover(SQLException e, String sql); + + void templateRetryService(); +} diff --git a/spring-scheduling/src/main/java/org/baeldung/springretry/MyServiceImpl.java b/spring-scheduling/src/main/java/com/baeldung/springretry/MyServiceImpl.java similarity index 96% rename from spring-scheduling/src/main/java/org/baeldung/springretry/MyServiceImpl.java rename to spring-scheduling/src/main/java/com/baeldung/springretry/MyServiceImpl.java index 1b698f26c9..3e4b5ed00d 100644 --- a/spring-scheduling/src/main/java/org/baeldung/springretry/MyServiceImpl.java +++ b/spring-scheduling/src/main/java/com/baeldung/springretry/MyServiceImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.springretry; +package com.baeldung.springretry; import java.sql.SQLException; diff --git a/spring-scheduling/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerConfig.java b/spring-scheduling/src/main/java/com/baeldung/taskscheduler/ThreadPoolTaskSchedulerConfig.java similarity index 93% rename from spring-scheduling/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerConfig.java rename to spring-scheduling/src/main/java/com/baeldung/taskscheduler/ThreadPoolTaskSchedulerConfig.java index 342a5fe3e6..c24c701df5 100644 --- a/spring-scheduling/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerConfig.java +++ b/spring-scheduling/src/main/java/com/baeldung/taskscheduler/ThreadPoolTaskSchedulerConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.taskscheduler; +package com.baeldung.taskscheduler; import java.util.concurrent.TimeUnit; @@ -10,7 +10,7 @@ import org.springframework.scheduling.support.CronTrigger; import org.springframework.scheduling.support.PeriodicTrigger; @Configuration -@ComponentScan(basePackages = "org.baeldung.taskscheduler", basePackageClasses = { ThreadPoolTaskSchedulerExamples.class }) +@ComponentScan(basePackages = "com.baeldung.taskscheduler", basePackageClasses = { ThreadPoolTaskSchedulerExamples.class }) public class ThreadPoolTaskSchedulerConfig { @Bean diff --git a/spring-scheduling/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java b/spring-scheduling/src/main/java/com/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java similarity index 97% rename from spring-scheduling/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java rename to spring-scheduling/src/main/java/com/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java index 5d72ed148a..c0c6f37507 100644 --- a/spring-scheduling/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java +++ b/spring-scheduling/src/main/java/com/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java @@ -1,4 +1,4 @@ -package org.baeldung.taskscheduler; +package com.baeldung.taskscheduler; import java.util.Date; diff --git a/spring-scheduling/src/main/java/org/baeldung/springretry/AppConfig.java b/spring-scheduling/src/main/java/org/baeldung/springretry/AppConfig.java deleted file mode 100644 index d9b081578c..0000000000 --- a/spring-scheduling/src/main/java/org/baeldung/springretry/AppConfig.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.baeldung.springretry; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.retry.annotation.EnableRetry; -import org.springframework.retry.backoff.FixedBackOffPolicy; -import org.springframework.retry.policy.SimpleRetryPolicy; -import org.springframework.retry.support.RetryTemplate; - -@Configuration -@ComponentScan(basePackages = "org.baeldung.springretry") -@EnableRetry -// Uncomment this two lines if we need XML configuration -// @EnableAspectJAutoProxy -// @ImportResource("classpath:/retryadvice.xml") -public class AppConfig { - - @Bean - public RetryTemplate retryTemplate() { - RetryTemplate retryTemplate = new RetryTemplate(); - - FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy(); - fixedBackOffPolicy.setBackOffPeriod(2000l); - retryTemplate.setBackOffPolicy(fixedBackOffPolicy); - - SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); - retryPolicy.setMaxAttempts(2); - retryTemplate.setRetryPolicy(retryPolicy); - - retryTemplate.registerListener(new DefaultListenerSupport()); - return retryTemplate; - } -} diff --git a/spring-scheduling/src/main/java/org/baeldung/springretry/MyService.java b/spring-scheduling/src/main/java/org/baeldung/springretry/MyService.java deleted file mode 100644 index 6306ff3c26..0000000000 --- a/spring-scheduling/src/main/java/org/baeldung/springretry/MyService.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.springretry; - -import java.sql.SQLException; - -import org.springframework.retry.annotation.Backoff; -import org.springframework.retry.annotation.Recover; -import org.springframework.retry.annotation.Retryable; - -public interface MyService { - - @Retryable - void retryService(); - - @Retryable(value = { SQLException.class }, maxAttempts = 2, backoff = @Backoff(delay = 5000)) - void retryServiceWithRecovery(String sql) throws SQLException; - - @Recover - void recover(SQLException e, String sql); - - void templateRetryService(); -} diff --git a/spring-scheduling/src/main/resources/retryadvice.xml b/spring-scheduling/src/main/resources/retryadvice.xml index 79a9fc8660..8de7801a58 100644 --- a/spring-scheduling/src/main/resources/retryadvice.xml +++ b/spring-scheduling/src/main/resources/retryadvice.xml @@ -7,7 +7,7 @@ http://www.springframework.org/schema/beans/spring-beans.xsd"> + expression="execution(* com.baeldung.springretry..*MyService.defaultXmlRetryService(..))" /> diff --git a/spring-scheduling/src/main/resources/springAsync-config.xml b/spring-scheduling/src/main/resources/springAsync-config.xml index 40fc40c79f..48bfbb3f41 100644 --- a/spring-scheduling/src/main/resources/springAsync-config.xml +++ b/spring-scheduling/src/main/resources/springAsync-config.xml @@ -10,6 +10,6 @@ - + \ No newline at end of file diff --git a/spring-scheduling/src/main/resources/springScheduled-config.xml b/spring-scheduling/src/main/resources/springScheduled-config.xml index 4078f535da..1e42b118bd 100644 --- a/spring-scheduling/src/main/resources/springScheduled-config.xml +++ b/spring-scheduling/src/main/resources/springScheduled-config.xml @@ -16,7 +16,7 @@ - + + + 4.0.0 + spring-security-modules + 0.0.1-SNAPSHOT + spring-security-modules + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + spring-security-acl + spring-security-angular/server + spring-security-cache-control + spring-security-core + spring-security-cors + spring-security-kerberos + spring-security-mvc + spring-security-mvc-boot-1 + spring-security-mvc-boot-2 + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-jsonview + spring-security-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-socket + spring-security-oidc + spring-security-okta + spring-security-react + spring-security-rest + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + + + diff --git a/spring-security-modules/spring-security-acl/pom.xml b/spring-security-modules/spring-security-acl/pom.xml index 3c613f9d92..5c04aaa9ca 100644 --- a/spring-security-modules/spring-security-acl/pom.xml +++ b/spring-security-modules/spring-security-acl/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/Application.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/Application.java new file mode 100644 index 0000000000..b18a3a6527 --- /dev/null +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.acl; + +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-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/ACLContext.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/ACLContext.java similarity index 99% rename from spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/ACLContext.java rename to spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/ACLContext.java index 337e745c3c..cb60ef1d45 100644 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/ACLContext.java +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/ACLContext.java @@ -1,4 +1,4 @@ -package org.baeldung.acl.config; +package com.baeldung.acl.config; import javax.sql.DataSource; diff --git a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/AclMethodSecurityConfiguration.java similarity index 96% rename from spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java rename to spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/AclMethodSecurityConfiguration.java index e503cb1a41..1a8788b906 100644 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/AclMethodSecurityConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.acl.config; +package com.baeldung.acl.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/JPAPersistenceConfig.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/JPAPersistenceConfig.java new file mode 100644 index 0000000000..5f7fff5ff3 --- /dev/null +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/JPAPersistenceConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.acl.config; + +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories(basePackages = "com.baeldung.acl.persistence.dao") +@PropertySource("classpath:com.baeldung.acl.datasource.properties") +@EntityScan(basePackages={ "com.baeldung.acl.persistence.entity" }) +public class JPAPersistenceConfig { + +} diff --git a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/dao/NoticeMessageRepository.java similarity index 88% rename from spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java rename to spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/dao/NoticeMessageRepository.java index 91a2af7d83..be1a0118fc 100644 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/dao/NoticeMessageRepository.java @@ -1,8 +1,8 @@ -package org.baeldung.acl.persistence.dao; +package com.baeldung.acl.persistence.dao; import java.util.List; -import org.baeldung.acl.persistence.entity.NoticeMessage; +import com.baeldung.acl.persistence.entity.NoticeMessage; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; import org.springframework.security.access.prepost.PostAuthorize; diff --git a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/entity/NoticeMessage.java similarity index 92% rename from spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java rename to spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/entity/NoticeMessage.java index bd1e866f83..80c04146e4 100644 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/entity/NoticeMessage.java @@ -1,4 +1,4 @@ -package org.baeldung.acl.persistence.entity; +package com.baeldung.acl.persistence.entity; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/Application.java b/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/Application.java deleted file mode 100644 index 665ca64076..0000000000 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/Application.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.baeldung.acl; - -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-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java b/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java deleted file mode 100644 index 24d170e56c..0000000000 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.acl.config; - -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@EnableTransactionManagement -@EnableJpaRepositories(basePackages = "org.baeldung.acl.persistence.dao") -@PropertySource("classpath:org.baeldung.acl.datasource.properties") -@EntityScan(basePackages={ "org.baeldung.acl.persistence.entity" }) -public class JPAPersistenceConfig { - -} diff --git a/spring-security-modules/spring-security-acl/src/main/resources/acl-data.sql b/spring-security-modules/spring-security-acl/src/main/resources/acl-data.sql index a4e0011834..3b48c83f3c 100644 --- a/spring-security-modules/spring-security-acl/src/main/resources/acl-data.sql +++ b/spring-security-modules/spring-security-acl/src/main/resources/acl-data.sql @@ -4,7 +4,7 @@ INSERT INTO acl_sid (id, principal, sid) VALUES (3, 0, 'ROLE_EDITOR'); INSERT INTO acl_class (id, class) VALUES -(1, 'org.baeldung.acl.persistence.entity.NoticeMessage'); +(1, 'com.baeldung.acl.persistence.entity.NoticeMessage'); INSERT INTO system_message(id,content) VALUES (1,'First Level Message'), diff --git a/spring-security-modules/spring-security-acl/src/main/resources/org.baeldung.acl.datasource.properties b/spring-security-modules/spring-security-acl/src/main/resources/com.baeldung.acl.datasource.properties similarity index 100% rename from spring-security-modules/spring-security-acl/src/main/resources/org.baeldung.acl.datasource.properties rename to spring-security-modules/spring-security-acl/src/main/resources/com.baeldung.acl.datasource.properties diff --git a/spring-security-modules/spring-security-acl/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-acl/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e60983733e --- /dev/null +++ b/spring-security-modules/spring-security-acl/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import com.baeldung.acl.Application; +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(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-acl/src/test/java/org/baeldung/acl/SpringACLIntegrationTest.java b/spring-security-modules/spring-security-acl/src/test/java/com/baeldung/acl/SpringACLIntegrationTest.java similarity index 95% rename from spring-security-modules/spring-security-acl/src/test/java/org/baeldung/acl/SpringACLIntegrationTest.java rename to spring-security-modules/spring-security-acl/src/test/java/com/baeldung/acl/SpringACLIntegrationTest.java index 1460d4f47b..dfdeafe059 100644 --- a/spring-security-modules/spring-security-acl/src/test/java/org/baeldung/acl/SpringACLIntegrationTest.java +++ b/spring-security-modules/spring-security-acl/src/test/java/com/baeldung/acl/SpringACLIntegrationTest.java @@ -1,12 +1,12 @@ -package org.baeldung.acl; +package com.baeldung.acl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.List; -import org.baeldung.acl.persistence.dao.NoticeMessageRepository; -import org.baeldung.acl.persistence.entity.NoticeMessage; +import com.baeldung.acl.persistence.dao.NoticeMessageRepository; +import com.baeldung.acl.persistence.entity.NoticeMessage; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -39,7 +39,7 @@ public class SpringACLIntegrationTest extends AbstractJUnit4SpringContextTests{ private static String EDITTED_CONTENT = "EDITED"; @Configuration - @ComponentScan("org.baeldung.acl.*") + @ComponentScan("com.baeldung.acl.*") public static class SpringConfig { } diff --git a/spring-security-modules/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 74f26e2e5a..0000000000 --- a/spring-security-modules/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.acl.Application; -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(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-angular/server/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-angular/server/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..49314c0575 --- /dev/null +++ b/spring-security-modules/spring-security-angular/server/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.springbootsecurityrest.basicauth.SpringBootSecurityApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootSecurityApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e61d512bca..0000000000 --- a/spring-security-modules/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.springbootsecurityrest.basicauth.SpringBootSecurityApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringBootSecurityApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-cache-control/pom.xml b/spring-security-modules/spring-security-cache-control/pom.xml index ff96ae78dd..743b3c291d 100644 --- a/spring-security-modules/spring-security-cache-control/pom.xml +++ b/spring-security-modules/spring-security-cache-control/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -23,45 +23,15 @@ spring-boot-starter-web - org.springframework.security - spring-security-core - - - org.springframework.security - spring-security-config - - - org.springframework.security - spring-security-web - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} + org.springframework.boot + spring-boot-starter-security - org.hamcrest - hamcrest-core + org.springframework.boot + spring-boot-starter-test test - - org.hamcrest - hamcrest-library - test - - - - org.mockito - mockito-core - test - - - - org.springframework - spring-test - - \ No newline at end of file diff --git a/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0cde5d829d --- /dev/null +++ b/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.cachecontrol.AppRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AppRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java b/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java index d6a1a97773..d4d24a4986 100644 --- a/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java +++ b/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java @@ -4,8 +4,8 @@ import static io.restassured.RestAssured.given; 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.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; import io.restassured.http.ContentType; diff --git a/spring-security-modules/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 8fbaa7169b..0000000000 --- a/spring-security-modules/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.cachecontrol.AppRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AppRunner.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-core/README.md b/spring-security-modules/spring-security-core/README.md index 6b1f236b7c..f28b3abb2b 100644 --- a/spring-security-modules/spring-security-core/README.md +++ b/spring-security-modules/spring-security-core/README.md @@ -7,6 +7,8 @@ This module contains articles about core Spring Security - [Spring Boot Authentication Auditing Support](https://www.baeldung.com/spring-boot-authentication-audit) - [Introduction to Spring Method Security](https://www.baeldung.com/spring-security-method-security) - [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) +- [Deny Access on Missing @PreAuthorize to Spring Controller Methods](https://www.baeldung.com/spring-deny-access) +- [Spring Security: Check If a User Has a Role in Java](https://www.baeldung.com/spring-security-check-user-role) ### Build the Project diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java index a084f14eca..7e6b2c3d9c 100644 --- a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java @@ -1,8 +1,15 @@ package com.baeldung.app.controller; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -10,6 +17,8 @@ import org.springframework.web.bind.annotation.RequestMethod; import com.baeldung.app.entity.Task; import com.baeldung.app.service.TaskService; +import javax.servlet.http.HttpServletRequest; + @Controller @RequestMapping("api/tasks") public class TaskController { @@ -17,6 +26,9 @@ public class TaskController { @Autowired private TaskService taskService; + @Autowired(required = false) + private UserDetailsService userDetailsService; + @RequestMapping(method = RequestMethod.GET) public ResponseEntity> findAllTasks() { Iterable tasks = taskService.findAll(); diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/App.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/App.java new file mode 100644 index 0000000000..357583a572 --- /dev/null +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/App.java @@ -0,0 +1,11 @@ +package com.baeldung.checkrolejava; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class App { + public static void main(String[] args) { + SpringApplication.run(com.baeldung.app.App.class, args); + } +} diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UnauthorizedException.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UnauthorizedException.java new file mode 100644 index 0000000000..11fe9f9e5f --- /dev/null +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UnauthorizedException.java @@ -0,0 +1,8 @@ +package com.baeldung.checkrolejava; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.UNAUTHORIZED) +public class UnauthorizedException extends RuntimeException { +} diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UserController.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UserController.java new file mode 100644 index 0000000000..3092e94c7f --- /dev/null +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UserController.java @@ -0,0 +1,62 @@ +package com.baeldung.checkrolejava; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +import javax.servlet.http.HttpServletRequest; + +@Controller +public class UserController { + + @Autowired + private UserDetailsService userDetailsService; + + @PreAuthorize("hasRole('ROLE_ADMIN')") + @GetMapping("/user/{id}") + public String getUser(@PathVariable("id") String id) { + return "user"; + } + + @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_MANAGER')") + @GetMapping("/users") + public String getUsers() { + return "users"; + } + + @GetMapping("v2/user/{id}") + public String getUserUsingSecurityContext() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ADMIN"))) { + return "user"; + } + + throw new UnauthorizedException(); + } + + @GetMapping("v2/users") + public String getUsersUsingDetailsService() { + UserDetails details = userDetailsService.loadUserByUsername("mike"); + if (details != null && details.getAuthorities().stream() + .anyMatch(a -> a.getAuthority().equals("ADMIN"))) { + return "users"; + } + + throw new UnauthorizedException(); + } + + @GetMapping("v3/users") + public String getUsers(HttpServletRequest request) { + if (request.isUserInRole("ROLE_ADMIN")) { + return "users"; + } + + throw new UnauthorizedException(); + } +} diff --git a/spring-security-modules/spring-security-cors/pom.xml b/spring-security-modules/spring-security-cors/pom.xml index 91e8f5adb6..2acb99368f 100644 --- a/spring-security-modules/spring-security-cors/pom.xml +++ b/spring-security-modules/spring-security-cors/pom.xml @@ -3,15 +3,14 @@ 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-cors - 0.0.1-SNAPSHOT spring-security-cors jar Spring Security CORS com.baeldung - parent-modules - 1.0.0-SNAPSHOT + spring-security-modules + 0.0.1-SNAPSHOT diff --git a/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java b/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java deleted file mode 100644 index a471eb922f..0000000000 --- a/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.springbootsecuritycors; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; -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.security.test.web.servlet.setup.SecurityMockMvcConfigurers; -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 com.baeldung.springbootsecuritycors.basicauth.SpringBootSecurityApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = { SpringBootSecurityApplication.class }) -public class ResourceControllerTest { - - private MockMvc mockMvc; - - @Autowired - private WebApplicationContext wac; - - @Before - public void setUp() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) - .apply(SecurityMockMvcConfigurers.springSecurity()) - .build(); - } - - @Test - public void givenPreFlightRequest_whenPerfomed_shouldReturnOK() throws Exception { - mockMvc.perform(options("/user") - .header("Access-Control-Request-Method", "GET") - .header("Origin", "http://localhost:4200")) - .andExpect(status().isOk()); - } -} diff --git a/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerUnitTest.java b/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerUnitTest.java new file mode 100644 index 0000000000..7567573040 --- /dev/null +++ b/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.springbootsecuritycors; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +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.security.test.web.servlet.setup.SecurityMockMvcConfigurers; +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 com.baeldung.springbootsecuritycors.basicauth.SpringBootSecurityApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { SpringBootSecurityApplication.class }) +public class ResourceControllerUnitTest { + + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Before + public void setUp() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) + .apply(SecurityMockMvcConfigurers.springSecurity()) + .build(); + } + + @Test + public void givenPreFlightRequest_whenPerfomed_shouldReturnOK() throws Exception { + mockMvc.perform(options("/user") + .header("Access-Control-Request-Method", "GET") + .header("Origin", "http://localhost:4200")) + .andExpect(status().isOk()); + } +} diff --git a/spring-security-modules/spring-security-kerberos/pom.xml b/spring-security-modules/spring-security-kerberos/pom.xml index 6846bdf063..51a48a78c6 100644 --- a/spring-security-modules/spring-security-kerberos/pom.xml +++ b/spring-security-modules/spring-security-kerberos/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/Application.java b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..37dbe7dab8 --- /dev/null +++ b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/config/WebSecurityConfig.java b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/config/WebSecurityConfig.java new file mode 100644 index 0000000000..c1c206e5c9 --- /dev/null +++ b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/config/WebSecurityConfig.java @@ -0,0 +1,87 @@ +package com.baeldung.config; + +import com.baeldung.security.DummyUserDetailsService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.FileSystemResource; +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.WebSecurityConfigurerAdapter; +import org.springframework.security.kerberos.authentication.KerberosAuthenticationProvider; +import org.springframework.security.kerberos.authentication.KerberosServiceAuthenticationProvider; +import org.springframework.security.kerberos.authentication.sun.SunJaasKerberosClient; +import org.springframework.security.kerberos.authentication.sun.SunJaasKerberosTicketValidator; +import org.springframework.security.kerberos.web.authentication.SpnegoAuthenticationProcessingFilter; +import org.springframework.security.kerberos.web.authentication.SpnegoEntryPoint; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; + +@Configuration +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .anyRequest() + .authenticated() + .and() + .addFilterBefore(spnegoAuthenticationProcessingFilter(authenticationManagerBean()), BasicAuthenticationFilter.class); + } + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(kerberosAuthenticationProvider()) + .authenticationProvider(kerberosServiceAuthenticationProvider()); + } + + @Bean + public KerberosAuthenticationProvider kerberosAuthenticationProvider() { + KerberosAuthenticationProvider provider = new KerberosAuthenticationProvider(); + SunJaasKerberosClient client = new SunJaasKerberosClient(); + client.setDebug(true); + provider.setKerberosClient(client); + provider.setUserDetailsService(dummyUserDetailsService()); + return provider; + } + + @Bean + public SpnegoEntryPoint spnegoEntryPoint() { + return new SpnegoEntryPoint("/login"); + } + + @Bean + public SpnegoAuthenticationProcessingFilter spnegoAuthenticationProcessingFilter(AuthenticationManager authenticationManager) { + SpnegoAuthenticationProcessingFilter filter = new SpnegoAuthenticationProcessingFilter(); + filter.setAuthenticationManager(authenticationManager); + return filter; + } + + @Bean + public KerberosServiceAuthenticationProvider kerberosServiceAuthenticationProvider() { + KerberosServiceAuthenticationProvider provider = new KerberosServiceAuthenticationProvider(); + provider.setTicketValidator(sunJaasKerberosTicketValidator()); + provider.setUserDetailsService(dummyUserDetailsService()); + return provider; + } + + @Bean + public SunJaasKerberosTicketValidator sunJaasKerberosTicketValidator() { + SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator(); + ticketValidator.setServicePrincipal("HTTP/demo.kerberos.bealdung.com@baeldung.com"); + ticketValidator.setKeyTabLocation(new FileSystemResource("baeldung.keytab")); + ticketValidator.setDebug(true); + return ticketValidator; + } + + @Bean + public DummyUserDetailsService dummyUserDetailsService() { + return new DummyUserDetailsService(); + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/security/DummyUserDetailsService.java b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/security/DummyUserDetailsService.java similarity index 95% rename from spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/security/DummyUserDetailsService.java rename to spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/security/DummyUserDetailsService.java index 10d71fca8f..6ddd6c8969 100644 --- a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/security/DummyUserDetailsService.java +++ b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/security/DummyUserDetailsService.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; diff --git a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/Application.java b/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/Application.java deleted file mode 100644 index 39c2b51356..0000000000 --- a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/Application.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/config/WebSecurityConfig.java b/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/config/WebSecurityConfig.java deleted file mode 100644 index 49a1cf0a8e..0000000000 --- a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/config/WebSecurityConfig.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.baeldung.config; - -import org.baeldung.security.DummyUserDetailsService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.FileSystemResource; -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.WebSecurityConfigurerAdapter; -import org.springframework.security.kerberos.authentication.KerberosAuthenticationProvider; -import org.springframework.security.kerberos.authentication.KerberosServiceAuthenticationProvider; -import org.springframework.security.kerberos.authentication.sun.SunJaasKerberosClient; -import org.springframework.security.kerberos.authentication.sun.SunJaasKerberosTicketValidator; -import org.springframework.security.kerberos.web.authentication.SpnegoAuthenticationProcessingFilter; -import org.springframework.security.kerberos.web.authentication.SpnegoEntryPoint; -import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; - -@Configuration -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .anyRequest() - .authenticated() - .and() - .addFilterBefore(spnegoAuthenticationProcessingFilter(authenticationManagerBean()), BasicAuthenticationFilter.class); - } - - @Override - @Bean - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(kerberosAuthenticationProvider()) - .authenticationProvider(kerberosServiceAuthenticationProvider()); - } - - @Bean - public KerberosAuthenticationProvider kerberosAuthenticationProvider() { - KerberosAuthenticationProvider provider = new KerberosAuthenticationProvider(); - SunJaasKerberosClient client = new SunJaasKerberosClient(); - client.setDebug(true); - provider.setKerberosClient(client); - provider.setUserDetailsService(dummyUserDetailsService()); - return provider; - } - - @Bean - public SpnegoEntryPoint spnegoEntryPoint() { - return new SpnegoEntryPoint("/login"); - } - - @Bean - public SpnegoAuthenticationProcessingFilter spnegoAuthenticationProcessingFilter(AuthenticationManager authenticationManager) { - SpnegoAuthenticationProcessingFilter filter = new SpnegoAuthenticationProcessingFilter(); - filter.setAuthenticationManager(authenticationManager); - return filter; - } - - @Bean - public KerberosServiceAuthenticationProvider kerberosServiceAuthenticationProvider() { - KerberosServiceAuthenticationProvider provider = new KerberosServiceAuthenticationProvider(); - provider.setTicketValidator(sunJaasKerberosTicketValidator()); - provider.setUserDetailsService(dummyUserDetailsService()); - return provider; - } - - @Bean - public SunJaasKerberosTicketValidator sunJaasKerberosTicketValidator() { - SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator(); - ticketValidator.setServicePrincipal("HTTP/demo.kerberos.bealdung.com@baeldung.com"); - ticketValidator.setKeyTabLocation(new FileSystemResource("baeldung.keytab")); - ticketValidator.setDebug(true); - return ticketValidator; - } - - @Bean - public DummyUserDetailsService dummyUserDetailsService() { - return new DummyUserDetailsService(); - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-ldap/README.md b/spring-security-modules/spring-security-ldap/README.md similarity index 100% rename from spring-security-modules/spring-security-mvc-ldap/README.md rename to spring-security-modules/spring-security-ldap/README.md diff --git a/spring-security-modules/spring-security-ldap/pom.xml b/spring-security-modules/spring-security-ldap/pom.xml new file mode 100644 index 0000000000..baed682186 --- /dev/null +++ b/spring-security-modules/spring-security-ldap/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + spring-security-ldap + 0.1-SNAPSHOT + spring-security-ldap + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-actuator + + + + + org.springframework.security + spring-security-ldap + + + + + org.apache.directory.server + apacheds-server-jndi + ${apacheds.version} + + + + + + spring-security-mvc-ldap + + + src/main/resources + true + + + + + + 1.5.5 + + + diff --git a/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/SampleLDAPApplication.java b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/SampleLDAPApplication.java new file mode 100644 index 0000000000..2d619cccfa --- /dev/null +++ b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/SampleLDAPApplication.java @@ -0,0 +1,22 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +/** + * Main Application Class - uses Spring Boot. Just run this as a normal Java + * class to run up a Jetty Server (on http://localhost:8080) + * + */ +@SpringBootApplication +public class SampleLDAPApplication extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(SampleLDAPApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/SecurityConfig.java b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..69f90d9de9 --- /dev/null +++ b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/SecurityConfig.java @@ -0,0 +1,39 @@ +package com.baeldung.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.WebSecurityConfigurerAdapter; + +/** + * Security Configuration - LDAP and HTTP Authorizations. + */ +@Configuration +// @ImportResource({ "classpath:webSecurityConfig.xml" }) //=> uncomment to use equivalent xml config +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.ldapAuthentication() + .userSearchBase("ou=people") + .userSearchFilter("(uid={0})") + .groupSearchBase("ou=groups") + .groupSearchFilter("(member={0})") + .contextSource() + .root("dc=baeldung,dc=com") + .ldif("classpath:users.ldif"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/", "/home", "/css/**") + .permitAll() + .anyRequest() + .authenticated() + .and().formLogin().loginPage("/login").permitAll() + .and().logout().logoutSuccessUrl("/"); + } + +} diff --git a/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/WebConfig.java b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/WebConfig.java new file mode 100644 index 0000000000..9809be1844 --- /dev/null +++ b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/WebConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/login") + .setViewName("login"); + } +} diff --git a/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/controller/MyController.java b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/controller/MyController.java new file mode 100644 index 0000000000..7c746cfb31 --- /dev/null +++ b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/controller/MyController.java @@ -0,0 +1,70 @@ +package com.baeldung.controller; + +import java.security.Principal; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Spring Controller Definitions. + */ +@Controller +public class MyController { + + @RequestMapping("/") + public String init(Map model, Principal principal) { + model.put("title", "PUBLIC AREA"); + model.put("message", "Any user can view this page"); + model.put("username", getUserName(principal)); + model.put("userroles", getUserRoles(principal)); + return "home"; + } + + @RequestMapping("/secure") + public String secure(Map model, Principal principal) { + model.put("title", "SECURE AREA"); + model.put("message", "Only Authorised Users Can See This Page"); + model.put("username", getUserName(principal)); + model.put("userroles", getUserRoles(principal)); + return "home"; + } + + private String getUserName(Principal principal) { + if (principal == null) { + return "anonymous"; + } else { + + final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal(); + Collection authorities = currentUser.getAuthorities(); + for (GrantedAuthority grantedAuthority : authorities) { + System.out.println(grantedAuthority.getAuthority()); + } + return principal.getName(); + } + } + + private Collection getUserRoles(Principal principal) { + if (principal == null) { + return Arrays.asList("none"); + } else { + + Set roles = new HashSet(); + + final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal(); + Collection authorities = currentUser.getAuthorities(); + for (GrantedAuthority grantedAuthority : authorities) { + roles.add(grantedAuthority.getAuthority()); + } + return roles; + } + } + +} diff --git a/spring-security-modules/spring-security-ldap/src/main/resources/application.properties b/spring-security-modules/spring-security-ldap/src/main/resources/application.properties new file mode 100644 index 0000000000..3d0221bb7b --- /dev/null +++ b/spring-security-modules/spring-security-ldap/src/main/resources/application.properties @@ -0,0 +1 @@ +management.health.ldap.enabled=false \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-ldap/src/main/resources/logback.xml b/spring-security-modules/spring-security-ldap/src/main/resources/logback.xml similarity index 100% rename from spring-security-modules/spring-security-mvc-ldap/src/main/resources/logback.xml rename to spring-security-modules/spring-security-ldap/src/main/resources/logback.xml diff --git a/spring-security-modules/spring-security-mvc-ldap/src/main/resources/static/css/bootstrap.min.css b/spring-security-modules/spring-security-ldap/src/main/resources/static/css/bootstrap.min.css similarity index 100% rename from spring-security-modules/spring-security-mvc-ldap/src/main/resources/static/css/bootstrap.min.css rename to spring-security-modules/spring-security-ldap/src/main/resources/static/css/bootstrap.min.css diff --git a/spring-security-modules/spring-security-mvc-ldap/src/main/resources/templates/error.html b/spring-security-modules/spring-security-ldap/src/main/resources/templates/error.html similarity index 100% rename from spring-security-modules/spring-security-mvc-ldap/src/main/resources/templates/error.html rename to spring-security-modules/spring-security-ldap/src/main/resources/templates/error.html diff --git a/spring-security-modules/spring-security-mvc-ldap/src/main/resources/templates/home.html b/spring-security-modules/spring-security-ldap/src/main/resources/templates/home.html similarity index 100% rename from spring-security-modules/spring-security-mvc-ldap/src/main/resources/templates/home.html rename to spring-security-modules/spring-security-ldap/src/main/resources/templates/home.html diff --git a/spring-security-modules/spring-security-mvc-ldap/src/main/resources/templates/login.html b/spring-security-modules/spring-security-ldap/src/main/resources/templates/login.html similarity index 100% rename from spring-security-modules/spring-security-mvc-ldap/src/main/resources/templates/login.html rename to spring-security-modules/spring-security-ldap/src/main/resources/templates/login.html diff --git a/spring-security-modules/spring-security-mvc-ldap/src/main/resources/users.ldif b/spring-security-modules/spring-security-ldap/src/main/resources/users.ldif similarity index 100% rename from spring-security-modules/spring-security-mvc-ldap/src/main/resources/users.ldif rename to spring-security-modules/spring-security-ldap/src/main/resources/users.ldif diff --git a/spring-security-modules/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-ldap/src/main/resources/webSecurityConfig.xml similarity index 94% rename from spring-security-modules/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml rename to spring-security-modules/spring-security-ldap/src/main/resources/webSecurityConfig.xml index c13f65de5e..adfd603e54 100644 --- a/spring-security-modules/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-ldap/src/main/resources/webSecurityConfig.xml @@ -10,6 +10,7 @@ + diff --git a/spring-security-modules/spring-security-ldap/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-ldap/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a15ca31980 --- /dev/null +++ b/spring-security-modules/spring-security-ldap/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import com.baeldung.SampleLDAPApplication; +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(classes = SampleLDAPApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-mvc-ldap/src/test/resources/.gitignore b/spring-security-modules/spring-security-ldap/src/test/resources/.gitignore similarity index 100% rename from spring-security-modules/spring-security-mvc-ldap/src/test/resources/.gitignore rename to spring-security-modules/spring-security-ldap/src/test/resources/.gitignore diff --git a/spring-security-modules/spring-security-mvc-boot-1/README.md b/spring-security-modules/spring-security-mvc-boot-1/README.md new file mode 100644 index 0000000000..f2c161d387 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/README.md @@ -0,0 +1,17 @@ +## Spring Boot Security MVC - 1 + +This module contains articles about Spring Security with Spring MVC in Boot applications + +### The Course +The "REST With Spring" Classes: http://github.learnspringsecurity.com + +### Relevant Articles: +- [A Custom Security Expression with Spring Security](https://www.baeldung.com/spring-security-create-new-custom-security-expression) +- [Custom AccessDecisionVoters in Spring Security](https://www.baeldung.com/spring-security-custom-voter) +- [Spring Security: Authentication with a Database-backed UserDetailsService](https://www.baeldung.com/spring-security-authentication-with-a-database) +- [Spring Data with Spring Security](https://www.baeldung.com/spring-data-security) +- [Granted Authority Versus Role in Spring Security](https://www.baeldung.com/spring-security-granted-authority-vs-role) +- [Spring Security – Whitelist IP Range](https://www.baeldung.com/spring-security-whitelist-ip-range) +- [Find the Registered Spring Security Filters](https://www.baeldung.com/spring-security-registered-filters) +- More articles: [[next -->]](/../spring-security-mvc-boot-2) + diff --git a/spring-security-modules/spring-security-mvc-boot/WebContent/META-INF/MANIFEST.MF b/spring-security-modules/spring-security-mvc-boot-1/WebContent/META-INF/MANIFEST.MF similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/WebContent/META-INF/MANIFEST.MF rename to spring-security-modules/spring-security-mvc-boot-1/WebContent/META-INF/MANIFEST.MF diff --git a/spring-security-modules/spring-security-mvc-boot-1/pom.xml b/spring-security-modules/spring-security-mvc-boot-1/pom.xml new file mode 100644 index 0000000000..7ad18376ec --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/pom.xml @@ -0,0 +1,235 @@ + + + 4.0.0 + spring-security-mvc-boot-1 + 0.0.1-SNAPSHOT + spring-security-mvc-boot-1 + war + Spring Security MVC Boot - 1 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-security + + + 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-springsecurity5 + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.security + spring-security-data + + + mysql + mysql-connector-java + runtime + + + com.h2database + h2 + + + org.postgresql + postgresql + runtime + + + org.hamcrest + hamcrest + test + + + org.springframework + spring-test + test + + + org.springframework.security + spring-security-test + test + + + taglibs + standard + ${taglibs-standard.version} + + + 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 + + + org.springframework + spring-context-support + + + net.sf.ehcache + ehcache-core + ${ehcache-core.version} + jar + + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8082 + + + + + + + + + + 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 + + + + + + + + + + + entryPoints + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/*EntryPointsTest.java + + + + + + + json + + + + + + + + + + com.baeldung.roles.custom.Application + + + + 1.1.2 + 1.6.1 + 2.6.11 + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java new file mode 100644 index 0000000000..ab2cc71fec --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java @@ -0,0 +1,64 @@ +package com.baeldung.relationships; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +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.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@SpringBootApplication +@PropertySource({"classpath:persistence-h2.properties", "classpath:application-defaults.properties"}) +@EnableJpaRepositories(basePackages = {"com.baeldung.relationships.repositories"}) +@EnableWebMvc +@Import(SpringSecurityConfig.class) +public class AppConfig extends WebMvcConfigurerAdapter { + + @Autowired + private Environment env; + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(env.getProperty("driverClassName")); + dataSource.setUrl(env.getProperty("url")); + dataSource.setUsername(env.getProperty("user")); + dataSource.setPassword(env.getProperty("password")); + return dataSource; + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "com.baeldung.relationships.models" }); + em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + em.setJpaProperties(additionalProperties()); + return em; + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + if (env.getProperty("hibernate.hbm2ddl.auto") != null) { + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + } + if (env.getProperty("hibernate.dialect") != null) { + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + } + if (env.getProperty("hibernate.show_sql") != null) { + hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); + } + return hibernateProperties; + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java new file mode 100644 index 0000000000..88814038a8 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java @@ -0,0 +1,89 @@ +package com.baeldung.relationships; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.relationships.security.AuthenticationSuccessHandlerImpl; +import com.baeldung.relationships.security.CustomUserDetailsService; + +@Configuration +@EnableWebSecurity +@ComponentScan("com.baeldung.security") +public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private WebApplicationContext applicationContext; + private CustomUserDetailsService userDetailsService; + @Autowired + private AuthenticationSuccessHandlerImpl successHandler; + @Autowired + private DataSource dataSource; + + @PostConstruct + public void completeSetup() { + userDetailsService = applicationContext.getBean(CustomUserDetailsService.class); + } + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService) + .passwordEncoder(encoder()) + .and() + .authenticationProvider(authenticationProvider()) + .jdbcAuthentication() + .dataSource(dataSource); + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring() + .antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/login") + .permitAll() + .and() + .formLogin() + .permitAll() + .successHandler(successHandler) + .and() + .csrf() + .disable(); + } + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + authProvider.setUserDetailsService(userDetailsService); + authProvider.setPasswordEncoder(encoder()); + return authProvider; + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(11); + } + + @Bean + public SecurityEvaluationContextExtension securityEvaluationContextExtension() { + return new SecurityEvaluationContextExtension(); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java index e48233f90a..2efd24e879 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.relationships.models; import java.util.Date; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java index b2e45009f6..d8496f89be 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java @@ -1,16 +1,19 @@ -package com.baeldung.models; +package com.baeldung.relationships.models; import java.util.HashSet; import java.util.Set; +import javax.persistence.CollectionTable; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.persistence.Table; @Entity +@Table(name = "Tweet") public class Tweet { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) @@ -18,7 +21,8 @@ public class Tweet { private String tweet; private String owner; @ElementCollection(targetClass = String.class, fetch = FetchType.EAGER) - private Set likes = new HashSet(); + @CollectionTable(name = "Tweet_Likes") + private Set likes = new HashSet<>(); public long getId() { return id; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java similarity index 84% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java index 7d6446ed0d..4e4b16a151 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java @@ -1,11 +1,11 @@ -package com.baeldung.data.repositories; +package com.baeldung.relationships.repositories; 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 com.baeldung.models.Tweet; +import com.baeldung.relationships.models.Tweet; public interface TweetRepository extends PagingAndSortingRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/UserRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/UserRepository.java new file mode 100644 index 0000000000..883ea332f8 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/UserRepository.java @@ -0,0 +1,23 @@ +package com.baeldung.relationships.repositories; + +import java.util.Date; +import java.util.List; + +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.relationships.models.AppUser; + +public interface UserRepository extends CrudRepository { + AppUser findByUsername(String username); + + List findByName(String name); + + @Query("UPDATE AppUser u SET u.lastLogin=:lastLogin WHERE u.username = ?#{ principal?.username }") + @Modifying + @Transactional + public void updateLastLogin(@Param("lastLogin") Date lastLogin); +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AppUserPrincipal.java similarity index 93% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AppUserPrincipal.java index 195f9f7bf6..1ae7d95e41 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AppUserPrincipal.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.relationships.security; import java.util.Collection; import java.util.Collections; @@ -8,7 +8,7 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; -import com.baeldung.models.AppUser; +import com.baeldung.relationships.models.AppUser; public class AppUserPrincipal implements UserDetails { diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java similarity index 88% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java index 3fc2bc6559..1b85294467 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.relationships.security; import java.io.IOException; import java.util.Date; @@ -12,7 +12,7 @@ import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; -import com.baeldung.data.repositories.UserRepository; +import com.baeldung.relationships.repositories.UserRepository; @Component public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler { diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java similarity index 87% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java index 016f4f7fa9..10c266bb74 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.relationships.security; import javax.annotation.PostConstruct; @@ -9,8 +9,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.data.repositories.UserRepository; -import com.baeldung.models.AppUser; +import com.baeldung.relationships.repositories.UserRepository; +import com.baeldung.relationships.models.AppUser; @Service public class CustomUserDetailsService implements UserDetailsService { diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/util/DummyContentUtil.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/util/DummyContentUtil.java index f1640264d2..b8e5192b48 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/util/DummyContentUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.util; +package com.baeldung.relationships.util; import java.util.ArrayList; import java.util.Collection; @@ -10,8 +10,8 @@ import java.util.stream.IntStream; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import com.baeldung.models.AppUser; -import com.baeldung.models.Tweet; +import com.baeldung.relationships.models.AppUser; +import com.baeldung.relationships.models.Tweet; public class DummyContentUtil { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/Application.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/Application.java new file mode 100644 index 0000000000..e7ace1f962 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/Application.java @@ -0,0 +1,16 @@ +package com.baeldung.roles.custom; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@ComponentScan("com.baeldung.roles.custom") +@PropertySource("classpath:application-defaults.properties") +public class Application extends SpringBootServletInitializer { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MethodSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MethodSecurityConfig.java new file mode 100644 index 0000000000..57ab8b120f --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MethodSecurityConfig.java @@ -0,0 +1,21 @@ +package com.baeldung.roles.custom.config; + +import com.baeldung.roles.custom.security.CustomMethodSecurityExpressionHandler; +import com.baeldung.roles.custom.security.CustomPermissionEvaluator; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; + +@Configuration +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { + + @Override + protected MethodSecurityExpressionHandler createExpressionHandler() { + // final DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); + final CustomMethodSecurityExpressionHandler expressionHandler = new CustomMethodSecurityExpressionHandler(); + expressionHandler.setPermissionEvaluator(new CustomPermissionEvaluator()); + return expressionHandler; + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MvcConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MvcConfig.java new file mode 100644 index 0000000000..c99d1e38a5 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MvcConfig.java @@ -0,0 +1,41 @@ +package com.baeldung.roles.custom.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@EnableWebMvc +public class MvcConfig implements WebMvcConfigurer { + + public MvcConfig() { + super(); + } + + // + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java new file mode 100644 index 0000000000..6bf04120ab --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.roles.custom.config; + +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.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final HttpSecurity http) throws Exception { + http.csrf() + .disable() + .authorizeRequests() + .anyRequest() + .authenticated() + .and() + .formLogin() + .permitAll(); + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(11); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java index f0fcce3908..ab57e7436c 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java @@ -1,16 +1,16 @@ -package org.baeldung.custom.persistence; +package com.baeldung.roles.custom.persistence; import java.util.Arrays; import java.util.HashSet; import javax.annotation.PostConstruct; -import org.baeldung.custom.persistence.dao.OrganizationRepository; -import org.baeldung.custom.persistence.dao.PrivilegeRepository; -import org.baeldung.custom.persistence.dao.UserRepository; -import org.baeldung.custom.persistence.model.Organization; -import org.baeldung.custom.persistence.model.Privilege; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.dao.OrganizationRepository; +import com.baeldung.roles.custom.persistence.dao.PrivilegeRepository; +import com.baeldung.roles.custom.persistence.dao.UserRepository; +import com.baeldung.roles.custom.persistence.model.Organization; +import com.baeldung.roles.custom.persistence.model.Privilege; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/OrganizationRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/OrganizationRepository.java new file mode 100644 index 0000000000..2f585f3527 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/OrganizationRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.roles.custom.persistence.dao; + +import com.baeldung.roles.custom.persistence.model.Organization; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface OrganizationRepository extends JpaRepository { + + public Organization findByName(String name); + +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/PrivilegeRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/PrivilegeRepository.java new file mode 100644 index 0000000000..c83e0f505e --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/PrivilegeRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.roles.custom.persistence.dao; + +import com.baeldung.roles.custom.persistence.model.Privilege; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PrivilegeRepository extends JpaRepository { + + public Privilege findByName(String name); + +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/UserRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/UserRepository.java new file mode 100644 index 0000000000..884a998219 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/UserRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.roles.custom.persistence.dao; + +import com.baeldung.roles.custom.persistence.model.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.transaction.annotation.Transactional; + +public interface UserRepository extends JpaRepository { + + User findByUsername(final String username); + + @Transactional + void removeUserByUsername(String username); + +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java new file mode 100644 index 0000000000..3dbf48f7ce --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java @@ -0,0 +1,94 @@ +package com.baeldung.roles.custom.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false) + private String name; + + // + + public Foo() { + super(); + } + + public Foo(String name) { + super(); + this.name = name; + } + + // + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + // + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + 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 Foo other = (Foo) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java index 1fdb88e320..0d0220b6b2 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.persistence.model; +package com.baeldung.roles.custom.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java new file mode 100644 index 0000000000..60e0506641 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java @@ -0,0 +1,95 @@ +package com.baeldung.roles.custom.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Privilege { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String name; + + // + + public Privilege() { + super(); + } + + public Privilege(String name) { + super(); + this.name = name; + } + + // + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + // + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Privilege [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + 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 Privilege other = (Privilege) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java new file mode 100644 index 0000000000..219f40a3df --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java @@ -0,0 +1,155 @@ +package com.baeldung.roles.custom.persistence.model; + +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "user_table") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String username; + + private String password; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "users_privileges", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")) + private Set privileges; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "organization_id", referencedColumnName = "id") + private Organization organization; + + // + + public User() { + super(); + } + + // + 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 String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Set getPrivileges() { + return privileges; + } + + public void setPrivileges(Set privileges) { + this.privileges = privileges; + } + + public Organization getOrganization() { + return organization; + } + + public void setOrganization(Organization organization) { + this.organization = organization; + } + + // + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append(", privileges=").append(privileges).append(", organization=").append(organization).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + result = (prime * result) + ((organization == null) ? 0 : organization.hashCode()); + result = (prime * result) + ((password == null) ? 0 : password.hashCode()); + result = (prime * result) + ((privileges == null) ? 0 : privileges.hashCode()); + result = (prime * result) + ((username == null) ? 0 : username.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 User other = (User) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (organization == null) { + if (other.organization != null) { + return false; + } + } else if (!organization.equals(other.organization)) { + return false; + } + if (password == null) { + if (other.password != null) { + return false; + } + } else if (!password.equals(other.password)) { + return false; + } + if (privileges == null) { + if (other.privileges != null) { + return false; + } + } else if (!privileges.equals(other.privileges)) { + return false; + } + if (username == null) { + if (other.username != null) { + return false; + } + } else if (!username.equals(other.username)) { + return false; + } + return true; + } +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionHandler.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionHandler.java index 646f5a387f..76e94a9dd4 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import org.aopalliance.intercept.MethodInvocation; import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionRoot.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionRoot.java index b2f2be8cf5..dd9f6a5786 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionRoot.java @@ -1,6 +1,6 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.security.access.expression.SecurityExpressionRoot; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.core.Authentication; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomPermissionEvaluator.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomPermissionEvaluator.java index f436b4488b..d69e405b28 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomPermissionEvaluator.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import java.io.Serializable; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MySecurityExpressionRoot.java similarity index 98% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MySecurityExpressionRoot.java index 03d18cb755..8448ad9075 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MySecurityExpressionRoot.java @@ -1,11 +1,11 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Set; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.security.access.PermissionEvaluator; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.access.hierarchicalroles.RoleHierarchy; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserDetailsService.java new file mode 100644 index 0000000000..c6514d6c05 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserDetailsService.java @@ -0,0 +1,31 @@ +package com.baeldung.roles.custom.security; + +import com.baeldung.roles.custom.persistence.dao.UserRepository; +import com.baeldung.roles.custom.persistence.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + private UserRepository userRepository; + + public MyUserDetailsService() { + super(); + } + + // API + + @Override + public UserDetails loadUserByUsername(final String username) { + final User user = userRepository.findByUsername(username); + if (user == null) { + throw new UsernameNotFoundException(username); + } + return new MyUserPrincipal(user); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserPrincipal.java similarity index 89% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserPrincipal.java index 7d57227316..41741c64f4 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserPrincipal.java @@ -1,11 +1,11 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.baeldung.custom.persistence.model.Privilege; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.model.Privilege; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/web/MainController.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/web/MainController.java new file mode 100644 index 0000000000..beb12f7749 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/web/MainController.java @@ -0,0 +1,68 @@ +package com.baeldung.roles.custom.web; + +import com.baeldung.roles.custom.persistence.dao.OrganizationRepository; +import com.baeldung.roles.custom.persistence.model.Foo; +import com.baeldung.roles.custom.persistence.model.Organization; +import com.baeldung.roles.custom.security.MyUserPrincipal; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.stereotype.Controller; +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.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +@Controller +public class MainController { + + @Autowired + private OrganizationRepository organizationRepository; + + // @PostAuthorize("hasPermission(returnObject, 'read')") + @PreAuthorize("hasPermission(#id, 'Foo', 'read')") + @GetMapping("/foos/{id}") + @ResponseBody + public Foo findById(@PathVariable final long id) { + return new Foo("Sample"); + } + + @PreAuthorize("hasPermission(#foo, 'write')") + @PostMapping("/foos") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo create(@RequestBody final Foo foo) { + return foo; + } + + // + + @PreAuthorize("hasAuthority('FOO_READ_PRIVILEGE')") + @GetMapping("/foos") + @ResponseBody + public Foo findFooByName(@RequestParam final String name) { + return new Foo(name); + } + + // + + @PreAuthorize("isMember(#id)") + @GetMapping("/organizations/{id}") + @ResponseBody + public Organization findOrgById(@PathVariable final long id) { + return organizationRepository.findById(id) + .orElse(null); + } + + @PreAuthorize("hasPermission(#id, 'Foo', 'read')") + @GetMapping("/user") + @ResponseBody + public MyUserPrincipal retrieveUserDetails(@AuthenticationPrincipal MyUserPrincipal principal) { + return principal; + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/IpApplication.java similarity index 80% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/IpApplication.java index b68abbaed1..b9a86fee3e 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/IpApplication.java @@ -1,11 +1,13 @@ -package org.baeldung.ip; +package com.baeldung.roles.ip; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; @SpringBootApplication +@ComponentScan("com.baeldung.ip") @PropertySource("classpath:application-defaults.properties") public class IpApplication extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/CustomIpAuthenticationProvider.java similarity index 98% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/CustomIpAuthenticationProvider.java index 078dd81259..adcadb65e8 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/CustomIpAuthenticationProvider.java @@ -1,4 +1,4 @@ -package org.baeldung.ip.config; +package com.baeldung.roles.ip.config; import java.util.ArrayList; import java.util.HashSet; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java new file mode 100644 index 0000000000..46ba62afb3 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java @@ -0,0 +1,36 @@ +package com.baeldung.roles.ip.config; + +import org.springframework.beans.factory.annotation.Autowired; +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//(debug = true) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private CustomIpAuthenticationProvider authenticationProvider; + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("john").password("{noop}123").authorities("ROLE_USER"); + // auth.authenticationProvider(authenticationProvider); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() +// .antMatchers("/foos/**").hasIpAddress("11.11.11.11") + .antMatchers("/foos/**").access("isAuthenticated() and hasIpAddress('11.11.11.11')") + .anyRequest().authenticated() + .and().formLogin().permitAll() + .and().csrf().disable(); + // @formatter:on + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityXmlConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityXmlConfig.java new file mode 100644 index 0000000000..4b2cf43f6a --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityXmlConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.roles.ip.config; + + +//@Configuration +//@EnableWebSecurity +//@ImportResource({ "classpath:spring-security-ip.xml" }) +public class SecurityXmlConfig { + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java new file mode 100644 index 0000000000..438b668c5f --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java @@ -0,0 +1,42 @@ +package com.baeldung.roles.ip.web; + +import java.util.List; + +import javax.servlet.Filter; +import javax.servlet.http.HttpServletRequest; + +import com.baeldung.roles.custom.persistence.model.Foo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.stereotype.Controller; +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; + +@Controller +public class MainController { + + @Autowired + @Qualifier("springSecurityFilterChain") + private Filter springSecurityFilterChain; + + @RequestMapping(method = RequestMethod.GET, value = "/filters") + @ResponseBody + public void getFilters() { + FilterChainProxy filterChainProxy = (FilterChainProxy) springSecurityFilterChain; + List list = filterChainProxy.getFilterChains(); + list.stream() + .flatMap(chain -> chain.getFilters().stream()) + .forEach(filter -> System.out.println(filter.getClass())); + } + + @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") + @ResponseBody + public Foo findById(@PathVariable final long id, HttpServletRequest request) { + return new Foo("Sample"); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/CustomAuthenticationProvider.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/CustomAuthenticationProvider.java new file mode 100644 index 0000000000..5168e64b4a --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/CustomAuthenticationProvider.java @@ -0,0 +1,38 @@ +package com.baeldung.roles.rolesauthorities; + +import com.baeldung.roles.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.persistence.UserRepository; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.userdetails.UserDetailsService; + +public class CustomAuthenticationProvider extends DaoAuthenticationProvider { + + private final UserRepository userRepository; + @SuppressWarnings("unused") + private UserDetailsService userDetailsService; + + public CustomAuthenticationProvider(UserRepository userRepository, UserDetailsService userDetailsService){ + super(); + this.setUserDetailsService(userDetailsService); + this.userRepository = userRepository; + } + + @Override + public Authentication authenticate(Authentication auth) throws AuthenticationException { + final User user = userRepository.findByEmail(auth.getName()); + if ((user == null)) { + throw new BadCredentialsException("Invalid username or password"); + } + final Authentication result = super.authenticate(auth); + return new UsernamePasswordAuthenticationToken(user, result.getCredentials(), result.getAuthorities()); + } + + @Override + public boolean supports(Class authentication) { + return authentication.equals(UsernamePasswordAuthenticationToken.class); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java index b0dc0b7537..23104e5292 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities; +package com.baeldung.roles.rolesauthorities; import java.io.IOException; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyUserDetailsService.java new file mode 100644 index 0000000000..18230ba794 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyUserDetailsService.java @@ -0,0 +1,61 @@ +package com.baeldung.roles.rolesauthorities; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import com.baeldung.roles.rolesauthorities.model.Role; +import com.baeldung.roles.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.persistence.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("userDetailsService") +@Transactional +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + private UserRepository userRepository; + + public MyUserDetailsService() { + super(); + } + + // API + + @Override + public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { + + try { + User user = userRepository.findByEmail(email); + if (user == null) { + throw new UsernameNotFoundException("No user found with username: " + email); + } + org.springframework.security.core.userdetails.User userDetails = new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, getAuthorities(user.getRoles())); + return userDetails; + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + // UTIL + + private final Collection getAuthorities(Collection roles) { + List authorities = new ArrayList(); + for (Role role: roles) { + authorities.add(new SimpleGrantedAuthority(role.getName())); + authorities.addAll(role.getPrivileges() + .stream() + .map(p -> new SimpleGrantedAuthority(p.getName())) + .collect(Collectors.toList())); + } + return authorities; + } +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/RolesAuthoritiesApplication.java similarity index 87% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/RolesAuthoritiesApplication.java index 3c4e6f7b5a..d3e54b4303 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/RolesAuthoritiesApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities; +package com.baeldung.roles.rolesauthorities; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -8,7 +8,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration -@ComponentScan("org.baeldung.rolesauthorities") +@ComponentScan("com.baeldung.rolesauthorities") public class RolesAuthoritiesApplication extends SpringBootServletInitializer { public static void main(String[] args) { System.setProperty("spring.profiles.default", "rolesauthorities"); diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/MvcConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/MvcConfig.java new file mode 100644 index 0000000000..61394b6178 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/MvcConfig.java @@ -0,0 +1,46 @@ +package com.baeldung.roles.rolesauthorities.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@EnableWebMvc +public class MvcConfig implements WebMvcConfigurer { + + public MvcConfig() { + super(); + } + + // + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("forward:/home"); + registry.addViewController("/protectedbynothing").setViewName("rolesauthorities/protectedbynothing"); + registry.addViewController("/protectedbyrole").setViewName("rolesauthorities/protectedbyrole"); + registry.addViewController("/protectedbyauthority").setViewName("rolesauthorities/protectedbyauthority"); + registry.addViewController("/login").setViewName("rolesauthorities/login"); + registry.addViewController("/home").setViewName("rolesauthorities/home"); + registry.addViewController("/logout"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java new file mode 100644 index 0000000000..cb8476fcc7 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java @@ -0,0 +1,90 @@ +package com.baeldung.roles.rolesauthorities.config; + +import com.baeldung.roles.rolesauthorities.CustomAuthenticationProvider; +import com.baeldung.roles.rolesauthorities.persistence.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; + +@Configuration +@ComponentScan(basePackages = {"com.baeldung.rolesauthorities"}) +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private LogoutSuccessHandler myLogoutSuccessHandler; + + public SecurityConfig() { + super(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(authProvider()); + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring() + .antMatchers("/resources/**"); + } + + + @Override + protected void configure(HttpSecurity http) throws Exception { + + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/login*", "/logout*", "/protectedbynothing*", "/home*").permitAll() + .antMatchers("/protectedbyrole").hasRole("USER") + .antMatchers("/protectedbyauthority").hasAuthority("READ_PRIVILEGE") + .and() + .formLogin() + .loginPage("/login") + .failureUrl("/login?error=true") + .permitAll() + .and() + .logout() + .logoutSuccessHandler(myLogoutSuccessHandler) + .invalidateHttpSession(false) + .logoutSuccessUrl("/logout.html?logSucc=true") + .deleteCookies("JSESSIONID") + .permitAll(); + // @formatter:on + } + + // beans + + @Bean + public DaoAuthenticationProvider authProvider() { + final CustomAuthenticationProvider authProvider + = new CustomAuthenticationProvider(userRepository, userDetailsService); + authProvider.setPasswordEncoder(encoder()); + return authProvider; + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(11); + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java new file mode 100644 index 0000000000..507beaffa8 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java @@ -0,0 +1,89 @@ +package com.baeldung.roles.rolesauthorities.model; + +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Privilege { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String name; + + @ManyToMany(mappedBy = "privileges") + private Collection roles; + + public Privilege() { + super(); + } + + public Privilege(String name) { + super(); + this.name = name; + } + + // + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getRoles() { + return roles; + } + + public void setRoles(Collection roles) { + this.roles = roles; + } + + @Override + public int hashCode() { + int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Privilege other = (Privilege) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Privilege [name=").append(name).append("]").append("[id=").append(id).append("]"); + return builder.toString(); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java new file mode 100644 index 0000000000..a284d92090 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java @@ -0,0 +1,104 @@ +package com.baeldung.roles.rolesauthorities.model; + +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; + +@Entity +public class Role { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @ManyToMany(mappedBy = "roles") + private Collection users; + + @ManyToMany + @JoinTable(name = "roles_privileges", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")) + private Collection privileges; + + private String name; + + public Role() { + super(); + } + + public Role(String name) { + super(); + this.name = name; + } + + // + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getUsers() { + return users; + } + + public void setUsers(Collection users) { + this.users = users; + } + + public Collection getPrivileges() { + return privileges; + } + + public void setPrivileges(Collection privileges) { + this.privileges = privileges; + } + + @Override + public int hashCode() { + int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Role role = (Role) obj; + if (!role.equals(role.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]"); + return builder.toString(); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java new file mode 100644 index 0000000000..ebf0c9b310 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java @@ -0,0 +1,147 @@ +package com.baeldung.roles.rolesauthorities.model; + +import java.util.Collection; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + + +@Entity +@Table(name = "user_account") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String firstName; + + private String lastName; + + private String email; + + @Column(length = 60) + private String password; + + private boolean enabled; + + private boolean isUsing2FA; + + // + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) + private Collection roles; + + public User() { + super(); + this.enabled = false; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String username) { + this.email = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Collection getRoles() { + return roles; + } + + public void setRoles(Collection roles) { + this.roles = roles; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public boolean isUsing2FA() { + return isUsing2FA; + } + + public void setUsing2FA(boolean isUsing2FA) { + this.isUsing2FA = isUsing2FA; + } + + @Override + public int hashCode() { + int prime = 31; + int result = 1; + result = (prime * result) + ((email == null) ? 0 : email.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + User user = (User) obj; + if (!email.equals(user.email)) { + return false; + } + return true; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("User [id=").append(id).append(", firstName=") + .append(firstName).append(", lastName=").append(lastName).append(", email=").append(email).append(", password=").append(password).append(", enabled=").append(enabled).append(", roles=").append(roles).append("]"); + return builder.toString(); + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/IUserService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/IUserService.java new file mode 100644 index 0000000000..be9cb911d7 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/IUserService.java @@ -0,0 +1,9 @@ +package com.baeldung.roles.rolesauthorities.persistence; + +import com.baeldung.roles.rolesauthorities.model.User; + +public interface IUserService { + + User findUserByEmail(String email); + +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/PrivilegeRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/PrivilegeRepository.java new file mode 100644 index 0000000000..f8ba7def49 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/PrivilegeRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.roles.rolesauthorities.persistence; + +import com.baeldung.roles.rolesauthorities.model.Privilege; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PrivilegeRepository extends JpaRepository { + + Privilege findByName(String name); + + void delete(Privilege privilege); + +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/RoleRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/RoleRepository.java new file mode 100644 index 0000000000..e5833712fe --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/RoleRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.roles.rolesauthorities.persistence; + +import com.baeldung.roles.rolesauthorities.model.Role; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface RoleRepository extends JpaRepository { + + Role findByName(String name); + + void delete(Role role); + +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/SetupDataLoader.java similarity index 93% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/SetupDataLoader.java index 46dad4f06d..140fc56e53 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/SetupDataLoader.java @@ -1,13 +1,13 @@ -package org.baeldung.rolesauthorities.persistence; +package com.baeldung.roles.rolesauthorities.persistence; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; -import org.baeldung.rolesauthorities.model.Privilege; -import org.baeldung.rolesauthorities.model.Role; -import org.baeldung.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.model.Privilege; +import com.baeldung.roles.rolesauthorities.model.Role; +import com.baeldung.roles.rolesauthorities.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserRepository.java new file mode 100644 index 0000000000..6801eec01d --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.roles.rolesauthorities.persistence; + +import com.baeldung.roles.rolesauthorities.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + + User findByEmail(String email); + + void delete(User user); + +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java new file mode 100644 index 0000000000..17770e5cd0 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java @@ -0,0 +1,19 @@ +package com.baeldung.roles.rolesauthorities.persistence; + +import javax.transaction.Transactional; + +import com.baeldung.roles.rolesauthorities.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +@Transactional +public class UserService implements IUserService { + + @Autowired + private UserRepository repository; + + public User findUserByEmail(String email) { + return repository.findByEmail(email); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java index 2beda1e557..6970441a4e 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java @@ -1,4 +1,4 @@ -package org.baeldung.voter; +package com.baeldung.roles.voter; import java.time.LocalDateTime; import java.util.Collection; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterApplication.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterApplication.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java index d2078e6115..d3e0652ae9 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.voter; +package com.baeldung.roles.voter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -7,7 +7,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration -@ComponentScan(basePackages = { "org.baeldung.voter" }) +@ComponentScan(basePackages = {"com.baeldung.voter"}) public class VoterApplication { public static void main(String[] args) { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java new file mode 100644 index 0000000000..f11a4ae06c --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.roles.voter; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * Created by ambrusadrianz on 30/09/2016. + */ + +@Configuration +public class VoterMvcConfig implements WebMvcConfigurer { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("private"); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java new file mode 100644 index 0000000000..8a0f438b49 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java @@ -0,0 +1,54 @@ +package com.baeldung.roles.voter; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.AccessDecisionManager; +import org.springframework.security.access.AccessDecisionVoter; +import org.springframework.security.access.vote.AuthenticatedVoter; +import org.springframework.security.access.vote.RoleVoter; +import org.springframework.security.access.vote.UnanimousBased; +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.access.expression.WebExpressionVoter; + +import java.util.Arrays; +import java.util.List; + +@Configuration +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + // @formatter: off + auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("pass")).roles("USER").and().withUser("admin").password(passwordEncoder().encode("pass")).roles("ADMIN"); + // @formatter: on + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter: off + http + // needed so our login could work + .csrf().disable().authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager()).antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER").and().formLogin().permitAll().and().logout().permitAll() + .deleteCookies("JSESSIONID").logoutSuccessUrl("/login"); + // @formatter: on + } + + @Bean + public AccessDecisionManager accessDecisionManager() { + // @formatter: off + List> decisionVoters = Arrays.asList(new WebExpressionVoter(), new RoleVoter(), new AuthenticatedVoter(), new MinuteBasedVoter()); + // @formatter: on + return new UnanimousBased(decisionVoters); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/XmlSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/XmlSecurityConfig.java new file mode 100644 index 0000000000..0ef2ef51c7 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/XmlSecurityConfig.java @@ -0,0 +1,12 @@ +package com.baeldung.roles.voter; + +/** + * Created by ambrusadrianz on 09/10/2016. + */ +// @Configuration +// @ImportResource({ "classpath:spring-security-custom-voter.xml" }) +public class XmlSecurityConfig { + public XmlSecurityConfig() { + super(); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/application-defaults.properties b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/application-defaults.properties similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/application-defaults.properties rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/application-defaults.properties diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/application.properties b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/application.properties similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/application.properties rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/application.properties diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/logback.xml b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/logback.xml @@ -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-modules/spring-security-mvc-boot/src/main/resources/persistence-h2.properties b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/persistence-h2.properties rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/persistence-h2.properties diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/spring-security-custom-voter.xml b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-custom-voter.xml similarity index 90% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/spring-security-custom-voter.xml rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-custom-voter.xml index 0b334a3694..9f510280a1 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/resources/spring-security-custom-voter.xml +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-custom-voter.xml @@ -22,12 +22,12 @@ - + - + diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/spring-security-ip.xml b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-ip.xml similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/spring-security-ip.xml rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-ip.xml diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/403.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/403.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/403.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/403.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/index.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/index.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/index.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/index.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/login.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/login.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/login.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/login.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/loginAdmin.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/loginAdmin.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/loginAdmin.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/loginAdmin.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/loginUser.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/loginUser.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/loginUser.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/loginUser.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/login.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/login.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/login.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/login.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/loginWithWarning.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/loginWithWarning.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/loginWithWarning.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/loginWithWarning.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myAdminPage.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/myAdminPage.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myAdminPage.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/myAdminPage.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myGuestPage.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/myGuestPage.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myGuestPage.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/myGuestPage.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myUserPage.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/myUserPage.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myUserPage.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/multipleHttpElems/myUserPage.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/private.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/private.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/private.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/private.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/rolesauthorities/home.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/rolesauthorities/home.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/rolesauthorities/login.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/rolesauthorities/login.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/rolesauthorities/protectedbyauthority.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/rolesauthorities/protectedbyauthority.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/rolesauthorities/protectedbynothing.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/rolesauthorities/protectedbynothing.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/rolesauthorities/protectedbyrole.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/rolesauthorities/protectedbyrole.html diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/ssl/welcome.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html rename to spring-security-modules/spring-security-mvc-boot-1/src/main/resources/templates/ssl/welcome.html diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java new file mode 100644 index 0000000000..54120650d9 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java @@ -0,0 +1,111 @@ +package com.baeldung.relationships; + +import com.baeldung.relationships.repositories.TweetRepository; +import com.baeldung.relationships.repositories.UserRepository; +import com.baeldung.relationships.models.AppUser; +import com.baeldung.relationships.models.Tweet; +import com.baeldung.relationships.security.AppUserPrincipal; +import com.baeldung.relationships.util.DummyContentUtil; +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.dao.InvalidDataAccessApiUsageException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.jdbc.core.JdbcTemplate; +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.test.jdbc.JdbcTestUtils; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; + +import javax.servlet.ServletContext; +import java.util.Date; +import java.util.List; + +import static org.springframework.util.Assert.isTrue; + +@RunWith(SpringRunner.class) +@WebAppConfiguration +@ContextConfiguration +@DirtiesContext +public class SpringDataWithSecurityIntegrationTest { + 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)); + } + + /** + * This is to ensure the tables are dropped in proper order. + * After the Spring Boot 2.2.2 upgrade, DDL statements generated automatically try to drop Tweet table first. + * As a result we get org.h2.jdbc.JdbcSQLSyntaxErrorException because Tweet_Likes table depends on Tweet. + * + * @see + * StackOverflow#59364212 + * + * @see + * StackOverflow#59561551 + * + */ + @After + public void tearDown() { + JdbcTemplate jdbcTemplate = ctx.getBean(JdbcTemplate.class); + JdbcTestUtils.dropTables(jdbcTemplate, "Tweet_Likes", "Tweet"); + } + + @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(PageRequest.of(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(PageRequest.of(page != null ? page.getNumber() + 1 : 0, 5)); + } while (page != null && page.hasNext()); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/SpringContextTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/SpringContextTest.java new file mode 100644 index 0000000000..7b23b878c8 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.roles; + +import com.baeldung.roles.custom.Application; +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(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java similarity index 93% rename from spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java index dfcfcad609..5a040b8dea 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java @@ -1,9 +1,9 @@ -package org.baeldung.web; +package com.baeldung.roles.web; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import org.baeldung.custom.persistence.model.Foo; +import com.baeldung.roles.custom.persistence.model.Foo; import io.restassured.RestAssured; import io.restassured.authentication.FormAuthConfig; @@ -13,7 +13,7 @@ import io.restassured.specification.RequestSpecification; import org.junit.Test; import org.springframework.http.MediaType; - +// In order to execute these tests, com.baeldung.custom.Application needs to be running. public class ApplicationLiveTest { @Test diff --git a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java index d16acc729a..df7645150f 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.roles.web; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -7,8 +7,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.http.HttpHeaders; -import org.baeldung.custom.Application; -import org.baeldung.custom.persistence.model.Foo; +import com.baeldung.roles.custom.Application; +import com.baeldung.roles.custom.persistence.model.Foo; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -59,7 +59,7 @@ public class CustomUserDetailsServiceIntegrationTest { @WithAnonymousUser public void givenAnonymous_whenRequestFoo_thenRetrieveUnauthorized() throws Exception { this.mvc.perform(get("/foos/1").with(csrf())) - .andExpect(status().isUnauthorized()); + .andExpect(status().isFound()); } @Test diff --git a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/IpLiveTest.java similarity index 87% rename from spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/IpLiveTest.java index e12e2f87b0..2d0e2e5402 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/IpLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.roles.web; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -8,6 +8,7 @@ import io.restassured.response.Response; import org.junit.Test; +// In order to execute these tests, com.baeldung.ip.IpApplication needs to be running. public class IpLiveTest { @Test diff --git a/spring-security-modules/spring-security-mvc-boot-2/README.md b/spring-security-modules/spring-security-mvc-boot-2/README.md new file mode 100644 index 0000000000..3c95086d21 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/README.md @@ -0,0 +1,13 @@ +## Spring Boot Security MVC + +This module contains articles about Spring Security with Spring MVC in Boot applications + +### The Course +The "REST With Spring" Classes: http://github.learnspringsecurity.com + +### Relevant Articles: +- [Multiple Entry Points in Spring Security](https://www.baeldung.com/spring-security-multiple-entry-points) +- [Multiple Authentication Providers in Spring Security](https://www.baeldung.com/spring-security-multiple-auth-providers) +- [Two Login Pages with Spring Security](https://www.baeldung.com/spring-security-two-login-pages) +- [HTTPS using Self-Signed Certificate in Spring Boot](https://www.baeldung.com/spring-boot-https-self-signed-certificate) +- [Spring Security: Exploring JDBC Authentication](https://www.baeldung.com/spring-security-jdbc-authentication) \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/WebContent/META-INF/MANIFEST.MF b/spring-security-modules/spring-security-mvc-boot-2/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..254272e1c0 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/spring-security-modules/spring-security-mvc-boot-2/pom.xml b/spring-security-modules/spring-security-mvc-boot-2/pom.xml new file mode 100644 index 0000000000..668eb04cd9 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/pom.xml @@ -0,0 +1,240 @@ + + + 4.0.0 + spring-security-mvc-boot-2 + 0.0.1-SNAPSHOT + spring-security-mvc-boot-2 + war + Spring Security MVC Boot - 2 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-security + + + 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-springsecurity5 + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.security + spring-security-data + + + mysql + mysql-connector-java + runtime + + + com.h2database + h2 + + + org.postgresql + postgresql + runtime + + + org.hamcrest + hamcrest + test + + + org.springframework + spring-test + test + + + org.springframework.security + spring-security-test + test + + + taglibs + standard + ${taglibs-standard.version} + + + 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 + + + org.springframework + spring-context-support + + + net.sf.ehcache + ehcache-core + ${ehcache-core.version} + jar + + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8082 + + + + + + + + + + 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 + + + + + + + + + + + entryPoints + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/*EntryPointsTest.java + + + + + + + json + + + + + + + + + + + + com.baeldung.multiplelogin.MultipleLoginApplication + + + + + + 1.1.2 + 1.6.1 + 2.6.11 + + + diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/CustomLogoutApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/CustomLogoutApplication.java new file mode 100644 index 0000000000..39d867b1f4 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/CustomLogoutApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.customlogouthandler; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CustomLogoutApplication { + + public static void main(String[] args) { + SpringApplication.run(CustomLogoutApplication.class, args); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java new file mode 100644 index 0000000000..c363effb4e --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java @@ -0,0 +1,55 @@ +package com.baeldung.customlogouthandler; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +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.logout.HttpStatusReturningLogoutSuccessHandler; + +import com.baeldung.customlogouthandler.web.CustomLogoutHandler; + +@Configuration +@EnableWebSecurity +public class MvcConfiguration extends WebSecurityConfigurerAdapter { + + @Autowired + private DataSource dataSource; + + @Autowired + private CustomLogoutHandler logoutHandler; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.httpBasic() + .and() + .authorizeRequests() + .antMatchers(HttpMethod.GET, "/user/**") + .hasRole("USER") + .and() + .logout() + .logoutUrl("/user/logout") + .addLogoutHandler(logoutHandler) + .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)) + .permitAll() + .and() + .csrf() + .disable() + .formLogin() + .disable(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource) + .usersByUsernameQuery("select login, password, true from users where login=?") + .authoritiesByUsernameQuery("select login, role from users where login=?"); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java new file mode 100644 index 0000000000..b86edc0dee --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java @@ -0,0 +1,35 @@ +package com.baeldung.customlogouthandler.services; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.springframework.stereotype.Service; + +import com.baeldung.customlogouthandler.user.User; + +@Service +public class UserCache { + + @PersistenceContext + private EntityManager entityManager; + + private final ConcurrentMap store = new ConcurrentHashMap<>(256); + + public User getByUserName(String userName) { + return store.computeIfAbsent(userName, k -> entityManager.createQuery("from User where login=:login", User.class) + .setParameter("login", k) + .getSingleResult()); + } + + public void evictUser(String userName) { + store.remove(userName); + } + + public int size() { + return store.size(); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/User.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/User.java new file mode 100644 index 0000000000..ca3a998c5c --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/User.java @@ -0,0 +1,61 @@ +package com.baeldung.customlogouthandler.user; + +import javax.persistence.*; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + @Column(unique = true) + private String login; + + private String password; + + private String role; + + private String language; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java new file mode 100644 index 0000000000..aa9a521b01 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java @@ -0,0 +1,14 @@ +package com.baeldung.customlogouthandler.user; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +public class UserUtils { + + public static String getAuthenticatedUserName() { + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); + return auth != null ? ((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername() : null; + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java new file mode 100644 index 0000000000..a89c9a570d --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java @@ -0,0 +1,28 @@ +package com.baeldung.customlogouthandler.web; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutHandler; +import org.springframework.stereotype.Service; + +import com.baeldung.customlogouthandler.services.UserCache; +import com.baeldung.customlogouthandler.user.UserUtils; + +@Service +public class CustomLogoutHandler implements LogoutHandler { + + private final UserCache userCache; + + public CustomLogoutHandler(UserCache userCache) { + this.userCache = userCache; + } + + @Override + public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + String userName = UserUtils.getAuthenticatedUserName(); + userCache.evictUser(userName); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java new file mode 100644 index 0000000000..b2d332a1bb --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java @@ -0,0 +1,30 @@ +package com.baeldung.customlogouthandler.web; + +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.ResponseBody; + +import com.baeldung.customlogouthandler.services.UserCache; +import com.baeldung.customlogouthandler.user.User; +import com.baeldung.customlogouthandler.user.UserUtils; + +@Controller +@RequestMapping(path = "/user") +public class UserController { + + private final UserCache userCache; + + public UserController(UserCache userCache) { + this.userCache = userCache; + } + + @GetMapping(path = "/language") + @ResponseBody + public String getLanguage() { + String userName = UserUtils.getAuthenticatedUserName(); + User user = userCache.getByUserName(userName); + return user.getLanguage(); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java index 6936cdc560..d71885d73c 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.h2; +package com.baeldung.jdbcauthentication.h2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java new file mode 100644 index 0000000000..50dc5b6958 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java @@ -0,0 +1,51 @@ +package com.baeldung.jdbcauthentication.h2.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity httpSecurity) throws Exception { + httpSecurity.authorizeRequests() + .antMatchers("/h2-console/**") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin() + .permitAll(); + httpSecurity.csrf() + .ignoringAntMatchers("/h2-console/**"); + httpSecurity.headers() + .frameOptions() + .sameOrigin(); + } + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource) + .withDefaultSchema() + .withUser(User.withUsername("user") + .password(passwordEncoder().encode("pass")) + .roles("USER")); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/web/UserController.java new file mode 100644 index 0000000000..03271677a4 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/web/UserController.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.h2.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java index 52934e0096..1f4c54e512 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.mysql; +package com.baeldung.jdbcauthentication.mysql; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java new file mode 100644 index 0000000000..a0584818cd --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.mysql.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration { + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource) + .usersByUsernameQuery("select email,password,enabled " + + "from bael_users " + + "where email = ?") + .authoritiesByUsernameQuery("select email,authority " + + "from authorities " + + "where email = ?"); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java new file mode 100644 index 0000000000..ed15f8bfe6 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.mysql.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java index 2c4d1a5255..4b074ef51d 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.postgre; +package com.baeldung.jdbcauthentication.postgre; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java new file mode 100644 index 0000000000..85dc9d364c --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.jdbcauthentication.postgre.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration { + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java new file mode 100644 index 0000000000..da85a46562 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.postgre.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/CustomAuthenticationProvider.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/CustomAuthenticationProvider.java new file mode 100644 index 0000000000..97a8d8ac2a --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/CustomAuthenticationProvider.java @@ -0,0 +1,31 @@ +package com.baeldung.multipleauthproviders; + +import java.util.Collections; + +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.stereotype.Component; + +@Component +public class CustomAuthenticationProvider implements AuthenticationProvider { + @Override + public Authentication authenticate(Authentication auth) throws AuthenticationException { + final String username = auth.getName(); + final String password = auth.getCredentials() + .toString(); + + if ("externaluser".equals(username) && "pass".equals(password)) { + return new UsernamePasswordAuthenticationToken(username, password, Collections.emptyList()); + } else { + throw new BadCredentialsException("External system authentication failed"); + } + } + + @Override + public boolean supports(Class auth) { + return auth.equals(UsernamePasswordAuthenticationToken.class); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthController.java similarity index 85% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthController.java index b63169bb00..0079c84c6c 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthController.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleauthproviders; +package com.baeldung.multipleauthproviders; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java index 1f641298c3..e1a437e9a9 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleauthproviders; +package com.baeldung.multipleauthproviders; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java index 3819e981a2..aa2ffc9046 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleauthproviders; +package com.baeldung.multipleauthproviders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java index 847dab073e..4ed36f770f 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleentrypoints; +package com.baeldung.multipleentrypoints; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java similarity index 99% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java index dc89c83cde..b6155fc100 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleentrypoints; +package com.baeldung.multipleentrypoints; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/PagesController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/PagesController.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/PagesController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/PagesController.java index b3462d4061..ba5028aea7 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/PagesController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/PagesController.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleentrypoints; +package com.baeldung.multipleentrypoints; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginApplication.java similarity index 85% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginApplication.java index 90bb5e4260..abba2ba339 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -7,7 +7,6 @@ import org.springframework.context.annotation.PropertySource; @SpringBootApplication @PropertySource("classpath:application-defaults.properties") -@ComponentScan("org.baeldung.multiplelogin") public class MultipleLoginApplication { public static void main(String[] args) { SpringApplication.run(MultipleLoginApplication.class, args); diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginMvcConfig.java similarity index 89% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginMvcConfig.java index 204b186411..86b3314c7c 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginMvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -6,14 +6,12 @@ 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.WebMvcConfigurer; -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.context.annotation.ComponentScan; @EnableWebMvc @Configuration -@ComponentScan("org.baeldung.controller") public class MultipleLoginMvcConfig implements WebMvcConfigurer { public MultipleLoginMvcConfig() { diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginSecurityConfig.java similarity index 99% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginSecurityConfig.java index 9962bf41a9..3d12951f39 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/UsersController.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/UsersController.java index 61d7da127c..03be0fd6b2 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/UsersController.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/HttpsEnabledApplication.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/HttpsEnabledApplication.java index 17c249067c..f6a550ae54 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/HttpsEnabledApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.ssl; +package com.baeldung.ssl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/SecurityConfig.java new file mode 100644 index 0000000000..4bddf0592a --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/SecurityConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.ssl; + +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; + +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/**") + .permitAll(); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/WelcomeController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/WelcomeController.java new file mode 100644 index 0000000000..2bd8c8cfde --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/WelcomeController.java @@ -0,0 +1,14 @@ +package com.baeldung.ssl; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class WelcomeController { + + @GetMapping("/welcome") + public String welcome() { + return "ssl/welcome"; + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-customlogouthandler.properties b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-customlogouthandler.properties new file mode 100644 index 0000000000..2cb766378d --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-customlogouthandler.properties @@ -0,0 +1,5 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/test +spring.datasource.username=test +spring.datasource.password=test + +spring.jpa.hibernate.ddl-auto=create \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-defaults.properties b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-defaults.properties new file mode 100644 index 0000000000..e2032c4a6b --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-defaults.properties @@ -0,0 +1,13 @@ +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.database=H2 +spring.jpa.show-sql=false +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect + +#logging.level.org.springframework.security.web.FilterChainProxy=DEBUG + +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/application-mysql.properties b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-mysql.properties similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/application-mysql.properties rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-mysql.properties diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/application-postgre.properties b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-postgre.properties similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/application-postgre.properties rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-postgre.properties diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/application-ssl.properties b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-ssl.properties similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/application-ssl.properties rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-ssl.properties diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application.properties b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application.properties new file mode 100644 index 0000000000..3cf12afeb9 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8082 diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/data-mysql.sql b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/data-mysql.sql similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/data-mysql.sql rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/data-mysql.sql diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/data-postgre.sql b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/data-postgre.sql similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/data-postgre.sql rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/data-postgre.sql diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/keystore/baeldung.p12 similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/keystore/baeldung.p12 diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/logback.xml b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-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-modules/spring-security-mvc-boot-2/src/main/resources/persistence-h2.properties b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/persistence-h2.properties new file mode 100644 index 0000000000..a4b2af6361 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/persistence-h2.properties @@ -0,0 +1,8 @@ +driverClassName=org.h2.Driver +url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1 +username=sa +password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/schema-mysql.sql b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/schema-mysql.sql similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/schema-mysql.sql rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/schema-mysql.sql diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/schema-postgre.sql b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/schema-postgre.sql similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/schema-postgre.sql rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/schema-postgre.sql diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/spring-security-multiple-auth-providers.xml b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/spring-security-multiple-auth-providers.xml similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/spring-security-multiple-auth-providers.xml rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/spring-security-multiple-auth-providers.xml diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/spring-security-multiple-entry.xml b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/spring-security-multiple-entry.xml similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/spring-security-multiple-entry.xml rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/spring-security-multiple-entry.xml diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/403.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/403.html new file mode 100644 index 0000000000..20550768cf --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/403.html @@ -0,0 +1,10 @@ + + + + + + + +You do not have permission to view this page. + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/adminPage.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/adminPage.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/adminPage.html rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/adminPage.html diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/index.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/index.html new file mode 100644 index 0000000000..8e7394ad6a --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/index.html @@ -0,0 +1,21 @@ + + + + +Spring Security Thymeleaf + + + + + +
+ Welcome +
+ + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/login.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/login.html new file mode 100644 index 0000000000..dd6bd04767 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/login.html @@ -0,0 +1,27 @@ + + + + +

Login

+ +
+ + + + + + + + + + + + + + +
User:
Password:
+ +
+ + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/loginAdmin.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/loginAdmin.html new file mode 100644 index 0000000000..43d0e73233 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/loginAdmin.html @@ -0,0 +1,31 @@ + + + + +Insert title here + + + +

Admin login page

+
+ + + + + + + + + + + + + +
User:
Password:
+ +
+ +

Login failed!

+ + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/loginUser.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/loginUser.html new file mode 100644 index 0000000000..bf4ddd48bc --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/loginUser.html @@ -0,0 +1,30 @@ + + + + +Login + + + +

User login page

+ +
+ + + + + + + + + + + + +
User:
Password:
+ +
+

Login failed!

+ + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/login.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/login.html new file mode 100644 index 0000000000..2119baec66 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/login.html @@ -0,0 +1,27 @@ + + + + +

Login

+ +
+ + + + + + + + + + + + + + +
Username:
Password:
+ +
+ + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/loginWithWarning.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/loginWithWarning.html new file mode 100644 index 0000000000..a5b2eaf3dc --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/loginWithWarning.html @@ -0,0 +1,28 @@ + + + + +

Login

+

Warning! You are about to access sensible data!

+ +
+ + + + + + + + + + + + + + +
Username:
Password:
+ +
+ + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html new file mode 100644 index 0000000000..676badb16f --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html @@ -0,0 +1,18 @@ + + + + +Multiple Http Elements Links + + + +Admin page +
+User page +
+Private user page +
+Guest page + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myAdminPage.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myAdminPage.html new file mode 100644 index 0000000000..3003833562 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myAdminPage.html @@ -0,0 +1,13 @@ + + + + +Admin Page + + +Welcome admin! + +

+Back to links + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myGuestPage.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myGuestPage.html new file mode 100644 index 0000000000..47a4c9c44a --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myGuestPage.html @@ -0,0 +1,13 @@ + + + + +Guest Page + + +Welcome guest! + +

+Back to links + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html new file mode 100644 index 0000000000..52045ec320 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html @@ -0,0 +1,13 @@ + + + + +Insert title here + + +Welcome user to your private page! Logout + +

+Back to links + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myUserPage.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myUserPage.html new file mode 100644 index 0000000000..f6c2def0b8 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/multipleHttpElems/myUserPage.html @@ -0,0 +1,13 @@ + + + + +User Page + + +Welcome user! Logout + +

+Back to links + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/private.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/private.html new file mode 100644 index 0000000000..035d84bbbd --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/private.html @@ -0,0 +1,10 @@ + + + + Private + + +

Congrats!

+ + \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/protectedLinks.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/protectedLinks.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/protectedLinks.html rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/protectedLinks.html diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/ssl/welcome.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/ssl/welcome.html new file mode 100644 index 0000000000..93b3577f5c --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/ssl/welcome.html @@ -0,0 +1 @@ +

Welcome to Secured Site

\ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/userPage.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/userPage.html similarity index 100% rename from spring-security-modules/spring-security-mvc-boot/src/main/resources/templates/userPage.html rename to spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/userPage.html diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java new file mode 100644 index 0000000000..cd8a1a72d6 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java @@ -0,0 +1,108 @@ +package com.baeldung.customlogouthandler; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.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.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.jdbc.SqlGroup; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.customlogouthandler.services.UserCache; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = { CustomLogoutApplication.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SqlGroup({ @Sql(value = "classpath:customlogouthandler/before.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD), @Sql(value = "classpath:customlogouthandler/after.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) }) +@TestPropertySource(locations="classpath:customlogouthandler/application.properties") +class CustomLogoutHandlerIntegrationTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Autowired + private UserCache userCache; + + @LocalServerPort + private int port; + + @Test + public void whenLogin_thenUseUserCache() { + // User cache should be empty on start + assertThat(userCache.size()).isEqualTo(0); + + // Request using first login + ResponseEntity response = restTemplate.withBasicAuth("user", "pass") + .getForEntity(getLanguageUrl(), String.class); + + assertThat(response.getBody()).contains("english"); + + // User cache must contain the user + assertThat(userCache.size()).isEqualTo(1); + + // Getting the session cookie + HttpHeaders requestHeaders = new HttpHeaders(); + requestHeaders.add("Cookie", response.getHeaders() + .getFirst(HttpHeaders.SET_COOKIE)); + + // Request with the session cookie + response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getBody()).contains("english"); + + // Logging out using the session cookies + response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode() + .value()).isEqualTo(200); + } + + @Test + public void whenLogout_thenCacheIsEmpty() { + // User cache should be empty on start + assertThat(userCache.size()).isEqualTo(0); + + // Request using first login + ResponseEntity response = restTemplate.withBasicAuth("user", "pass") + .getForEntity(getLanguageUrl(), String.class); + + assertThat(response.getBody()).contains("english"); + + // User cache must contain the user + assertThat(userCache.size()).isEqualTo(1); + + // Getting the session cookie + HttpHeaders requestHeaders = new HttpHeaders(); + requestHeaders.add("Cookie", response.getHeaders() + .getFirst(HttpHeaders.SET_COOKIE)); + + // Logging out using the session cookies + response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode() + .value()).isEqualTo(200); + + // User cache must be empty now + // this is the reaction on custom logout filter execution + assertThat(userCache.size()).isEqualTo(0); + + // Assert unauthorized request + response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode() + .value()).isEqualTo(401); + } + + private String getLanguageUrl() { + return "http://localhost:" + port + "/user/language"; + } + + private String getLogoutUrl() { + return "http://localhost:" + port + "/user/logout"; + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/SpringContextTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/SpringContextTest.java new file mode 100644 index 0000000000..5bd2a0ce27 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.jdbcauthentication.h2; + +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(classes = H2JdbcAuthenticationApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..12b5ca5867 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.h2.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +import io.restassured.authentication.FormAuthConfig; +import io.restassured.filter.session.SessionFilter; + +/** + * This Live Test requires the H2JdbcAuthenticationApplication application to be up and running + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + SessionFilter filter = new SessionFilter(); + given().auth() + .form("user", "pass", new FormAuthConfig("/login", "username", "password").withCsrfFieldName("_csrf")) + .and() + .filter(filter) + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user")) + .body("name", is("user")); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..79bc84ea69 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.mysql.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +/** + * This Live Test requires: + * * a MySql instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication + * (e.g. with the following command `docker run -p 3306:3306 --name bael-mysql -e MYSQL_ROOT_PASSWORD=pass -e MYSQL_DATABASE=jdbc_authentication mysql:latest`) + * * the service up and running + * + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + given().auth() + .preemptive() + .basic("user@email.com", "pass") + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user@email.com")) + .body("name", is("user@email.com")); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..e6426a843e --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.postgre.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +/** + * This Live Test requires: + * * a PostgreSQL instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication + * (e.g. with the following command `docker run -p 5432:5432 --name bael-postgre -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=jdbc_authentication postgres:latest`) + * * the service up and running + * + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + given().auth() + .preemptive() + .basic("user", "pass") + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user")) + .body("name", is("user")); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/HttpsApplicationIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/HttpsApplicationIntegrationTest.java index fe7883ec94..63d47e6a46 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/HttpsApplicationIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.web; +package com.baeldung.web; import org.apache.http.client.HttpClient; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; -import org.baeldung.ssl.HttpsEnabledApplication; +import com.baeldung.ssl.HttpsEnabledApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; diff --git a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java index 9ef09f1f67..c5ef469fe8 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.web; +package com.baeldung.web; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; -import org.baeldung.multipleauthproviders.MultipleAuthProvidersApplication; +import com.baeldung.multipleauthproviders.MultipleAuthProvidersApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleEntryPointsIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleEntryPointsIntegrationTest.java index 157480c3f1..352b4af244 100644 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleEntryPointsIntegrationTest.java @@ -1,6 +1,5 @@ -package org.baeldung.web; +package com.baeldung.web; -import org.baeldung.multipleentrypoints.MultipleEntryPointsApplication; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -15,6 +14,9 @@ import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.baeldung.multipleentrypoints.MultipleEntryPointsApplication; + import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; @RunWith(SpringRunner.class) diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/after.sql b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/after.sql new file mode 100644 index 0000000000..df6f312987 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/after.sql @@ -0,0 +1 @@ +delete from users; \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties new file mode 100644 index 0000000000..84347c2664 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties @@ -0,0 +1,4 @@ +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=test +spring.datasource.password=test \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/before.sql b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/before.sql new file mode 100644 index 0000000000..bb0a85f613 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/before.sql @@ -0,0 +1 @@ +insert into users (login, password, role, language) values ('user', '{noop}pass', 'ROLE_USER', 'english'); \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/README.md b/spring-security-modules/spring-security-mvc-boot/README.md deleted file mode 100644 index a1056cc130..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/README.md +++ /dev/null @@ -1,21 +0,0 @@ -## Spring Boot Security MVC - -This module contains articles about Spring Security with Spring MVC in Boot applications - -### The Course -The "REST With Spring" Classes: http://github.learnspringsecurity.com - -### Relevant Articles: -- [A Custom Security Expression with Spring Security](https://www.baeldung.com/spring-security-create-new-custom-security-expression) -- [Custom AccessDecisionVoters in Spring Security](https://www.baeldung.com/spring-security-custom-voter) -- [Spring Security: Authentication with a Database-backed UserDetailsService](https://www.baeldung.com/spring-security-authentication-with-a-database) -- [Two Login Pages with Spring Security](https://www.baeldung.com/spring-security-two-login-pages) -- [Multiple Entry Points in Spring Security](https://www.baeldung.com/spring-security-multiple-entry-points) -- [Multiple Authentication Providers in Spring Security](https://www.baeldung.com/spring-security-multiple-auth-providers) -- [Granted Authority Versus Role in Spring Security](https://www.baeldung.com/spring-security-granted-authority-vs-role) -- [Spring Data with Spring Security](https://www.baeldung.com/spring-data-security) -- [Spring Security – Whitelist IP Range](https://www.baeldung.com/spring-security-whitelist-ip-range) -- [Find the Registered Spring Security Filters](https://www.baeldung.com/spring-security-registered-filters) -- [HTTPS using Self-Signed Certificate in Spring Boot](https://www.baeldung.com/spring-boot-https-self-signed-certificate) -- [Spring Security: Exploring JDBC Authentication](https://www.baeldung.com/spring-security-jdbc-authentication) - diff --git a/spring-security-modules/spring-security-mvc-boot/pom.xml b/spring-security-modules/spring-security-mvc-boot/pom.xml deleted file mode 100644 index 489ec2d427..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/pom.xml +++ /dev/null @@ -1,249 +0,0 @@ - - - 4.0.0 - spring-security-mvc-boot - 0.0.1-SNAPSHOT - spring-security-mvc-boot - war - Spring Security MVC Boot - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-security - - - 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-springsecurity5 - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.security - spring-security-data - - - mysql - mysql-connector-java - runtime - - - com.h2database - h2 - - - org.postgresql - postgresql - runtime - - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - - - org.springframework - spring-test - test - - - org.springframework.security - spring-security-test - test - - - taglibs - standard - ${taglibs-standard.version} - - - 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 - - - org.springframework - spring-context-support - - - net.sf.ehcache - ehcache-core - ${ehcache-core.version} - jar - - - - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - tomcat8x - embedded - - - - - - - 8082 - - - - - - - - - - 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 - - - - - - - - - - - entryPoints - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/*EntryPointsTest.java - - - - - - - json - - - - - - - - - - org.baeldung.custom.Application - - - - - - - - - - 1.1.2 - 1.6.1 - 2.6.11 - - - diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java deleted file mode 100644 index 8719e39a20..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung; - -import java.util.Properties; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -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.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@SpringBootApplication -@PropertySource({"classpath:persistence-h2.properties", "classpath:application-defaults.properties"}) -@EnableJpaRepositories(basePackages = { "com.baeldung.data.repositories" }) -@EnableWebMvc -@Import(SpringSecurityConfig.class) -public class AppConfig extends WebMvcConfigurerAdapter { - - @Autowired - private Environment env; - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(env.getProperty("driverClassName")); - dataSource.setUrl(env.getProperty("url")); - dataSource.setUsername(env.getProperty("user")); - dataSource.setPassword(env.getProperty("password")); - return dataSource; - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.models" }); - em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); - em.setJpaProperties(additionalProperties()); - return em; - } - - final Properties additionalProperties() { - final Properties hibernateProperties = new Properties(); - if (env.getProperty("hibernate.hbm2ddl.auto") != null) { - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - } - if (env.getProperty("hibernate.dialect") != null) { - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - } - if (env.getProperty("hibernate.show_sql") != null) { - hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); - } - return hibernateProperties; - } - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java deleted file mode 100644 index ee13678a24..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.baeldung; - -import javax.annotation.PostConstruct; -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension; -import org.springframework.web.context.WebApplicationContext; - -import com.baeldung.security.AuthenticationSuccessHandlerImpl; -import com.baeldung.security.CustomUserDetailsService; - -@Configuration -@EnableWebSecurity -@ComponentScan("com.baeldung.security") -public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private WebApplicationContext applicationContext; - private CustomUserDetailsService userDetailsService; - @Autowired - private AuthenticationSuccessHandlerImpl successHandler; - @Autowired - private DataSource dataSource; - - @PostConstruct - public void completeSetup() { - userDetailsService = applicationContext.getBean(CustomUserDetailsService.class); - } - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService) - .passwordEncoder(encoder()) - .and() - .authenticationProvider(authenticationProvider()) - .jdbcAuthentication() - .dataSource(dataSource); - } - - @Override - public void configure(WebSecurity web) throws Exception { - web.ignoring() - .antMatchers("/resources/**"); - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/login") - .permitAll() - .and() - .formLogin() - .permitAll() - .successHandler(successHandler) - .and() - .csrf() - .disable(); - } - - @Bean - public DaoAuthenticationProvider authenticationProvider() { - final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); - authProvider.setUserDetailsService(userDetailsService); - authProvider.setPasswordEncoder(encoder()); - return authProvider; - } - - @Bean - public PasswordEncoder encoder() { - return new BCryptPasswordEncoder(11); - } - - @Bean - public SecurityEvaluationContextExtension securityEvaluationContextExtension() { - return new SecurityEvaluationContextExtension(); - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java deleted file mode 100644 index 9f13c3197e..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.data.repositories; - -import java.util.Date; -import java.util.List; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.models.AppUser; -import com.baeldung.models.Tweet; - -public interface UserRepository extends CrudRepository { - AppUser findByUsername(String username); - - List findByName(String name); - - @Query("UPDATE AppUser u SET u.lastLogin=:lastLogin WHERE u.username = ?#{ principal?.username }") - @Modifying - @Transactional - public void updateLastLogin(@Param("lastLogin") Date lastLogin); -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java deleted file mode 100644 index 2bd0da48d2..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.custom; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.PropertySource; - -@SpringBootApplication -@PropertySource("classpath:application-defaults.properties") -public class Application extends SpringBootServletInitializer { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java deleted file mode 100644 index 6a005153dc..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.custom.config; - -import org.baeldung.custom.security.CustomMethodSecurityExpressionHandler; -import org.baeldung.custom.security.CustomPermissionEvaluator; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; - -@Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true) -public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { - - @Override - protected MethodSecurityExpressionHandler createExpressionHandler() { - // final DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); - final CustomMethodSecurityExpressionHandler expressionHandler = new CustomMethodSecurityExpressionHandler(); - expressionHandler.setPermissionEvaluator(new CustomPermissionEvaluator()); - return expressionHandler; - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java deleted file mode 100644 index 58d11ea9ae..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.custom.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -@EnableWebMvc -public class MvcConfig implements WebMvcConfigurer { - - public MvcConfig() { - super(); - } - - // - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Override - public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - registry.addViewController("/").setViewName("forward:/index"); - registry.addViewController("/index"); - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java deleted file mode 100644 index 739e4d3417..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.custom.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -public class SecurityConfig { - - @Bean - public PasswordEncoder encoder() { - return new BCryptPasswordEncoder(11); - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java deleted file mode 100644 index 1319a7b9f8..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.custom.persistence.dao; - -import org.baeldung.custom.persistence.model.Organization; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface OrganizationRepository extends JpaRepository { - - public Organization findByName(String name); - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java deleted file mode 100644 index c232bb986c..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.custom.persistence.dao; - -import org.baeldung.custom.persistence.model.Privilege; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface PrivilegeRepository extends JpaRepository { - - public Privilege findByName(String name); - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java deleted file mode 100644 index 68dd1d756c..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.custom.persistence.dao; - -import org.baeldung.custom.persistence.model.User; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.transaction.annotation.Transactional; - -public interface UserRepository extends JpaRepository { - - User findByUsername(final String username); - - @Transactional - void removeUserByUsername(String username); - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java deleted file mode 100644 index f139382eea..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.baeldung.custom.persistence.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Foo { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Column(nullable = false) - private String name; - - // - - public Foo() { - super(); - } - - public Foo(String name) { - super(); - this.name = name; - } - - // - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - // - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Foo [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + ((id == null) ? 0 : id.hashCode()); - 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 Foo other = (Foo) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java deleted file mode 100644 index ed3edd5085..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.baeldung.custom.persistence.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Privilege { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Column(nullable = false, unique = true) - private String name; - - // - - public Privilege() { - super(); - } - - public Privilege(String name) { - super(); - this.name = name; - } - - // - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - // - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Privilege [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + ((id == null) ? 0 : id.hashCode()); - 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 Privilege other = (Privilege) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java deleted file mode 100644 index c14ef034b4..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java +++ /dev/null @@ -1,155 +0,0 @@ -package org.baeldung.custom.persistence.model; - -import java.util.Set; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "user_table") -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Column(nullable = false, unique = true) - private String username; - - private String password; - - @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "users_privileges", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")) - private Set privileges; - - @ManyToOne(fetch = FetchType.EAGER) - @JoinColumn(name = "organization_id", referencedColumnName = "id") - private Organization organization; - - // - - public User() { - super(); - } - - // - 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 String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public Set getPrivileges() { - return privileges; - } - - public void setPrivileges(Set privileges) { - this.privileges = privileges; - } - - public Organization getOrganization() { - return organization; - } - - public void setOrganization(Organization organization) { - this.organization = organization; - } - - // - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append(", privileges=").append(privileges).append(", organization=").append(organization).append("]"); - return builder.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + ((id == null) ? 0 : id.hashCode()); - result = (prime * result) + ((organization == null) ? 0 : organization.hashCode()); - result = (prime * result) + ((password == null) ? 0 : password.hashCode()); - result = (prime * result) + ((privileges == null) ? 0 : privileges.hashCode()); - result = (prime * result) + ((username == null) ? 0 : username.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 User other = (User) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (organization == null) { - if (other.organization != null) { - return false; - } - } else if (!organization.equals(other.organization)) { - return false; - } - if (password == null) { - if (other.password != null) { - return false; - } - } else if (!password.equals(other.password)) { - return false; - } - if (privileges == null) { - if (other.privileges != null) { - return false; - } - } else if (!privileges.equals(other.privileges)) { - return false; - } - if (username == null) { - if (other.username != null) { - return false; - } - } else if (!username.equals(other.username)) { - return false; - } - return true; - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java deleted file mode 100644 index b9b40fbcb9..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.baeldung.custom.security; - -import org.baeldung.custom.persistence.dao.UserRepository; -import org.baeldung.custom.persistence.model.User; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; - -@Service -public class MyUserDetailsService implements UserDetailsService { - - @Autowired - private UserRepository userRepository; - - public MyUserDetailsService() { - super(); - } - - // API - - @Override - public UserDetails loadUserByUsername(final String username) { - final User user = userRepository.findByUsername(username); - if (user == null) { - throw new UsernameNotFoundException(username); - } - return new MyUserPrincipal(user); - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java deleted file mode 100644 index 74de45d1a8..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.baeldung.custom.web; - -import org.baeldung.custom.persistence.dao.OrganizationRepository; -import org.baeldung.custom.persistence.model.Foo; -import org.baeldung.custom.persistence.model.Organization; -import org.baeldung.custom.security.MyUserPrincipal; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.security.core.annotation.AuthenticationPrincipal; -import org.springframework.stereotype.Controller; -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.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; - -@Controller -public class MainController { - - @Autowired - private OrganizationRepository organizationRepository; - - // @PostAuthorize("hasPermission(returnObject, 'read')") - @PreAuthorize("hasPermission(#id, 'Foo', 'read')") - @GetMapping("/foos/{id}") - @ResponseBody - public Foo findById(@PathVariable final long id) { - return new Foo("Sample"); - } - - @PreAuthorize("hasPermission(#foo, 'write')") - @PostMapping("/foos") - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Foo create(@RequestBody final Foo foo) { - return foo; - } - - // - - @PreAuthorize("hasAuthority('FOO_READ_PRIVILEGE')") - @GetMapping("/foos") - @ResponseBody - public Foo findFooByName(@RequestParam final String name) { - return new Foo(name); - } - - // - - @PreAuthorize("isMember(#id)") - @GetMapping("/organizations/{id}") - @ResponseBody - public Organization findOrgById(@PathVariable final long id) { - return organizationRepository.findById(id) - .orElse(null); - } - - @PreAuthorize("hasPermission(#id, 'Foo', 'read')") - @GetMapping("/user") - @ResponseBody - public MyUserPrincipal retrieveUserDetails(@AuthenticationPrincipal MyUserPrincipal principal) { - return principal; - } - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java deleted file mode 100644 index 3a8032a734..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.ip.config; - -import org.springframework.beans.factory.annotation.Autowired; -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//(debug = true) -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private CustomIpAuthenticationProvider authenticationProvider; - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("john").password("{noop}123").authorities("ROLE_USER"); - // auth.authenticationProvider(authenticationProvider); - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http.authorizeRequests() - .antMatchers("/login").permitAll() -// .antMatchers("/foos/**").hasIpAddress("11.11.11.11") - .antMatchers("/foos/**").access("isAuthenticated() and hasIpAddress('11.11.11.11')") - .anyRequest().authenticated() - .and().formLogin().permitAll() - .and().csrf().disable(); - // @formatter:on - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java deleted file mode 100644 index 1d22ca4c67..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.ip.config; - - -//@Configuration -//@EnableWebSecurity -//@ImportResource({ "classpath:spring-security-ip.xml" }) -public class SecurityXmlConfig { - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java deleted file mode 100644 index 940194c421..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.ip.web; - -import java.util.List; - -import javax.servlet.Filter; -import javax.servlet.http.HttpServletRequest; - -import org.baeldung.custom.persistence.model.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.security.web.FilterChainProxy; -import org.springframework.security.web.SecurityFilterChain; -import org.springframework.stereotype.Controller; -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; - -@Controller -public class MainController { - - @Autowired - @Qualifier("springSecurityFilterChain") - private Filter springSecurityFilterChain; - - @RequestMapping(method = RequestMethod.GET, value = "/filters") - @ResponseBody - public void getFilters() { - FilterChainProxy filterChainProxy = (FilterChainProxy) springSecurityFilterChain; - List list = filterChainProxy.getFilterChains(); - list.stream() - .flatMap(chain -> chain.getFilters().stream()) - .forEach(filter -> System.out.println(filter.getClass())); - } - - @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") - @ResponseBody - public Foo findById(@PathVariable final long id, HttpServletRequest request) { - return new Foo("Sample"); - } - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java deleted file mode 100644 index 8b8696f0b2..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.baeldung.jdbcauthentication.h2.config; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -public class SecurityConfiguration extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity httpSecurity) throws Exception { - httpSecurity.authorizeRequests() - .antMatchers("/h2-console/**") - .permitAll() - .anyRequest() - .authenticated() - .and() - .formLogin() - .permitAll(); - httpSecurity.csrf() - .ignoringAntMatchers("/h2-console/**"); - httpSecurity.headers() - .frameOptions() - .sameOrigin(); - } - - @Autowired - private DataSource dataSource; - - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.jdbcAuthentication() - .dataSource(dataSource) - .withDefaultSchema() - .withUser(User.withUsername("user") - .password(passwordEncoder().encode("pass")) - .roles("USER")); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java deleted file mode 100644 index 0955061614..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.jdbcauthentication.h2.web; - -import java.security.Principal; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/principal") -public class UserController { - - @GetMapping - public Principal retrievePrincipal(Principal principal) { - return principal; - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java deleted file mode 100644 index 157c0be748..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.jdbcauthentication.mysql.config; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -public class SecurityConfiguration { - - @Autowired - private DataSource dataSource; - - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.jdbcAuthentication() - .dataSource(dataSource) - .usersByUsernameQuery("select email,password,enabled " - + "from bael_users " - + "where email = ?") - .authoritiesByUsernameQuery("select email,authority " - + "from authorities " - + "where email = ?"); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java deleted file mode 100644 index f1060b5f78..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.jdbcauthentication.mysql.web; - -import java.security.Principal; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/principal") -public class UserController { - - @GetMapping - public Principal retrievePrincipal(Principal principal) { - return principal; - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java deleted file mode 100644 index ba79635852..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.jdbcauthentication.postgre.config; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -public class SecurityConfiguration { - - @Autowired - private DataSource dataSource; - - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.jdbcAuthentication() - .dataSource(dataSource); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java deleted file mode 100644 index c8fd3812b1..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.jdbcauthentication.postgre.web; - -import java.security.Principal; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/principal") -public class UserController { - - @GetMapping - public Principal retrievePrincipal(Principal principal) { - return principal; - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java deleted file mode 100644 index 1a89c362cd..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.baeldung.multipleauthproviders; - -import java.util.Collections; - -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.stereotype.Component; - -@Component -public class CustomAuthenticationProvider implements AuthenticationProvider { - @Override - public Authentication authenticate(Authentication auth) throws AuthenticationException { - final String username = auth.getName(); - final String password = auth.getCredentials() - .toString(); - - if ("externaluser".equals(username) && "pass".equals(password)) { - return new UsernamePasswordAuthenticationToken(username, password, Collections.emptyList()); - } else { - throw new BadCredentialsException("External system authentication failed"); - } - } - - @Override - public boolean supports(Class auth) { - return auth.equals(UsernamePasswordAuthenticationToken.class); - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java deleted file mode 100644 index d7195ac358..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.baeldung.rolesauthorities; - -import org.baeldung.rolesauthorities.model.User; -import org.baeldung.rolesauthorities.persistence.UserRepository; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.userdetails.UserDetailsService; - -public class CustomAuthenticationProvider extends DaoAuthenticationProvider { - - private final UserRepository userRepository; - @SuppressWarnings("unused") - private UserDetailsService userDetailsService; - - public CustomAuthenticationProvider(UserRepository userRepository, UserDetailsService userDetailsService){ - super(); - this.setUserDetailsService(userDetailsService); - this.userRepository = userRepository; - } - - @Override - public Authentication authenticate(Authentication auth) throws AuthenticationException { - final User user = userRepository.findByEmail(auth.getName()); - if ((user == null)) { - throw new BadCredentialsException("Invalid username or password"); - } - final Authentication result = super.authenticate(auth); - return new UsernamePasswordAuthenticationToken(user, result.getCredentials(), result.getAuthorities()); - } - - @Override - public boolean supports(Class authentication) { - return authentication.equals(UsernamePasswordAuthenticationToken.class); - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java deleted file mode 100644 index f38b867a75..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.baeldung.rolesauthorities; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - -import org.baeldung.rolesauthorities.model.Role; -import org.baeldung.rolesauthorities.model.User; -import org.baeldung.rolesauthorities.persistence.UserRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("userDetailsService") -@Transactional -public class MyUserDetailsService implements UserDetailsService { - - @Autowired - private UserRepository userRepository; - - public MyUserDetailsService() { - super(); - } - - // API - - @Override - public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { - - try { - User user = userRepository.findByEmail(email); - if (user == null) { - throw new UsernameNotFoundException("No user found with username: " + email); - } - org.springframework.security.core.userdetails.User userDetails = new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, getAuthorities(user.getRoles())); - return userDetails; - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - // UTIL - - private final Collection getAuthorities(Collection roles) { - List authorities = new ArrayList(); - for (Role role: roles) { - authorities.add(new SimpleGrantedAuthority(role.getName())); - authorities.addAll(role.getPrivileges() - .stream() - .map(p -> new SimpleGrantedAuthority(p.getName())) - .collect(Collectors.toList())); - } - return authorities; - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java deleted file mode 100644 index c42958457e..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.baeldung.rolesauthorities.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -@EnableWebMvc -public class MvcConfig implements WebMvcConfigurer { - - public MvcConfig() { - super(); - } - - // - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Override - public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - registry.addViewController("/").setViewName("forward:/home"); - registry.addViewController("/protectedbynothing").setViewName("rolesauthorities/protectedbynothing"); - registry.addViewController("/protectedbyrole").setViewName("rolesauthorities/protectedbyrole"); - registry.addViewController("/protectedbyauthority").setViewName("rolesauthorities/protectedbyauthority"); - registry.addViewController("/login").setViewName("rolesauthorities/login"); - registry.addViewController("/home").setViewName("rolesauthorities/home"); - registry.addViewController("/logout"); - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java deleted file mode 100644 index 7624dd7d39..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.baeldung.rolesauthorities.config; - -import org.baeldung.rolesauthorities.CustomAuthenticationProvider; -import org.baeldung.rolesauthorities.persistence.UserRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; - -@Configuration -@ComponentScan(basePackages = { "org.baeldung.rolesauthorities" }) -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private UserRepository userRepository; - - @Autowired - private UserDetailsService userDetailsService; - - @Autowired - private LogoutSuccessHandler myLogoutSuccessHandler; - - public SecurityConfig() { - super(); - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(authProvider()); - } - - @Override - public void configure(WebSecurity web) throws Exception { - web.ignoring() - .antMatchers("/resources/**"); - } - - - @Override - protected void configure(HttpSecurity http) throws Exception { - - // @formatter:off - http - .csrf().disable() - .authorizeRequests() - .antMatchers("/login*", "/logout*", "/protectedbynothing*", "/home*").permitAll() - .antMatchers("/protectedbyrole").hasRole("USER") - .antMatchers("/protectedbyauthority").hasAuthority("READ_PRIVILEGE") - .and() - .formLogin() - .loginPage("/login") - .failureUrl("/login?error=true") - .permitAll() - .and() - .logout() - .logoutSuccessHandler(myLogoutSuccessHandler) - .invalidateHttpSession(false) - .logoutSuccessUrl("/logout.html?logSucc=true") - .deleteCookies("JSESSIONID") - .permitAll(); - // @formatter:on - } - - // beans - - @Bean - public DaoAuthenticationProvider authProvider() { - final CustomAuthenticationProvider authProvider - = new CustomAuthenticationProvider(userRepository, userDetailsService); - authProvider.setPasswordEncoder(encoder()); - return authProvider; - } - - @Bean - public PasswordEncoder encoder() { - return new BCryptPasswordEncoder(11); - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java deleted file mode 100644 index ab2cd08610..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.baeldung.rolesauthorities.model; - -import java.util.Collection; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToMany; - -@Entity -public class Privilege { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String name; - - @ManyToMany(mappedBy = "privileges") - private Collection roles; - - public Privilege() { - super(); - } - - public Privilege(String name) { - super(); - this.name = name; - } - - // - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Collection getRoles() { - return roles; - } - - public void setRoles(Collection roles) { - this.roles = roles; - } - - @Override - public int hashCode() { - int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Privilege other = (Privilege) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Privilege [name=").append(name).append("]").append("[id=").append(id).append("]"); - return builder.toString(); - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java deleted file mode 100644 index ac33e32fcf..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.baeldung.rolesauthorities.model; - -import java.util.Collection; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; - -@Entity -public class Role { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @ManyToMany(mappedBy = "roles") - private Collection users; - - @ManyToMany - @JoinTable(name = "roles_privileges", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")) - private Collection privileges; - - private String name; - - public Role() { - super(); - } - - public Role(String name) { - super(); - this.name = name; - } - - // - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Collection getUsers() { - return users; - } - - public void setUsers(Collection users) { - this.users = users; - } - - public Collection getPrivileges() { - return privileges; - } - - public void setPrivileges(Collection privileges) { - this.privileges = privileges; - } - - @Override - public int hashCode() { - int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Role role = (Role) obj; - if (!role.equals(role.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]"); - return builder.toString(); - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java deleted file mode 100644 index dc1096541d..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java +++ /dev/null @@ -1,147 +0,0 @@ -package org.baeldung.rolesauthorities.model; - -import java.util.Collection; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.Table; - - -@Entity -@Table(name = "user_account") -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String firstName; - - private String lastName; - - private String email; - - @Column(length = 60) - private String password; - - private boolean enabled; - - private boolean isUsing2FA; - - // - - @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) - private Collection roles; - - public User() { - super(); - this.enabled = false; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getEmail() { - return email; - } - - public void setEmail(String username) { - this.email = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public Collection getRoles() { - return roles; - } - - public void setRoles(Collection roles) { - this.roles = roles; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public boolean isUsing2FA() { - return isUsing2FA; - } - - public void setUsing2FA(boolean isUsing2FA) { - this.isUsing2FA = isUsing2FA; - } - - @Override - public int hashCode() { - int prime = 31; - int result = 1; - result = (prime * result) + ((email == null) ? 0 : email.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - User user = (User) obj; - if (!email.equals(user.email)) { - return false; - } - return true; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("User [id=").append(id).append(", firstName=") - .append(firstName).append(", lastName=").append(lastName).append(", email=").append(email).append(", password=").append(password).append(", enabled=").append(enabled).append(", roles=").append(roles).append("]"); - return builder.toString(); - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java deleted file mode 100644 index 2c508cbd20..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.rolesauthorities.persistence; - -import org.baeldung.rolesauthorities.model.User; - -public interface IUserService { - - User findUserByEmail(String email); - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java deleted file mode 100644 index 05d5f2b870..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.rolesauthorities.persistence; - -import org.baeldung.rolesauthorities.model.Privilege; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface PrivilegeRepository extends JpaRepository { - - Privilege findByName(String name); - - void delete(Privilege privilege); - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java deleted file mode 100644 index 25e3b3a1f6..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.rolesauthorities.persistence; - -import org.baeldung.rolesauthorities.model.Role; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface RoleRepository extends JpaRepository { - - Role findByName(String name); - - void delete(Role role); - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java deleted file mode 100644 index bca2953153..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.rolesauthorities.persistence; - -import org.baeldung.rolesauthorities.model.User; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface UserRepository extends JpaRepository { - - User findByEmail(String email); - - void delete(User user); - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java deleted file mode 100644 index 3b16c78898..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung.rolesauthorities.persistence; - -import javax.transaction.Transactional; - -import org.baeldung.rolesauthorities.model.User; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -@Transactional -public class UserService implements IUserService { - - @Autowired - private UserRepository repository; - - public User findUserByEmail(String email) { - return repository.findByEmail(email); - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java deleted file mode 100644 index 92f92d8fc7..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.ssl; - -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; - -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/**") - .permitAll(); - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java deleted file mode 100644 index 72ad8abb85..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.ssl; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -@Controller -public class WelcomeController { - - @GetMapping("/welcome") - public String welcome() { - return "ssl/welcome"; - } - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java deleted file mode 100644 index 8f41153f06..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung.voter; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -/** - * Created by ambrusadrianz on 30/09/2016. - */ - -@Configuration -public class VoterMvcConfig implements WebMvcConfigurer { - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/").setViewName("private"); - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java deleted file mode 100644 index 84ed070e8e..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.baeldung.voter; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.access.AccessDecisionManager; -import org.springframework.security.access.AccessDecisionVoter; -import org.springframework.security.access.vote.AuthenticatedVoter; -import org.springframework.security.access.vote.RoleVoter; -import org.springframework.security.access.vote.UnanimousBased; -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.access.expression.WebExpressionVoter; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; - -import java.util.Arrays; -import java.util.List; - -@Configuration -@EnableWebSecurity -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - // @formatter: off - auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("pass")).roles("USER").and().withUser("admin").password(passwordEncoder().encode("pass")).roles("ADMIN"); - // @formatter: on - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter: off - http - // needed so our login could work - .csrf().disable().authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager()).antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER").and().formLogin().permitAll().and().logout().permitAll() - .deleteCookies("JSESSIONID").logoutSuccessUrl("/login"); - // @formatter: on - } - - @Bean - public AccessDecisionManager accessDecisionManager() { - // @formatter: off - List> decisionVoters = Arrays.asList(new WebExpressionVoter(), new RoleVoter(), new AuthenticatedVoter(), new MinuteBasedVoter()); - // @formatter: on - return new UnanimousBased(decisionVoters); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/XmlSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/XmlSecurityConfig.java deleted file mode 100644 index 8041585f42..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/main/java/org/baeldung/voter/XmlSecurityConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.voter; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; - -/** - * Created by ambrusadrianz on 09/10/2016. - */ -// @Configuration -// @ImportResource({ "classpath:spring-security-custom-voter.xml" }) -public class XmlSecurityConfig { - public XmlSecurityConfig() { - super(); - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java deleted file mode 100644 index bd0c14ca1f..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.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 SpringDataWithSecurityIntegrationTest { - 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-modules/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 2041249b71..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.custom.Application; -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(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextTest.java b/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextTest.java deleted file mode 100644 index 7aa26ff031..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.jdbcauthentication.h2; - -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(classes = H2JdbcAuthenticationApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java deleted file mode 100644 index 638e9d7919..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.jdbcauthentication.h2.web; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.CoreMatchers.is; - -import org.junit.jupiter.api.Test; -import org.springframework.http.HttpStatus; - -import io.restassured.authentication.FormAuthConfig; -import io.restassured.filter.session.SessionFilter; - -/** - * This Live Test requires the H2JdbcAuthenticationApplication application to be up and running - */ -public class UserControllerLiveTest { - - private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; - - @Test - public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { - SessionFilter filter = new SessionFilter(); - given().auth() - .form("user", "pass", new FormAuthConfig("/login", "username", "password").withCsrfFieldName("_csrf")) - .and() - .filter(filter) - .when() - .get(PRINCIPAL_SVC_URL) - .then() - .statusCode(HttpStatus.OK.value()) - .and() - .body("authorities[0].authority", is("ROLE_USER")) - .body("principal.username", is("user")) - .body("name", is("user")); - } -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java deleted file mode 100644 index 261063cbb6..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.jdbcauthentication.mysql.web; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.CoreMatchers.is; - -import org.junit.jupiter.api.Test; -import org.springframework.http.HttpStatus; - -/** - * This Live Test requires: - * * a MySql instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication - * (e.g. with the following command `docker run -p 3306:3306 --name bael-mysql -e MYSQL_ROOT_PASSWORD=pass -e MYSQL_DATABASE=jdbc_authentication mysql:latest`) - * * the service up and running - * - */ -public class UserControllerLiveTest { - - private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; - - @Test - public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { - given().auth() - .preemptive() - .basic("user@email.com", "pass") - .when() - .get(PRINCIPAL_SVC_URL) - .then() - .statusCode(HttpStatus.OK.value()) - .and() - .body("authorities[0].authority", is("ROLE_USER")) - .body("principal.username", is("user@email.com")) - .body("name", is("user@email.com")); - } - -} diff --git a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java deleted file mode 100644 index 82bf6df8db..0000000000 --- a/spring-security-modules/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.jdbcauthentication.postgre.web; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.CoreMatchers.is; - -import org.junit.jupiter.api.Test; -import org.springframework.http.HttpStatus; - -/** - * This Live Test requires: - * * a PostgreSQL instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication - * (e.g. with the following command `docker run -p 5432:5432 --name bael-postgre -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=jdbc_authentication postgres:latest`) - * * the service up and running - * - */ -public class UserControllerLiveTest { - - private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; - - @Test - public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { - given().auth() - .preemptive() - .basic("user", "pass") - .when() - .get(PRINCIPAL_SVC_URL) - .then() - .statusCode(HttpStatus.OK.value()) - .and() - .body("authorities[0].authority", is("ROLE_USER")) - .body("principal.username", is("user")) - .body("name", is("user")); - } - -} diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java new file mode 100644 index 0000000000..728445952e --- /dev/null +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -0,0 +1,83 @@ +package com.baeldung.security; + +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.web.DefaultRedirectStrategy; +import org.springframework.security.web.RedirectStrategy; +import org.springframework.security.web.WebAttributes; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { + protected final Log logger = LogFactory.getLog(this.getClass()); + + private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); + + public MySimpleUrlAuthenticationSuccessHandler() { + super(); + } + + // API + + @Override + public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { + handle(request, response, authentication); + clearAuthenticationAttributes(request); + } + + // IMPL + + protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { + final String targetUrl = determineTargetUrl(authentication); + + if (response.isCommitted()) { + logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); + return; + } + + redirectStrategy.sendRedirect(request, response, targetUrl); + } + + protected String determineTargetUrl(final Authentication authentication) { + + Map roleTargetUrlMap = new HashMap<>(); + roleTargetUrlMap.put("ROLE_USER", "/homepage.html"); + roleTargetUrlMap.put("ROLE_ADMIN", "/console.html"); + + final Collection authorities = authentication.getAuthorities(); + for (final GrantedAuthority grantedAuthority : authorities) { + + String authorityName = grantedAuthority.getAuthority(); + if(roleTargetUrlMap.containsKey(authorityName)) { + return roleTargetUrlMap.get(authorityName); + } + } + + throw new IllegalStateException(); + } + + /** + * Removes temporary authentication-related data which may have been stored in the session + * during the authentication process. + */ + protected final void clearAuthenticationAttributes(final HttpServletRequest request) { + final HttpSession session = request.getSession(false); + + if (session == null) { + return; + } + + session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); + } + +} diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MvcConfig.java new file mode 100644 index 0000000000..583825a66a --- /dev/null +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MvcConfig.java @@ -0,0 +1,55 @@ +package com.baeldung.spring; + +import com.baeldung.web.interceptor.LoggerInterceptor; +import com.baeldung.web.interceptor.SessionTimerInterceptor; +import com.baeldung.web.interceptor.UserInterceptor; +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.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +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("com.baeldung.web.controller") +public class MvcConfig implements WebMvcConfigurer { + + public MvcConfig() { + super(); + } + + // API + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/anonymous.html"); + + registry.addViewController("/login.html"); + registry.addViewController("/homepage.html"); + registry.addViewController("/console.html"); + registry.addViewController("/csrfHome.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 addInterceptors(final InterceptorRegistry registry) { + registry.addInterceptor(new LoggerInterceptor()); + registry.addInterceptor(new UserInterceptor()); + registry.addInterceptor(new SessionTimerInterceptor()); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MyUserDetailsService.java new file mode 100644 index 0000000000..ee80ad12d7 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MyUserDetailsService.java @@ -0,0 +1,32 @@ +package com.baeldung.spring; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.util.*; + +@Service +public class MyUserDetailsService implements UserDetailsService { + + private Map roles = new HashMap<>(); + + @PostConstruct + public void init() { + roles.put("admin", new User("admin", "{noop}admin1", getAuthority("ROLE_ADMIN"))); + roles.put("user", new User("user", "{noop}user1", getAuthority("ROLE_USER"))); + } + + @Override + public UserDetails loadUserByUsername(String username) { + return roles.get(username); + } + + private List getAuthority(String role) { + return Collections.singletonList(new SimpleGrantedAuthority(role)); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/SecSecurityConfig.java new file mode 100644 index 0000000000..9cee909ad4 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -0,0 +1,60 @@ +package com.baeldung.spring; + +import com.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.security.authentication.AuthenticationManager; +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" }) +@EnableWebSecurity +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { + + public SecSecurityConfig() { + super(); + } + + @Bean("authenticationManager") + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @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-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/BankController.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/BankController.java similarity index 96% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/BankController.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/BankController.java index 1a4322c611..c4bbde21f2 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/BankController.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/BankController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/FooController.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/FooController.java new file mode 100644 index 0000000000..6f9268c976 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/FooController.java @@ -0,0 +1,59 @@ +package com.baeldung.web.controller; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +import java.util.Arrays; +import java.util.List; + +import javax.servlet.http.HttpServletResponse; + +import com.baeldung.web.dto.Foo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +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.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.util.UriComponentsBuilder; + +@Controller +@RequestMapping(value = "/auth/foos") +public class FooController { + + @Autowired + private ApplicationEventPublisher eventPublisher; + + public FooController() { + super(); + } + + // API + + // read - single + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public Foo findById(@PathVariable("id") final Long id, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { + return new Foo(randomAlphabetic(6)); + } + + // read - multiple + + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public List findAll() { + return Arrays.asList(new Foo(randomAlphabetic(6))); + } + + // write - just for test + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo create(@RequestBody final Foo foo) { + return foo; + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/LoginController.java similarity index 97% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/LoginController.java index 99bf345a41..8a823cdf7e 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/LoginController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/PrintUserController.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/PrintUserController.java similarity index 95% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/PrintUserController.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/PrintUserController.java index 78f164c7f1..9623471f12 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/PrintUserController.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/PrintUserController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/dto/Foo.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/dto/Foo.java new file mode 100644 index 0000000000..b349e75b72 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/dto/Foo.java @@ -0,0 +1,80 @@ +package com.baeldung.web.dto; + +import java.io.Serializable; + +public class Foo implements Serializable { + + private long id; + + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + 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; + } + + // + + @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(); + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/LoggerInterceptor.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/LoggerInterceptor.java index 7c68d3e9c7..b54fda5a82 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/LoggerInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import com.google.common.base.Strings; import org.slf4j.Logger; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/SessionTimerInterceptor.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/SessionTimerInterceptor.java index 90199347b4..38e852305c 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/SessionTimerInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/UserInterceptor.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/UserInterceptor.java index 6b808d885e..cd64a20842 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/UserInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java deleted file mode 100644 index 19f49ea59d..0000000000 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.baeldung.security; - -import java.io.IOException; -import java.util.Collection; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.web.DefaultRedirectStrategy; -import org.springframework.security.web.RedirectStrategy; -import org.springframework.security.web.WebAttributes; -import org.springframework.security.web.authentication.AuthenticationSuccessHandler; - -public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { - protected final Log logger = LogFactory.getLog(this.getClass()); - - private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - - public MySimpleUrlAuthenticationSuccessHandler() { - super(); - } - - // API - - @Override - public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { - handle(request, response, authentication); - clearAuthenticationAttributes(request); - } - - // IMPL - - protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { - final String targetUrl = determineTargetUrl(authentication); - - if (response.isCommitted()) { - logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); - return; - } - - redirectStrategy.sendRedirect(request, response, targetUrl); - } - - protected String determineTargetUrl(final Authentication authentication) { - boolean isUser = false; - boolean isAdmin = false; - final Collection authorities = authentication.getAuthorities(); - for (final GrantedAuthority grantedAuthority : authorities) { - if (grantedAuthority.getAuthority().equals("ROLE_USER")) { - isUser = true; - break; - } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) { - isAdmin = true; - break; - } - } - - if (isUser) { - return "/homepage.html"; - } else if (isAdmin) { - return "/console.html"; - } else { - throw new IllegalStateException(); - } - } - - /** - * Removes temporary authentication-related data which may have been stored in the session - * during the authentication process. - */ - protected final void clearAuthenticationAttributes(final HttpServletRequest request) { - final HttpSession session = request.getSession(false); - - if (session == null) { - return; - } - - session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); - } - - public void setRedirectStrategy(final RedirectStrategy redirectStrategy) { - this.redirectStrategy = redirectStrategy; - } - - protected RedirectStrategy getRedirectStrategy() { - return redirectStrategy; - } - -} diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java deleted file mode 100644 index db6141d43e..0000000000 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.baeldung.spring; - -import org.baeldung.web.interceptor.LoggerInterceptor; -import org.baeldung.web.interceptor.SessionTimerInterceptor; -import org.baeldung.web.interceptor.UserInterceptor; -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.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -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 implements WebMvcConfigurer { - - public MvcConfig() { - super(); - } - - // API - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - registry.addViewController("/anonymous.html"); - - registry.addViewController("/login.html"); - registry.addViewController("/homepage.html"); - registry.addViewController("/console.html"); - registry.addViewController("/csrfHome.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 addInterceptors(final InterceptorRegistry registry) { - registry.addInterceptor(new LoggerInterceptor()); - registry.addInterceptor(new UserInterceptor()); - registry.addInterceptor(new SessionTimerInterceptor()); - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java deleted file mode 100644 index ebe23950a7..0000000000 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ /dev/null @@ -1,70 +0,0 @@ -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.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" }) -@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-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/FooController.java deleted file mode 100644 index 5a3c85d220..0000000000 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/FooController.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.baeldung.web.controller; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; - -import java.util.Arrays; -import java.util.List; - -import javax.servlet.http.HttpServletResponse; - -import org.baeldung.web.dto.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -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.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.util.UriComponentsBuilder; - -@Controller -@RequestMapping(value = "/auth/foos") -public class FooController { - - @Autowired - private ApplicationEventPublisher eventPublisher; - - public FooController() { - super(); - } - - // API - - // read - single - - @RequestMapping(value = "/{id}", method = RequestMethod.GET) - @ResponseBody - public Foo findById(@PathVariable("id") final Long id, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { - return new Foo(randomAlphabetic(6)); - } - - // read - multiple - - @RequestMapping(method = RequestMethod.GET) - @ResponseBody - public List findAll() { - return Arrays.asList(new Foo(randomAlphabetic(6))); - } - - // write - just for test - @RequestMapping(method = RequestMethod.POST) - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Foo create(@RequestBody final Foo foo) { - return foo; - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/dto/Foo.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/dto/Foo.java deleted file mode 100644 index 02283e7df9..0000000000 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/dto/Foo.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.baeldung.web.dto; - -import java.io.Serializable; - -public class Foo implements Serializable { - - private long id; - - private String name; - - public Foo() { - super(); - } - - public Foo(final String name) { - super(); - - 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; - } - - // - - @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(); - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml index e79e14abeb..eb2dc719f5 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml @@ -22,7 +22,7 @@
- + @@ -33,8 +33,7 @@ - - \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/webapp/WEB-INF/web.xml b/spring-security-modules/spring-security-mvc-custom/src/main/webapp/WEB-INF/web.xml index e805828809..61fd248f53 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-modules/spring-security-mvc-custom/src/main/webapp/WEB-INF/web.xml @@ -20,7 +20,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3a73503bca --- /dev/null +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import com.baeldung.spring.MvcConfig; +import com.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfAbstractIntegrationTest.java similarity index 95% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index 44424bf7f9..97972b7358 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -1,11 +1,11 @@ -package org.baeldung.security.csrf; +package com.baeldung.security.csrf; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import javax.servlet.Filter; -import org.baeldung.web.dto.Foo; +import com.baeldung.web.dto.Foo; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfDisabledIntegrationTest.java similarity index 87% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfDisabledIntegrationTest.java index 1d16e08514..a1c8be9daf 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfDisabledIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.security.csrf; +package com.baeldung.security.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.security.spring.SecurityWithoutCsrfConfig; -import org.baeldung.spring.MvcConfig; +import com.baeldung.security.spring.SecurityWithoutCsrfConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfEnabledIntegrationTest.java similarity index 88% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index 9d882973bd..87e5005e17 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -1,11 +1,11 @@ -package org.baeldung.security.csrf; +package com.baeldung.security.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.security.spring.SecurityWithCsrfConfig; -import org.baeldung.spring.MvcConfig; +import com.baeldung.security.spring.SecurityWithCsrfConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityConfig.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityConfig.java index 23d13a0ff1..438cec38bb 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.security.spring; +package com.baeldung.security.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityIntegrationTest.java index afc86bd74c..002ba8df3e 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityIntegrationTest.java @@ -1,11 +1,11 @@ -package org.baeldung.security.spring; +package com.baeldung.security.spring; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import javax.servlet.http.HttpSession; -import org.baeldung.spring.MvcConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java index ca401622c0..9b3ac50546 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.security.spring; +package com.baeldung.security.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java index 1067c70fea..4a1263b498 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.security.spring; +package com.baeldung.security.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java similarity index 91% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java index c33c9a04e8..9e850861bf 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.security.spring.SecurityWithoutCsrfConfig; -import org.baeldung.spring.MvcConfig; +import com.baeldung.security.spring.SecurityWithoutCsrfConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java similarity index 93% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java index bdc1be2c44..07bc22f184 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java @@ -1,12 +1,12 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import javax.servlet.http.HttpSession; -import org.baeldung.security.spring.SecurityWithoutCsrfConfig; -import org.baeldung.spring.MvcConfig; +import com.baeldung.security.spring.SecurityWithoutCsrfConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/UserInterceptorIntegrationTest.java similarity index 92% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/UserInterceptorIntegrationTest.java index a85fd999a6..b7547cb23a 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/UserInterceptorIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.security.spring.SecurityWithoutCsrfConfig; -import org.baeldung.spring.MvcConfig; +import com.baeldung.security.spring.SecurityWithoutCsrfConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 5ee80d856a..0000000000 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.MvcConfig; -import org.baeldung.spring.SecSecurityConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) -@WebAppConfiguration -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java new file mode 100644 index 0000000000..1b9ffc3db8 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -0,0 +1,31 @@ +package com.baeldung.basic; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +@Component +public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { + + @Override + public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException { + response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + final PrintWriter writer = response.getWriter(); + writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage()); + } + + @Override + public void afterPropertiesSet() throws Exception { + setRealmName("Baeldung"); + super.afterPropertiesSet(); + } + +} diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java similarity index 98% rename from spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java rename to spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java index 1e6f213305..67c2d6031f 100644 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java @@ -1,4 +1,4 @@ -package org.baeldung.client; +package com.baeldung.client; import org.apache.http.HttpHost; import org.apache.http.client.AuthCache; diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/ClientConfig.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/ClientConfig.java new file mode 100644 index 0000000000..b7145daaea --- /dev/null +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/ClientConfig.java @@ -0,0 +1,44 @@ +package com.baeldung.spring; + +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import com.baeldung.client.HttpComponentsClientHttpRequestFactoryDigestAuth; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class ClientConfig { + private static final String DEFAULT_USER = "user1"; + private static final String DEFAULT_PASS = "user1Pass"; + + public ClientConfig() { + super(); + } + + @Bean + public RestTemplate restTemplate() { + HttpHost host = new HttpHost("localhost", 8080, "http"); + CloseableHttpClient client = HttpClientBuilder.create(). + setDefaultCredentialsProvider(provider()).useSystemProperties().build(); + HttpComponentsClientHttpRequestFactory requestFactory = + new HttpComponentsClientHttpRequestFactoryDigestAuth(host, client); + + return new RestTemplate(requestFactory); + } + + private CredentialsProvider provider() { + CredentialsProvider provider = new BasicCredentialsProvider(); + UsernamePasswordCredentials credentials = + new UsernamePasswordCredentials("user1", "user1Pass"); + provider.setCredentials(AuthScope.ANY, credentials); + return provider; + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/MvcConfig.java new file mode 100644 index 0000000000..0d9962cda0 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/MvcConfig.java @@ -0,0 +1,39 @@ +package com.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.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // API + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + + registry.addViewController("/homepage.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-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/SecSecurityConfig.java new file mode 100644 index 0000000000..4ba9d47f8d --- /dev/null +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +@Configuration +@ImportResource({ "classpath:webSecurityConfig.xml" }) +@ComponentScan("com.baeldung.security") +public class SecSecurityConfig { + + public SecSecurityConfig() { + super(); + } + +} diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java deleted file mode 100644 index c51c0a0bc8..0000000000 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.baeldung.basic; - -import java.io.IOException; -import java.io.PrintWriter; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; -import org.springframework.stereotype.Component; - -@Component -public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { - - @Override - public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException { - response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - final PrintWriter writer = response.getWriter(); - writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage()); - } - - @Override - public void afterPropertiesSet() throws Exception { - setRealmName("Baeldung"); - super.afterPropertiesSet(); - } - -} diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/ClientConfig.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/ClientConfig.java deleted file mode 100644 index f305321f13..0000000000 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/ClientConfig.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.baeldung.spring; - -import org.apache.http.HttpHost; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.baeldung.client.HttpComponentsClientHttpRequestFactoryDigestAuth; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.web.client.RestTemplate; - -@Configuration -public class ClientConfig { - private static final String DEFAULT_USER = "user1"; - private static final String DEFAULT_PASS = "user1Pass"; - - public ClientConfig() { - super(); - } - - @Bean - public RestTemplate restTemplate() { - HttpHost host = new HttpHost("localhost", 8080, "http"); - CloseableHttpClient client = HttpClientBuilder.create(). - setDefaultCredentialsProvider(provider()).useSystemProperties().build(); - HttpComponentsClientHttpRequestFactory requestFactory = - new HttpComponentsClientHttpRequestFactoryDigestAuth(host, client); - - return new RestTemplate(requestFactory); - } - - private CredentialsProvider provider() { - CredentialsProvider provider = new BasicCredentialsProvider(); - UsernamePasswordCredentials credentials = - new UsernamePasswordCredentials("user1", "user1Pass"); - provider.setCredentials(AuthScope.ANY, credentials); - return provider; - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/MvcConfig.java deleted file mode 100644 index 74c11478ee..0000000000 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/MvcConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -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.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@Configuration -@EnableWebMvc -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - // API - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - - registry.addViewController("/homepage.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-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java deleted file mode 100644 index 4ce80dab9f..0000000000 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; - -@Configuration -@ImportResource({ "classpath:webSecurityConfig.xml" }) -@ComponentScan("org.baeldung.security") -public class SecSecurityConfig { - - public SecSecurityConfig() { - super(); - } - -} diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/webapp/WEB-INF/web.xml b/spring-security-modules/spring-security-mvc-digest-auth/src/main/webapp/WEB-INF/web.xml index bebd5d9cd3..25f5a91932 100644 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/webapp/WEB-INF/web.xml @@ -16,7 +16,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..080935c8c1 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package com.baeldung; + +import com.baeldung.spring.ClientConfig; +import com.baeldung.spring.MvcConfig; +import com.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { ClientConfig.class, MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java b/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/client/RawClientLiveTest.java similarity index 94% rename from spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java rename to spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/client/RawClientLiveTest.java index e8dcf82ebc..de6dca3ec4 100644 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/client/RawClientLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.client; +package com.baeldung.client; import java.io.IOException; @@ -6,7 +6,7 @@ import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.baeldung.spring.ClientConfig; +import com.baeldung.spring.ClientConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index cd2b796308..0000000000 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.ClientConfig; -import org.baeldung.spring.MvcConfig; -import org.baeldung.spring.SecSecurityConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ClientConfig.class, MvcConfig.class, SecSecurityConfig.class }) -@WebAppConfiguration -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-mvc-ldap/pom.xml b/spring-security-modules/spring-security-mvc-ldap/pom.xml deleted file mode 100644 index 2f227d7908..0000000000 --- a/spring-security-modules/spring-security-mvc-ldap/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - 4.0.0 - spring-security-mvc-ldap - 0.1-SNAPSHOT - spring-security-mvc-ldap - war - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-actuator - - - - - org.springframework.security - spring-security-ldap - - - - - org.apache.directory.server - apacheds-server-jndi - ${apacheds.version} - - - - - - spring-security-mvc-ldap - - - src/main/resources - true - - - - - - 1.5.5 - - - diff --git a/spring-security-modules/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java b/spring-security-modules/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java deleted file mode 100644 index 5936aa30ef..0000000000 --- a/spring-security-modules/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; -import org.springframework.context.annotation.Bean; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -/** - * Main Application Class - uses Spring Boot. Just run this as a normal Java - * class to run up a Jetty Server (on http://localhost:8080) - * - */ -@SpringBootApplication -public class SampleLDAPApplication extends SpringBootServletInitializer { - - public static void main(String[] args) { - SpringApplication.run(SampleLDAPApplication.class, args); - } - - @Bean - public WebMvcConfigurerAdapter adapter() { - return new WebMvcConfigurerAdapter() { - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/login") - .setViewName("login"); - } - }; - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-ldap/src/main/java/org/baeldung/controller/MyController.java b/spring-security-modules/spring-security-mvc-ldap/src/main/java/org/baeldung/controller/MyController.java deleted file mode 100644 index e347bd8633..0000000000 --- a/spring-security-modules/spring-security-mvc-ldap/src/main/java/org/baeldung/controller/MyController.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.baeldung.controller; - -import java.security.Principal; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * Spring Controller Definitions. - */ -@Controller -public class MyController { - - @RequestMapping("/") - public String init(Map model, Principal principal) { - model.put("title", "PUBLIC AREA"); - model.put("message", "Any user can view this page"); - model.put("username", getUserName(principal)); - model.put("userroles", getUserRoles(principal)); - return "home"; - } - - @RequestMapping("/secure") - public String secure(Map model, Principal principal) { - model.put("title", "SECURE AREA"); - model.put("message", "Only Authorised Users Can See This Page"); - model.put("username", getUserName(principal)); - model.put("userroles", getUserRoles(principal)); - return "home"; - } - - private String getUserName(Principal principal) { - if (principal == null) { - return "anonymous"; - } else { - - final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal(); - Collection authorities = currentUser.getAuthorities(); - for (GrantedAuthority grantedAuthority : authorities) { - System.out.println(grantedAuthority.getAuthority()); - } - return principal.getName(); - } - } - - private Collection getUserRoles(Principal principal) { - if (principal == null) { - return Arrays.asList("none"); - } else { - - Set roles = new HashSet(); - - final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal(); - Collection authorities = currentUser.getAuthorities(); - for (GrantedAuthority grantedAuthority : authorities) { - roles.add(grantedAuthority.getAuthority()); - } - return roles; - } - } - -} diff --git a/spring-security-modules/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java b/spring-security-modules/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java deleted file mode 100644 index 0d444e36ff..0000000000 --- a/spring-security-modules/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.security; - -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; - -/** - * Security Configuration - LDAP and HTTP Authorizations. - */ -@Configuration -// @ImportResource({ "classpath:webSecurityConfig.xml" }) //=> uncomment to use equivalent xml config -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.ldapAuthentication().userSearchBase("ou=people").userSearchFilter("(uid={0})").groupSearchBase("ou=groups").groupSearchFilter("(member={0})").contextSource().root("dc=baeldung,dc=com").ldif("classpath:users.ldif"); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().antMatchers("/", "/home").permitAll().anyRequest().authenticated(); - http.formLogin().loginPage("/login").permitAll().and().logout().logoutSuccessUrl("/"); - } - -} diff --git a/spring-security-modules/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 30ba7671d8..0000000000 --- a/spring-security-modules/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.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(classes = SampleLDAPApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml b/spring-security-modules/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml index 659347f610..6c0f24e2c4 100644 --- a/spring-security-modules/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml +++ b/spring-security-modules/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml @@ -2,9 +2,9 @@ diff --git a/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml b/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml index 516829f5eb..8b8b4cd2f3 100644 --- a/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml +++ b/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml @@ -2,9 +2,9 @@ @@ -23,7 +23,7 @@ - + diff --git a/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml index 189522889f..543792fadc 100644 --- a/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ @@ -25,11 +25,11 @@ - + - + - + diff --git a/spring-security-modules/spring-security-mvc-login/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-security-modules/spring-security-mvc-login/src/main/webapp/WEB-INF/mvc-servlet.xml index 4ba9642448..fa2fae4148 100644 --- a/spring-security-modules/spring-security-mvc-login/src/main/webapp/WEB-INF/mvc-servlet.xml +++ b/spring-security-modules/spring-security-mvc-login/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd" > \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java index 4cf3b736ea..dfc83a40b0 100644 --- a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml" }) @WebAppConfiguration public class SpringContextTest { @Test diff --git a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java index 1235e2e69f..e2b444de20 100644 --- a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java @@ -25,7 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml" }) @WebAppConfiguration public class RedirectionSecurityIntegrationTest { diff --git a/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml b/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml deleted file mode 100644 index aa5488b116..0000000000 --- a/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/controller/MyController.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/controller/MyController.java new file mode 100644 index 0000000000..0ef07a2c19 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/controller/MyController.java @@ -0,0 +1,33 @@ +package com.baeldung.controller; + +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.RequestParam; +import org.springframework.web.servlet.ModelAndView; + +/** + * Web Controller. + * + */ +@Controller +public class MyController { + + /** + * Build the view model for the login page (add authentication error + * information in the event of an unsuccessful login attempt). + */ + @RequestMapping(value = "/login", method = RequestMethod.GET) + public ModelAndView login(@RequestParam(value = "error", required = false) String error) { + + ModelAndView model = new ModelAndView(); + if (error != null) { + model.addObject("message", "Username or password not recognised - please try again."); + } + + model.setViewName("login"); + return model; + + } + +} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java new file mode 100644 index 0000000000..5d3c59be11 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -0,0 +1,97 @@ +package com.baeldung.security; + +import java.io.IOException; +import java.util.Collection; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.web.DefaultRedirectStrategy; +import org.springframework.security.web.RedirectStrategy; +import org.springframework.security.web.WebAttributes; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.stereotype.Component; + +@Component(value = "mySimpleUrlAuthenticationSuccessHandler") +public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { + + private final Log logger = LogFactory.getLog(this.getClass()); + + private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); + + protected MySimpleUrlAuthenticationSuccessHandler() { + super(); + } + + // API + + @Override + public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { + handle(request, response, authentication); + clearAuthenticationAttributes(request); + } + + // IMPL + + protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { + final String targetUrl = determineTargetUrl(authentication); + + if (response.isCommitted()) { + logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); + return; + } + + redirectStrategy.sendRedirect(request, response, targetUrl); + } + + protected String determineTargetUrl(final Authentication authentication) { + boolean isUser = false; + boolean isAdmin = false; + final Collection authorities = authentication.getAuthorities(); + for (final GrantedAuthority grantedAuthority : authorities) { + if (grantedAuthority.getAuthority().equals(SecurityRole.ROLE_USER.toString())) { + isUser = true; + break; + } else if (grantedAuthority.getAuthority().equals(SecurityRole.ROLE_ADMIN.toString())) { + isAdmin = true; + break; + } + } + + if (isUser) { + return "/homepage.html"; + } else if (isAdmin) { + return "/console.html"; + } else { + throw new IllegalStateException(); + } + } + + /** + * Removes temporary authentication-related data which may have been stored in the session + * during the authentication process. + */ + protected final void clearAuthenticationAttributes(final HttpServletRequest request) { + final HttpSession session = request.getSession(false); + + if (session == null) { + return; + } + + session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); + } + + public void setRedirectStrategy(final RedirectStrategy redirectStrategy) { + this.redirectStrategy = redirectStrategy; + } + + protected RedirectStrategy getRedirectStrategy() { + return redirectStrategy; + } + +} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityRole.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityRole.java similarity index 78% rename from spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityRole.java rename to spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityRole.java index e41e7a4c4f..ffe385996d 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityRole.java +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityRole.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; /** * Simple enum of Security Roles available. diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java new file mode 100644 index 0000000000..98eb4cd41c --- /dev/null +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java @@ -0,0 +1,11 @@ +package com.baeldung.security; + +import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; + +/** + * Registers the springSecurityFilterChain Filter for every URL in the application. + * + */ +public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { + +} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/service/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/service/MyUserDetailsService.java new file mode 100644 index 0000000000..34782bdfab --- /dev/null +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/service/MyUserDetailsService.java @@ -0,0 +1,58 @@ +package com.baeldung.service; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import com.baeldung.security.SecurityRole; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.*; +import java.util.stream.Collectors; + +@Service +public class MyUserDetailsService implements UserDetailsService { + + private final Log logger = LogFactory.getLog(this.getClass()); + + private final Map availableUsers = new HashMap(); + + public MyUserDetailsService() { + populateDemoUsers(); + } + + @Override + public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { + logger.info("Load user by username " + username); + + final UserDetails user = availableUsers.get(username); + if (user == null) { + throw new UsernameNotFoundException(username); + } + + return user; + } + + /** + * Create demo users (note: obviously in a real system these would be persisted + * in database or retrieved from another system). + */ + private void populateDemoUsers() { + logger.info("Populate demo users"); + + availableUsers.put("user", createUser("user", "password", Arrays.asList(SecurityRole.ROLE_USER))); + availableUsers.put("admin", createUser("admin", "password", Arrays.asList(SecurityRole.ROLE_ADMIN))); + } + + private User createUser(final String username, final String password, final List roles) { + logger.info("Create user " + username); + + final List authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.toString())).collect(Collectors.toList()); + + return new User(username, password, true, true, true, true, authorities); + } +} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/MvcConfig.java new file mode 100644 index 0000000000..6fa3b522e7 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/MvcConfig.java @@ -0,0 +1,42 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +/** + * Spring Web Configuration. + */ +@EnableWebMvc +@ComponentScan("com.baeldung") +@Configuration +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/anonymous.html"); + registry.addViewController("/login.html"); + registry.addViewController("/homepage.html"); + registry.addViewController("/console.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-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/PersistenceConfig.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/PersistenceConfig.java new file mode 100644 index 0000000000..fe7b82b63d --- /dev/null +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -0,0 +1,38 @@ +package com.baeldung.spring; + +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.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +/** + * Spring Database Configuration. + */ +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-h2.properties" }) +public class PersistenceConfig { + + @Autowired + private Environment env; + + // + + @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; + } + +} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/SecurityConfig.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/SecurityConfig.java new file mode 100644 index 0000000000..d3cfff81cb --- /dev/null +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/SecurityConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +/** + * Spring Security Configuration. + */ +@Configuration +@EnableWebSecurity +@ImportResource({ "classpath:webSecurityConfig.xml" }) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + public SecurityConfig() { + super(); + } + +} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/controller/MyController.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/controller/MyController.java deleted file mode 100644 index 51202225ee..0000000000 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/controller/MyController.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.baeldung.controller; - -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.RequestParam; -import org.springframework.web.servlet.ModelAndView; - -/** - * Web Controller. - * - */ -@Controller -public class MyController { - - /** - * Build the view model for the login page (add authentication error - * information in the event of an unsuccessful login attempt). - */ - @RequestMapping(value = "/login", method = RequestMethod.GET) - public ModelAndView login(@RequestParam(value = "error", required = false) String error) { - - ModelAndView model = new ModelAndView(); - if (error != null) { - model.addObject("message", "Username or password not recognised - please try again."); - } - - model.setViewName("login"); - return model; - - } - -} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java deleted file mode 100644 index 22fd2cdcb6..0000000000 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.baeldung.security; - -import java.io.IOException; -import java.util.Collection; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.web.DefaultRedirectStrategy; -import org.springframework.security.web.RedirectStrategy; -import org.springframework.security.web.WebAttributes; -import org.springframework.security.web.authentication.AuthenticationSuccessHandler; -import org.springframework.stereotype.Component; - -@Component(value = "mySimpleUrlAuthenticationSuccessHandler") -public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { - - private final Log logger = LogFactory.getLog(this.getClass()); - - private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - - protected MySimpleUrlAuthenticationSuccessHandler() { - super(); - } - - // API - - @Override - public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { - handle(request, response, authentication); - clearAuthenticationAttributes(request); - } - - // IMPL - - protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { - final String targetUrl = determineTargetUrl(authentication); - - if (response.isCommitted()) { - logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); - return; - } - - redirectStrategy.sendRedirect(request, response, targetUrl); - } - - protected String determineTargetUrl(final Authentication authentication) { - boolean isUser = false; - boolean isAdmin = false; - final Collection authorities = authentication.getAuthorities(); - for (final GrantedAuthority grantedAuthority : authorities) { - if (grantedAuthority.getAuthority().equals(SecurityRole.ROLE_USER.toString())) { - isUser = true; - break; - } else if (grantedAuthority.getAuthority().equals(SecurityRole.ROLE_ADMIN.toString())) { - isAdmin = true; - break; - } - } - - if (isUser) { - return "/homepage.html"; - } else if (isAdmin) { - return "/console.html"; - } else { - throw new IllegalStateException(); - } - } - - /** - * Removes temporary authentication-related data which may have been stored in the session - * during the authentication process. - */ - protected final void clearAuthenticationAttributes(final HttpServletRequest request) { - final HttpSession session = request.getSession(false); - - if (session == null) { - return; - } - - session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); - } - - public void setRedirectStrategy(final RedirectStrategy redirectStrategy) { - this.redirectStrategy = redirectStrategy; - } - - protected RedirectStrategy getRedirectStrategy() { - return redirectStrategy; - } - -} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java deleted file mode 100644 index 75f782e7dc..0000000000 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.baeldung.security; - -import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; - -/** - * Registers the springSecurityFilterChain Filter for every URL in the application. - * - */ -public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { - -} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java deleted file mode 100644 index e6c77110b3..0000000000 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.baeldung.service; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.baeldung.security.SecurityRole; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; - -import java.util.*; -import java.util.stream.Collectors; - -@Service -public class MyUserDetailsService implements UserDetailsService { - - private final Log logger = LogFactory.getLog(this.getClass()); - - private final Map availableUsers = new HashMap(); - - public MyUserDetailsService() { - populateDemoUsers(); - } - - @Override - public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { - logger.info("Load user by username " + username); - - final UserDetails user = availableUsers.get(username); - if (user == null) { - throw new UsernameNotFoundException(username); - } - - return user; - } - - /** - * Create demo users (note: obviously in a real system these would be persisted - * in database or retrieved from another system). - */ - private void populateDemoUsers() { - logger.info("Populate demo users"); - - availableUsers.put("user", createUser("user", "password", Arrays.asList(SecurityRole.ROLE_USER))); - availableUsers.put("admin", createUser("admin", "password", Arrays.asList(SecurityRole.ROLE_ADMIN))); - } - - private User createUser(final String username, final String password, final List roles) { - logger.info("Create user " + username); - - final List authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.toString())).collect(Collectors.toList()); - - return new User(username, password, true, true, true, true, authorities); - } -} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/MvcConfig.java deleted file mode 100644 index d4e0c55004..0000000000 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/MvcConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -/** - * Spring Web Configuration. - */ -@EnableWebMvc -@ComponentScan("org.baeldung") -@Configuration -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/anonymous.html"); - registry.addViewController("/login.html"); - registry.addViewController("/homepage.html"); - registry.addViewController("/console.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-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/PersistenceConfig.java deleted file mode 100644 index 02308e64fb..0000000000 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.baeldung.spring; - -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.jdbc.datasource.DriverManagerDataSource; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.google.common.base.Preconditions; - -/** - * Spring Database Configuration. - */ -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-h2.properties" }) -public class PersistenceConfig { - - @Autowired - private Environment env; - - // - - @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; - } - -} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/SecurityConfig.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/SecurityConfig.java deleted file mode 100644 index 2d9bb8e731..0000000000 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/SecurityConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -/** - * Spring Security Configuration. - */ -@Configuration -@EnableWebSecurity -@ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - public SecurityConfig() { - super(); - } - -} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/web.xml b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/web.xml index aa52205420..11b922a801 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/web.xml @@ -19,7 +19,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..bf4951c83a --- /dev/null +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package com.baeldung; + +import com.baeldung.spring.MvcConfig; +import com.baeldung.spring.PersistenceConfig; +import com.baeldung.spring.SecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, PersistenceConfig.class, SecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 8113ed0fbe..0000000000 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.MvcConfig; -import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MvcConfig.class, PersistenceConfig.class, SecurityConfig.class }) -@WebAppConfiguration -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-mvc-socket/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-socket/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4ef4948601 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-socket/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,24 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.springsecuredsockets.config.AppConfig; +import com.baeldung.springsecuredsockets.config.DataStoreConfig; +import com.baeldung.springsecuredsockets.config.SecurityConfig; +import com.baeldung.springsecuredsockets.config.SocketBrokerConfig; +import com.baeldung.springsecuredsockets.config.SocketSecurityConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppConfig.class, DataStoreConfig.class, SecurityConfig.class, + SocketBrokerConfig.class, SocketSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 7b9c738904..0000000000 --- a/spring-security-modules/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -import com.baeldung.springsecuredsockets.config.AppConfig; -import com.baeldung.springsecuredsockets.config.DataStoreConfig; -import com.baeldung.springsecuredsockets.config.SecurityConfig; -import com.baeldung.springsecuredsockets.config.SocketBrokerConfig; -import com.baeldung.springsecuredsockets.config.SocketSecurityConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { AppConfig.class, DataStoreConfig.class, SecurityConfig.class, - SocketBrokerConfig.class, SocketSecurityConfig.class }) -@WebAppConfiguration -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-mvc/README.md b/spring-security-modules/spring-security-mvc/README.md index 7d1a492cd3..bb4cfe1a4f 100644 --- a/spring-security-modules/spring-security-mvc/README.md +++ b/spring-security-modules/spring-security-mvc/README.md @@ -10,6 +10,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [HttpSessionListener Example – Monitoring](https://www.baeldung.com/httpsessionlistener_with_metrics) - [Control the Session with Spring Security](https://www.baeldung.com/spring-security-session) +- [The Clear-Site-Data Header in Spring Security](https://www.baeldung.com/spring-security-clear-site-data-header) ### Build the Project diff --git a/spring-security-modules/spring-security-mvc/pom.xml b/spring-security-modules/spring-security-mvc/pom.xml index 7da047707a..517aa83270 100644 --- a/spring-security-modules/spring-security-mvc/pom.xml +++ b/spring-security-modules/spring-security-mvc/pom.xml @@ -64,9 +64,36 @@ org.springframework.security spring-security-test + ${spring.mvc.version} test + + org.springframework.security + spring-security-web + ${spring.mvc.version} + + + org.springframework.security + spring-security-config + ${spring.mvc.version} + + + org.springframework + spring-webmvc + ${spring.mvc.version} + + + javax.servlet + javax.servlet-api + ${javax.version} +
+ + + 5.2.2.RELEASE + 4.0.1 + + diff --git a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/LogoutClearSiteDataController.java b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/LogoutClearSiteDataController.java new file mode 100644 index 0000000000..fcf78ac82f --- /dev/null +++ b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/LogoutClearSiteDataController.java @@ -0,0 +1,16 @@ +package com.baeldung.clearsitedata; + +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +@Controller +public class LogoutClearSiteDataController { + + @GetMapping(value = "/baeldung/logout") + public ResponseEntity logout(@PathVariable String name) { + return ResponseEntity.ok().build(); + } + +} diff --git a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/SpringSecurityConfig.java b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/SpringSecurityConfig.java new file mode 100644 index 0000000000..13011da9e4 --- /dev/null +++ b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/SpringSecurityConfig.java @@ -0,0 +1,35 @@ +package com.baeldung.clearsitedata; + + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +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.logout.HeaderWriterLogoutHandler; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; + +import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.CACHE; +import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.COOKIES; +import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + + http.csrf() + .disable() + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/perform_login") + .defaultSuccessUrl("/homepage.html", true) + .and() + .logout().logoutUrl("/baeldung/logout") + .addLogoutHandler(new HeaderWriterLogoutHandler( + new ClearSiteDataHeaderWriter(CACHE, COOKIES, STORAGE))); + } +} diff --git a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/WebConfig.java b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/WebConfig.java new file mode 100644 index 0000000000..a523efa554 --- /dev/null +++ b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/WebConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.clearsitedata; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.CacheControl; +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.mvc.WebContentInterceptor; + +import java.util.concurrent.TimeUnit; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = {"com.baeldung.clearsitedata"}) +public class WebConfig implements WebMvcConfigurer { +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java index e2224996c2..ce122db609 100644 --- a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java +++ b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java @@ -13,7 +13,7 @@ public final class MetricRegistrySingleton { public static final MetricRegistry metrics = new MetricRegistry(); static { - Logger logger = LoggerFactory.getLogger("org.baeldung.monitoring"); + Logger logger = LoggerFactory.getLogger("com.baeldung.monitoring"); final Slf4jReporter reporter = Slf4jReporter.forRegistry(metrics).outputTo(logger).convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).build(); reporter.start(5, TimeUnit.MINUTES); } diff --git a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/session/web/config/MainWebAppInitializer.java b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/session/web/config/MainWebAppInitializer.java new file mode 100644 index 0000000000..f85f9f3fb0 --- /dev/null +++ b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/session/web/config/MainWebAppInitializer.java @@ -0,0 +1,16 @@ +package com.baeldung.session.web.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; + +import org.springframework.web.WebApplicationInitializer; + +public class MainWebAppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext sc) throws ServletException { + sc.getSessionCookieConfig().setHttpOnly(true); + sc.getSessionCookieConfig().setSecure(true); + } + +} diff --git a/spring-security-modules/spring-security-mvc/src/main/webapp/WEB-INF/web.xml b/spring-security-modules/spring-security-mvc/src/main/webapp/WEB-INF/web.xml index 88087c92ed..ec6bc0d3b4 100644 --- a/spring-security-modules/spring-security-mvc/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-modules/spring-security-mvc/src/main/webapp/WEB-INF/web.xml @@ -30,7 +30,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring @@ -60,7 +60,7 @@ - + 1 diff --git a/spring-security-modules/spring-security-rest/README.md b/spring-security-modules/spring-security-rest/README.md index 00bc2a1403..26c101d32c 100644 --- a/spring-security-modules/spring-security-rest/README.md +++ b/spring-security-modules/spring-security-rest/README.md @@ -8,11 +8,11 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: -- [Spring REST Service Security](https://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/) + - [Setting Up Swagger 2 with a Spring REST API](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Custom Error Message Handling for REST API](https://www.baeldung.com/global-error-handler-in-a-spring-rest-api) - [Spring Security Context Propagation with @Async](https://www.baeldung.com/spring-security-async-principal-propagation) - [Servlet 3 Async Support with Spring MVC and Spring Security](https://www.baeldung.com/spring-mvc-async-security) - [Intro to Spring Security Expressions](https://www.baeldung.com/spring-security-expressions) -- [Spring Security for a REST API](https://www.baeldung.com/securing-a-restful-web-service-with-spring-security) - [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) +- [Error Handling for REST with Spring](https://www.baeldung.com/exception-handling-for-rest-with-spring) diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/ApiError.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/ApiError.java similarity index 97% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/ApiError.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/ApiError.java index 8a1ddd8882..0fba2deca5 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/ApiError.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/ApiError.java @@ -1,4 +1,4 @@ -package org.baeldung.errorhandling; +package com.baeldung.errorhandling; import java.util.Arrays; import java.util.List; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/CustomRestExceptionHandler.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/CustomRestExceptionHandler.java similarity index 99% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/CustomRestExceptionHandler.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/CustomRestExceptionHandler.java index cd4d58e60c..02bc0a2512 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/CustomRestExceptionHandler.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/CustomRestExceptionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.errorhandling; +package com.baeldung.errorhandling; import java.util.ArrayList; import java.util.List; diff --git a/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/persistence/model/Foo.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/persistence/model/Foo.java new file mode 100644 index 0000000000..d85cca1dcc --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/persistence/model/Foo.java @@ -0,0 +1,78 @@ +package com.baeldung.persistence.model; + +import java.io.Serializable; + +import javax.validation.constraints.Size; + +public class Foo implements Serializable { + + private static final long serialVersionUID = -5422285893276747592L; + + private long id; + + @Size(min = 5, max = 14) + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + 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; + } + + // + + @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-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityJavaConfig.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityJavaConfig.java similarity index 92% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityJavaConfig.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityJavaConfig.java index 74623080b5..d20198c2bb 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityJavaConfig.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityJavaConfig.java @@ -1,8 +1,8 @@ -package org.baeldung.security; +package com.baeldung.security; -import org.baeldung.security.web.MySavedRequestAwareAuthenticationSuccessHandler; -import org.baeldung.security.web.RestAuthenticationEntryPoint; -import org.baeldung.web.error.CustomAccessDeniedHandler; +import com.baeldung.security.web.MySavedRequestAwareAuthenticationSuccessHandler; +import com.baeldung.security.web.RestAuthenticationEntryPoint; +import com.baeldung.web.error.CustomAccessDeniedHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -20,7 +20,7 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) -@ComponentScan("org.baeldung.security") +@ComponentScan("com.baeldung.security") public class SecurityJavaConfig extends WebSecurityConfigurerAdapter { @Autowired diff --git a/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java new file mode 100644 index 0000000000..77e70d5b84 --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java @@ -0,0 +1,10 @@ +package com.baeldung.security; + +import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; + +public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { + + public SecurityWebApplicationInitializer() { + super(SecurityJavaConfig.class); + } +} diff --git a/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java new file mode 100644 index 0000000000..2d74ed9dca --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java @@ -0,0 +1,43 @@ +package com.baeldung.security.web; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; +import org.springframework.security.web.savedrequest.HttpSessionRequestCache; +import org.springframework.security.web.savedrequest.RequestCache; +import org.springframework.security.web.savedrequest.SavedRequest; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +@Component +public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { + + private RequestCache requestCache = new HttpSessionRequestCache(); + + @Override + public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException { + final SavedRequest savedRequest = requestCache.getRequest(request, response); + + if (savedRequest == null) { + clearAuthenticationAttributes(request); + return; + } + final String targetUrlParameter = getTargetUrlParameter(); + if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) { + requestCache.removeRequest(request, response); + clearAuthenticationAttributes(request); + return; + } + + clearAuthenticationAttributes(request); + } + + public void setRequestCache(final RequestCache requestCache) { + this.requestCache = requestCache; + } +} diff --git a/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/RestAuthenticationEntryPoint.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/RestAuthenticationEntryPoint.java new file mode 100644 index 0000000000..162ee46727 --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/RestAuthenticationEntryPoint.java @@ -0,0 +1,27 @@ +package com.baeldung.security.web; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +/** + * The Entry Point will not redirect to any sort of Login - it will return the 401 + */ +@Component +public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { + + @Override + public void commence( + final HttpServletRequest request, + final HttpServletResponse response, + final AuthenticationException authException) throws IOException { + + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/ClientWebConfig.java new file mode 100644 index 0000000000..db24817f5b --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@EnableWebMvc +@Configuration +public class ClientWebConfig implements WebMvcConfigurer { +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/SecurityXmlConfig.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/SecurityXmlConfig.java new file mode 100644 index 0000000000..92f7cea784 --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/SecurityXmlConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.ComponentScan; + +// @Configuration +// @ImportResource({ "classpath:webSecurityConfig.xml" }) +@ComponentScan("com.baeldung.security") +public class SecurityXmlConfig { + + public SecurityXmlConfig() { + super(); + } + +} diff --git a/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/WebConfig.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/WebConfig.java new file mode 100644 index 0000000000..84b211a9bd --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/WebConfig.java @@ -0,0 +1,40 @@ +package com.baeldung.spring; + +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.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.WebMvcConfigurer; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@ComponentScan("com.baeldung.web") +@EnableWebMvc +@EnableAsync +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); + + registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setPrefix("/WEB-INF/view/"); + viewResolver.setSuffix(".jsp"); + return viewResolver; + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/csrfAttacker.html"); + } + +} diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/swagger2/SwaggerConfig.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/swagger2/SwaggerConfig.java similarity index 94% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/swagger2/SwaggerConfig.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/swagger2/SwaggerConfig.java index 67c760353d..c8c4227ebf 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/swagger2/SwaggerConfig.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/swagger2/SwaggerConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.swagger2; +package com.baeldung.swagger2; import static com.google.common.collect.Lists.newArrayList; @@ -25,7 +25,7 @@ public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).select() - .apis(RequestHandlerSelectors.basePackage("org.baeldung.web.controller")) + .apis(RequestHandlerSelectors.basePackage("com.baeldung.web.controller")) .paths(PathSelectors.ant("/foos/*")) .build() .apiInfo(apiInfo()) diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/AsyncController.java similarity index 94% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/AsyncController.java index f6f1c392cb..c2123913c6 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/AsyncController.java @@ -1,11 +1,11 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import java.util.concurrent.Callable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.baeldung.web.service.AsyncService; +import com.baeldung.web.service.AsyncService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/CustomController.java similarity index 90% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/CustomController.java index 7d40b9bb8d..d833d3af7a 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/CustomController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/FooController.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/FooController.java new file mode 100644 index 0000000000..033bf2d1e3 --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/FooController.java @@ -0,0 +1,49 @@ +package com.baeldung.web.controller; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +import java.util.List; + +import javax.servlet.http.HttpServletResponse; + +import com.baeldung.persistence.model.Foo; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +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.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.util.UriComponentsBuilder; + +import com.google.common.collect.Lists; + +@Controller +@RequestMapping(value = "/foos") +public class FooController { + + // API + + // read - single + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public Foo findById(@PathVariable("id") final Long id, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { + return new Foo(randomAlphabetic(6)); + } + + // read - multiple + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public List findAll() { + return Lists.newArrayList(new Foo(randomAlphabetic(6))); + } + + // write - just for test + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo create(@RequestBody final Foo foo) { + return foo; + } +} diff --git a/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/RootController.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/RootController.java new file mode 100644 index 0000000000..3abbe8a309 --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/RootController.java @@ -0,0 +1,30 @@ +package com.baeldung.web.controller; + +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; + +@Controller +public class RootController { + + public RootController() { + super(); + } + + // API + + @RequestMapping(value = "/admin/x", method = RequestMethod.GET) + @ResponseBody + public String sampleAdminPage() { + return "Hello"; + } + + + @RequestMapping(value = "/my-error-page", method = RequestMethod.GET) + @ResponseBody + public String sampleErrorPage() { + return "Error Occurred"; + } + +} diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/CustomAccessDeniedHandler.java similarity index 96% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/CustomAccessDeniedHandler.java index cc07417427..6c686cd9e9 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/CustomAccessDeniedHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.web.error; +package com.baeldung.web.error; import java.io.IOException; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java similarity index 99% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java index 9ff4f040fe..9e6ae78d27 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.web.error; +package com.baeldung.web.error; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; diff --git a/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java new file mode 100644 index 0000000000..fd002efc28 --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java @@ -0,0 +1,21 @@ +package com.baeldung.web.exception; + +public final class MyResourceNotFoundException extends RuntimeException { + + public MyResourceNotFoundException() { + super(); + } + + public MyResourceNotFoundException(final String message, final Throwable cause) { + super(message, cause); + } + + public MyResourceNotFoundException(final String message) { + super(message); + } + + public MyResourceNotFoundException(final Throwable cause) { + super(cause); + } + +} diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncService.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncService.java similarity index 81% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncService.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncService.java index 1ba4dfa4cb..ee07313ee8 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncService.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncService.java @@ -1,4 +1,4 @@ -package org.baeldung.web.service; +package com.baeldung.web.service; import java.util.concurrent.Callable; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncServiceImpl.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncServiceImpl.java similarity index 97% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncServiceImpl.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncServiceImpl.java index d6d7f53dd7..8aebbc3234 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncServiceImpl.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncServiceImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.web.service; +package com.baeldung.web.service; import java.util.concurrent.Callable; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/persistence/model/Foo.java deleted file mode 100644 index 05a7c7b9a0..0000000000 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/persistence/model/Foo.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.baeldung.persistence.model; - -import java.io.Serializable; - -import javax.validation.constraints.Size; - -public class Foo implements Serializable { - - private static final long serialVersionUID = -5422285893276747592L; - - private long id; - - @Size(min = 5, max = 14) - private String name; - - public Foo() { - super(); - } - - public Foo(final String name) { - super(); - - 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; - } - - // - - @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-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java deleted file mode 100644 index c56568e979..0000000000 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.baeldung.security.web; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.security.core.Authentication; -import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; -import org.springframework.security.web.savedrequest.HttpSessionRequestCache; -import org.springframework.security.web.savedrequest.RequestCache; -import org.springframework.security.web.savedrequest.SavedRequest; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - -@Component -public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { - - private RequestCache requestCache = new HttpSessionRequestCache(); - - @Override - public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException { - final SavedRequest savedRequest = requestCache.getRequest(request, response); - - if (savedRequest == null) { - clearAuthenticationAttributes(request); - return; - } - final String targetUrlParameter = getTargetUrlParameter(); - if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) { - requestCache.removeRequest(request, response); - clearAuthenticationAttributes(request); - return; - } - - clearAuthenticationAttributes(request); - } - - public void setRequestCache(final RequestCache requestCache) { - this.requestCache = requestCache; - } -} diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/RestAuthenticationEntryPoint.java b/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/RestAuthenticationEntryPoint.java deleted file mode 100644 index 643e2f0575..0000000000 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/RestAuthenticationEntryPoint.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.baeldung.security.web; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.stereotype.Component; - -/** - * The Entry Point will not redirect to any sort of Login - it will return the 401 - */ -@Component -public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { - - @Override - public void commence( - final HttpServletRequest request, - final HttpServletResponse response, - final AuthenticationException authException) throws IOException { - - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/ClientWebConfig.java b/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/ClientWebConfig.java deleted file mode 100644 index 8e20358a5a..0000000000 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/ClientWebConfig.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@EnableWebMvc -@Configuration -public class ClientWebConfig implements WebMvcConfigurer { -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/SecurityXmlConfig.java b/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/SecurityXmlConfig.java deleted file mode 100644 index 0830a1ebe1..0000000000 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/SecurityXmlConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.ComponentScan; - -// @Configuration -// @ImportResource({ "classpath:webSecurityConfig.xml" }) -@ComponentScan("org.baeldung.security") -public class SecurityXmlConfig { - - public SecurityXmlConfig() { - super(); - } - -} diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java deleted file mode 100644 index dba07dc4e5..0000000000 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.scheduling.annotation.EnableAsync; -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.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -@ComponentScan("org.baeldung.web") -@EnableWebMvc -@EnableAsync -public class WebConfig implements WebMvcConfigurer { - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); - - registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/WEB-INF/view/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - registry.addViewController("/csrfAttacker.html"); - } - -} diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/FooController.java deleted file mode 100644 index f914f82215..0000000000 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/FooController.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.baeldung.web.controller; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; - -import java.util.List; - -import javax.servlet.http.HttpServletResponse; - -import org.baeldung.persistence.model.Foo; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -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.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.util.UriComponentsBuilder; - -import com.google.common.collect.Lists; - -@Controller -@RequestMapping(value = "/foos") -public class FooController { - - // API - - // read - single - @RequestMapping(value = "/{id}", method = RequestMethod.GET) - @ResponseBody - public Foo findById(@PathVariable("id") final Long id, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { - return new Foo(randomAlphabetic(6)); - } - - // read - multiple - @RequestMapping(method = RequestMethod.GET) - @ResponseBody - public List findAll() { - return Lists.newArrayList(new Foo(randomAlphabetic(6))); - } - - // write - just for test - @RequestMapping(method = RequestMethod.POST) - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Foo create(@RequestBody final Foo foo) { - return foo; - } -} diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/RootController.java b/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/RootController.java deleted file mode 100644 index 4253ed7a59..0000000000 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/RootController.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.baeldung.web.controller; - -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; - -@Controller -public class RootController { - - public RootController() { - super(); - } - - // API - - @RequestMapping(value = "/admin/x", method = RequestMethod.GET) - @ResponseBody - public String sampleAdminPage() { - return "Hello"; - } - - - @RequestMapping(value = "/my-error-page", method = RequestMethod.GET) - @ResponseBody - public String sampleErrorPage() { - return "Error Occurred"; - } - -} diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java deleted file mode 100644 index 14b61f9832..0000000000 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.web.exception; - -public final class MyResourceNotFoundException extends RuntimeException { - - public MyResourceNotFoundException() { - super(); - } - - public MyResourceNotFoundException(final String message, final Throwable cause) { - super(message, cause); - } - - public MyResourceNotFoundException(final String message) { - super(message); - } - - public MyResourceNotFoundException(final Throwable cause) { - super(cause); - } - -} diff --git a/spring-security-modules/spring-security-rest/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-rest/src/main/resources/webSecurityConfig.xml index edd3cba39c..2c0a0bc774 100644 --- a/spring-security-modules/spring-security-rest/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-rest/src/main/resources/webSecurityConfig.xml @@ -30,7 +30,7 @@ + class="com.baeldung.security.MySavedRequestAwareAuthenticationSuccessHandler" /> diff --git a/spring-security-modules/spring-security-rest/src/main/webapp/WEB-INF/web.xml b/spring-security-modules/spring-security-rest/src/main/webapp/WEB-INF/web.xml index 3195603837..663c17bc56 100644 --- a/spring-security-modules/spring-security-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-modules/spring-security-rest/src/main/webapp/WEB-INF/web.xml @@ -17,7 +17,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring diff --git a/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..bcc66558cb --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package com.baeldung; + +import com.baeldung.security.SecurityJavaConfig; +import com.baeldung.spring.ClientWebConfig; +import com.baeldung.spring.WebConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/errorhandling/FooLiveTest.java b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/errorhandling/FooLiveTest.java new file mode 100644 index 0000000000..e08a24676a --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/errorhandling/FooLiveTest.java @@ -0,0 +1,87 @@ +package com.baeldung.errorhandling; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.baeldung.web.TestConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.jayway.restassured.RestAssured; +import com.jayway.restassured.response.Response; +import com.jayway.restassured.specification.RequestSpecification; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +public class FooLiveTest { + private static final String URL_PREFIX = "http://localhost:8080/spring-security-rest"; + // private FormAuthConfig formConfig = new FormAuthConfig(URL_PREFIX + "/login", "temporary", "temporary"); + + private String cookie; + + private RequestSpecification givenAuth() { + // return RestAssured.given().auth().form("user", "userPass", formConfig); + // if (cookie == null) { + // cookie = RestAssured.given().contentType("application/x-www-form-urlencoded").formParam("password", "userPass").formParam("username", "user").post(URL_PREFIX + "/login").getCookie("JSESSIONID"); + // } + // return RestAssured.given().cookie("JSESSIONID", cookie); + return RestAssured.given() + .auth().preemptive() + .basic("user", "userPass"); + } + + @Test + public void whenTry_thenOK() { + final Response response = givenAuth().get(URL_PREFIX + "/api/foos"); + assertEquals(200, response.statusCode()); + System.out.println(response.asString()); + + } + + @Test + public void whenMethodArgumentMismatch_thenBadRequest() { + final Response response = givenAuth().get(URL_PREFIX + "/api/foos/ccc"); + final ApiError error = response.as(ApiError.class); + assertEquals(HttpStatus.BAD_REQUEST, error.getStatus()); + assertEquals(1, error.getErrors().size()); + assertTrue(error.getErrors().get(0).contains("should be of type")); + } + + @Test + public void whenNoHandlerForHttpRequest_thenNotFound() { + final Response response = givenAuth().delete(URL_PREFIX + "/api/xx"); + final ApiError error = response.as(ApiError.class); + assertEquals(HttpStatus.NOT_FOUND, error.getStatus()); + assertEquals(1, error.getErrors().size()); + assertTrue(error.getErrors().get(0).contains("No handler found")); + System.out.println(response.asString()); + + } + + @Test + public void whenHttpRequestMethodNotSupported_thenMethodNotAllowed() { + final Response response = givenAuth().delete(URL_PREFIX + "/api/foos/1"); + final ApiError error = response.as(ApiError.class); + assertEquals(HttpStatus.METHOD_NOT_ALLOWED, error.getStatus()); + assertEquals(1, error.getErrors().size()); + assertTrue(error.getErrors().get(0).contains("Supported methods are")); + System.out.println(response.asString()); + + } + + @Test + public void whenSendInvalidHttpMediaType_thenUnsupportedMediaType() { + final Response response = givenAuth().body("").post(URL_PREFIX + "/api/foos"); + final ApiError error = response.as(ApiError.class); + assertEquals(HttpStatus.UNSUPPORTED_MEDIA_TYPE, error.getStatus()); + assertEquals(1, error.getErrors().size()); + assertTrue(error.getErrors().get(0).contains("media type is not supported")); + System.out.println(response.asString()); + + } + +} diff --git a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerIntegrationTest.java b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/AsyncControllerIntegrationTest.java similarity index 87% rename from spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerIntegrationTest.java rename to spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/AsyncControllerIntegrationTest.java index 1e5e1b7d85..bf93c14f1f 100644 --- a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerIntegrationTest.java +++ b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/AsyncControllerIntegrationTest.java @@ -1,9 +1,9 @@ -package org.baeldung.web; +package com.baeldung.web; -import org.baeldung.security.SecurityJavaConfig; -import org.baeldung.spring.ClientWebConfig; -import org.baeldung.spring.WebConfig; -import org.baeldung.web.controller.AsyncController; +import com.baeldung.security.SecurityJavaConfig; +import com.baeldung.spring.ClientWebConfig; +import com.baeldung.spring.WebConfig; +import com.baeldung.web.controller.AsyncController; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/SwaggerLiveTest.java similarity index 95% rename from spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java rename to spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/SwaggerLiveTest.java index 792b3e28ce..3f86b63503 100644 --- a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java +++ b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/SwaggerLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.web; import static org.junit.Assert.assertEquals; diff --git a/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/TestConfig.java b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/TestConfig.java new file mode 100644 index 0000000000..ddb7240611 --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/TestConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.web; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.multipart.MultipartResolver; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; + +@Configuration +@ComponentScan({ "com.baeldung.web" }) +public class TestConfig { + + @Bean + public MultipartResolver multipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + return multipartResolver; + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 11586ce670..0000000000 --- a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung; - -import org.baeldung.security.SecurityJavaConfig; -import org.baeldung.spring.ClientWebConfig; -import org.baeldung.spring.WebConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class }) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/errorhandling/FooLiveTest.java b/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/errorhandling/FooLiveTest.java deleted file mode 100644 index 8d1db5736f..0000000000 --- a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/errorhandling/FooLiveTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.baeldung.errorhandling; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.baeldung.errorhandling.ApiError; -import org.baeldung.web.TestConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.http.HttpStatus; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.jayway.restassured.RestAssured; -import com.jayway.restassured.response.Response; -import com.jayway.restassured.specification.RequestSpecification; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class FooLiveTest { - private static final String URL_PREFIX = "http://localhost:8080/spring-security-rest"; - // private FormAuthConfig formConfig = new FormAuthConfig(URL_PREFIX + "/login", "temporary", "temporary"); - - private String cookie; - - private RequestSpecification givenAuth() { - // return RestAssured.given().auth().form("user", "userPass", formConfig); - // if (cookie == null) { - // cookie = RestAssured.given().contentType("application/x-www-form-urlencoded").formParam("password", "userPass").formParam("username", "user").post(URL_PREFIX + "/login").getCookie("JSESSIONID"); - // } - // return RestAssured.given().cookie("JSESSIONID", cookie); - return RestAssured.given() - .auth().preemptive() - .basic("user", "userPass"); - } - - @Test - public void whenTry_thenOK() { - final Response response = givenAuth().get(URL_PREFIX + "/api/foos"); - assertEquals(200, response.statusCode()); - System.out.println(response.asString()); - - } - - @Test - public void whenMethodArgumentMismatch_thenBadRequest() { - final Response response = givenAuth().get(URL_PREFIX + "/api/foos/ccc"); - final ApiError error = response.as(ApiError.class); - assertEquals(HttpStatus.BAD_REQUEST, error.getStatus()); - assertEquals(1, error.getErrors().size()); - assertTrue(error.getErrors().get(0).contains("should be of type")); - } - - @Test - public void whenNoHandlerForHttpRequest_thenNotFound() { - final Response response = givenAuth().delete(URL_PREFIX + "/api/xx"); - final ApiError error = response.as(ApiError.class); - assertEquals(HttpStatus.NOT_FOUND, error.getStatus()); - assertEquals(1, error.getErrors().size()); - assertTrue(error.getErrors().get(0).contains("No handler found")); - System.out.println(response.asString()); - - } - - @Test - public void whenHttpRequestMethodNotSupported_thenMethodNotAllowed() { - final Response response = givenAuth().delete(URL_PREFIX + "/api/foos/1"); - final ApiError error = response.as(ApiError.class); - assertEquals(HttpStatus.METHOD_NOT_ALLOWED, error.getStatus()); - assertEquals(1, error.getErrors().size()); - assertTrue(error.getErrors().get(0).contains("Supported methods are")); - System.out.println(response.asString()); - - } - - @Test - public void whenSendInvalidHttpMediaType_thenUnsupportedMediaType() { - final Response response = givenAuth().body("").post(URL_PREFIX + "/api/foos"); - final ApiError error = response.as(ApiError.class); - assertEquals(HttpStatus.UNSUPPORTED_MEDIA_TYPE, error.getStatus()); - assertEquals(1, error.getErrors().size()); - assertTrue(error.getErrors().get(0).contains("media type is not supported")); - System.out.println(response.asString()); - - } - -} diff --git a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java b/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java deleted file mode 100644 index 61bd6e776b..0000000000 --- a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung.web; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.multipart.MultipartResolver; -import org.springframework.web.multipart.commons.CommonsMultipartResolver; - -@Configuration -@ComponentScan({ "org.baeldung.web" }) -public class TestConfig { - - @Bean - public MultipartResolver multipartResolver() { - CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); - return multipartResolver; - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-sso/pom.xml b/spring-security-modules/spring-security-sso/pom.xml index 3d9c1bf595..4e5bb49aa3 100644 --- a/spring-security-modules/spring-security-sso/pom.xml +++ b/spring-security-modules/spring-security-sso/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-security-sso 1.0.0-SNAPSHOT spring-security-sso diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/pom.xml b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/pom.xml index 933cb6a2b2..3537c01e46 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/pom.xml +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/pom.xml @@ -7,7 +7,7 @@ war - org.baeldung + com.baeldung spring-security-sso 1.0.0-SNAPSHOT diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthServerConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthServerConfig.java similarity index 98% rename from spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthServerConfig.java rename to spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthServerConfig.java index 0835f3d721..9a6400abdf 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthServerConfig.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthServerConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthorizationServerApplication.java similarity index 94% rename from spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java rename to spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthorizationServerApplication.java index b74d2f144c..5cfcb2bb5b 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthorizationServerApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/SecurityConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..29c7549753 --- /dev/null +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/SecurityConfig.java @@ -0,0 +1,41 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +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 { + + @Override + protected void configure(HttpSecurity http) throws Exception { // @formatter:off + http.requestMatchers() + .antMatchers("/login", "/oauth/authorize") + .and() + .authorizeRequests() + .anyRequest() + .authenticated() + .and() + .formLogin() + .permitAll() + .and().csrf().disable(); + } // @formatter:on + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off + auth.inMemoryAuthentication() + .withUser("john") + .password(passwordEncoder().encode("123")) + .roles("USER"); + } // @formatter:on + + @Bean + public BCryptPasswordEncoder passwordEncoder(){ + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/UserController.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/UserController.java new file mode 100644 index 0000000000..80415fbd30 --- /dev/null +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/UserController.java @@ -0,0 +1,16 @@ +package com.baeldung.config; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserController { + + @RequestMapping("/user/me") + public Principal user(Principal principal) { + System.out.println(principal); + return principal; + } +} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/SecurityConfig.java deleted file mode 100644 index 2254de8e39..0000000000 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/SecurityConfig.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -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 { - - @Override - protected void configure(HttpSecurity http) throws Exception { // @formatter:off - http.requestMatchers() - .antMatchers("/login", "/oauth/authorize") - .and() - .authorizeRequests() - .anyRequest() - .authenticated() - .and() - .formLogin() - .permitAll() - .and().csrf().disable(); - } // @formatter:on - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off - auth.inMemoryAuthentication() - .withUser("john") - .password(passwordEncoder().encode("123")) - .roles("USER"); - } // @formatter:on - - @Bean - public BCryptPasswordEncoder passwordEncoder(){ - return new BCryptPasswordEncoder(); - } -} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/UserController.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/UserController.java deleted file mode 100644 index 28128f9d97..0000000000 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/UserController.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.config; - -import java.security.Principal; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class UserController { - - @RequestMapping("/user/me") - public Principal user(Principal principal) { - System.out.println(principal); - return principal; - } -} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1f07837da9 --- /dev/null +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import com.baeldung.config.AuthorizationServerApplication; +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.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AuthorizationServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/UserInfoEndpointLiveTest.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/UserInfoEndpointLiveTest.java similarity index 99% rename from spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/UserInfoEndpointLiveTest.java rename to spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/UserInfoEndpointLiveTest.java index ffdb1df8fe..104f980dd2 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/UserInfoEndpointLiveTest.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/UserInfoEndpointLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import static org.junit.Assert.assertEquals; import java.util.HashMap; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index f677f683b2..0000000000 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.baeldung.config.AuthorizationServerApplication; -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.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AuthorizationServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class SpringContextTest { - - @Test - public void whenLoadApplication_thenSuccess() { - - } -} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md index 0227d9ac70..3aa092edb8 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md +++ b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md @@ -1,4 +1,3 @@ ## Relevant articles: -- [Introduction to SPNEGO/Kerberos Authentication in Spring](https://www.baeldung.com/spring-security-kerberos) - [Spring Security Kerberos Integration](https://www.baeldung.com/spring-security-kerberos-integration) diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/pom.xml b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/pom.xml index 88b9354538..0864ead1c4 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/pom.xml +++ b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/pom.xml @@ -6,7 +6,7 @@ spring-security-sso-kerberos - org.baeldung + com.baeldung spring-security-sso 1.0.0-SNAPSHOT diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/pom.xml b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/pom.xml index 10592a5e92..0645ba3593 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/pom.xml +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/pom.xml @@ -7,7 +7,7 @@ war - org.baeldung + com.baeldung spring-security-sso 1.0.0-SNAPSHOT diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiApplication.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiApplication.java new file mode 100644 index 0000000000..ca178cfa7e --- /dev/null +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiApplication.java @@ -0,0 +1,21 @@ +package com.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.web.context.request.RequestContextListener; + +@SpringBootApplication +public class UiApplication extends SpringBootServletInitializer { + + + @Bean + public RequestContextListener requestContextListener() { + return new RequestContextListener(); + } + + public static void main(String[] args) { + SpringApplication.run(UiApplication.class, args); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiSecurityConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiSecurityConfig.java new file mode 100644 index 0000000000..7ef1392659 --- /dev/null +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiSecurityConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.config; + +import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + + +@EnableOAuth2Sso +@Configuration +public class UiSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/", "/login**") + .permitAll() + .anyRequest() + .authenticated(); + } + +} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiWebConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiWebConfig.java new file mode 100644 index 0000000000..ae5008daa3 --- /dev/null +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiWebConfig.java @@ -0,0 +1,36 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.*; + +@Configuration +@EnableWebMvc +public class UiWebConfig implements WebMvcConfigurer { + + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/") + .setViewName("forward:/index"); + registry.addViewController("/index"); + registry.addViewController("/securedPage"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**") + .addResourceLocations("/resources/"); + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java deleted file mode 100644 index 0c20853aed..0000000000 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.Bean; -import org.springframework.web.context.request.RequestContextListener; - -@SpringBootApplication -public class UiApplication extends SpringBootServletInitializer { - - - @Bean - public RequestContextListener requestContextListener() { - return new RequestContextListener(); - } - - public static void main(String[] args) { - SpringApplication.run(UiApplication.class, args); - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java deleted file mode 100644 index de81ada9e0..0000000000 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - - -@EnableOAuth2Sso -@Configuration -public class UiSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/", "/login**") - .permitAll() - .anyRequest() - .authenticated(); - } - -} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiWebConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiWebConfig.java deleted file mode 100644 index c17bb85173..0000000000 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiWebConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.web.servlet.config.annotation.*; - -@Configuration -@EnableWebMvc -public class UiWebConfig implements WebMvcConfigurer { - - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Override - public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - registry.addViewController("/") - .setViewName("forward:/index"); - registry.addViewController("/index"); - registry.addViewController("/securedPage"); - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**") - .addResourceLocations("/resources/"); - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1eeab34e94 --- /dev/null +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import com.baeldung.config.UiApplication; +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.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 61a2a022ed..0000000000 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.baeldung.config.UiApplication; -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.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class SpringContextTest { - - @Test - public void whenLoadApplication_thenSuccess() { - - } -} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/pom.xml b/spring-security-modules/spring-security-sso/spring-security-sso-ui/pom.xml index 2f0ac3a42e..d34317a4b0 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui/pom.xml +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui/pom.xml @@ -7,7 +7,7 @@ war - org.baeldung + com.baeldung spring-security-sso 1.0.0-SNAPSHOT diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiApplication.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiApplication.java new file mode 100644 index 0000000000..16d94d6d80 --- /dev/null +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiApplication.java @@ -0,0 +1,21 @@ +package com.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.web.context.request.RequestContextListener; + + +@SpringBootApplication +public class UiApplication extends SpringBootServletInitializer { + + @Bean + public RequestContextListener requestContextListener() { + return new RequestContextListener(); + } + + public static void main(String[] args) { + SpringApplication.run(UiApplication.class, args); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiSecurityConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiSecurityConfig.java new file mode 100644 index 0000000000..7ef1392659 --- /dev/null +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiSecurityConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.config; + +import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + + +@EnableOAuth2Sso +@Configuration +public class UiSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/", "/login**") + .permitAll() + .anyRequest() + .authenticated(); + } + +} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiWebConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiWebConfig.java new file mode 100644 index 0000000000..ae5008daa3 --- /dev/null +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiWebConfig.java @@ -0,0 +1,36 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.*; + +@Configuration +@EnableWebMvc +public class UiWebConfig implements WebMvcConfigurer { + + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/") + .setViewName("forward:/index"); + registry.addViewController("/index"); + registry.addViewController("/securedPage"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**") + .addResourceLocations("/resources/"); + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java deleted file mode 100644 index 07d875d805..0000000000 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.Bean; -import org.springframework.web.context.request.RequestContextListener; - - -@SpringBootApplication -public class UiApplication extends SpringBootServletInitializer { - - @Bean - public RequestContextListener requestContextListener() { - return new RequestContextListener(); - } - - public static void main(String[] args) { - SpringApplication.run(UiApplication.class, args); - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java deleted file mode 100644 index de81ada9e0..0000000000 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - - -@EnableOAuth2Sso -@Configuration -public class UiSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/", "/login**") - .permitAll() - .anyRequest() - .authenticated(); - } - -} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiWebConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiWebConfig.java deleted file mode 100644 index c17bb85173..0000000000 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiWebConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.web.servlet.config.annotation.*; - -@Configuration -@EnableWebMvc -public class UiWebConfig implements WebMvcConfigurer { - - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Override - public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - registry.addViewController("/") - .setViewName("forward:/index"); - registry.addViewController("/index"); - registry.addViewController("/securedPage"); - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**") - .addResourceLocations("/resources/"); - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1eeab34e94 --- /dev/null +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import com.baeldung.config.UiApplication; +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.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 61a2a022ed..0000000000 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.baeldung.config.UiApplication; -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.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class SpringContextTest { - - @Test - public void whenLoadApplication_thenSuccess() { - - } -} diff --git a/spring-security-modules/spring-security-x509/README.md b/spring-security-modules/spring-security-x509/README.md index b1eb0debf5..da431d862c 100644 --- a/spring-security-modules/spring-security-x509/README.md +++ b/spring-security-modules/spring-security-x509/README.md @@ -4,3 +4,10 @@ This module contains articles about X.509 authentication with Spring Security ### Relevant Articles: - [X.509 Authentication in Spring Security](https://www.baeldung.com/x-509-authentication-in-spring-security) + +###### Note for the [X.509 Authentication in Spring Security](https://www.baeldung.com/x-509-authentication-in-spring-security): +All the ready to use certificates are located in the [store](store) directory. The application is already configured to use these files. +This means the app works out of the box. + +However, it's highly recommended that you follow the article step by step and generate all the needed files by yourself. +This will let you understand the topic more deeply. \ No newline at end of file diff --git a/spring-security-modules/spring-security-x509/keystore/Makefile b/spring-security-modules/spring-security-x509/keystore/Makefile deleted file mode 100644 index 2cd7c55c5b..0000000000 --- a/spring-security-modules/spring-security-x509/keystore/Makefile +++ /dev/null @@ -1,92 +0,0 @@ -PASSWORD=changeit -KEYSTORE=keystore.jks -HOSTNAME=localhost -CLIENTNAME=cid -CLIENT_PRIVATE_KEY="${CLIENTNAME}_pk" - -# CN = Common Name -# OU = Organization Unit -# O = Organization Name -# L = Locality Name -# ST = State Name -# C = Country (2-letter Country Code) -# E = Email -DNAME_CA='CN=Baeldung CA,OU=baeldung.com,O=Baeldung,L=SomeCity,ST=SomeState,C=CC' -# For server certificates, the Common Name (CN) must be the hostname -DNAME_HOST='CN=$(HOSTNAME),OU=baeldung.com,O=Baeldung,L=SomeCity,ST=SomeState,C=CC' -DNAME_CLIENT='CN=$(CLIENTNAME),OU=baeldung.com,O=Baeldung,L=SomeCity,ST=SomeState,C=CC' -TRUSTSTORE=truststore.jks - -all: clean create-keystore add-host create-truststore add-client - -create-keystore: - # Generate a certificate authority (CA) - keytool -genkey -alias ca -ext san=dns:localhost,ip:127.0.0.1 -ext BC=ca:true \ - -keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \ - -validity 3650 -dname $(DNAME_CA) \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - -add-host: - # Generate a host certificate - keytool -genkey -alias $(HOSTNAME) -ext san=dns:localhost,ip:127.0.0.1 \ - -keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \ - -validity 3650 -dname $(DNAME_HOST) \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - # Generate a host certificate signing request - keytool -certreq -alias $(HOSTNAME) -ext san=dns:localhost,ip:127.0.0.1 -ext BC=ca:true \ - -keyalg RSA -keysize 4096 -sigalg SHA512withRSA \ - -validity 3650 -file "$(HOSTNAME).csr" \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - # Generate signed certificate with the certificate authority - keytool -gencert -alias ca -ext san=dns:localhost,ip:127.0.0.1 \ - -validity 3650 -sigalg SHA512withRSA \ - -infile "$(HOSTNAME).csr" -outfile "$(HOSTNAME).crt" -rfc \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - # Import signed certificate into the keystore - keytool -import -trustcacerts -alias $(HOSTNAME) -ext san=dns:localhost,ip:127.0.0.1 \ - -file "$(HOSTNAME).crt" \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - -export-authority: - # Export certificate authority - keytool -export -alias ca -ext san=dns:localhost,ip:127.0.0.1 -file ca.crt -rfc \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - - -create-truststore: export-authority - # Import certificate authority into a new truststore - keytool -import -trustcacerts -noprompt -alias ca -ext san=dns:localhost,ip:127.0.0.1 -file ca.crt \ - -keystore $(TRUSTSTORE) -storepass $(PASSWORD) - -add-client: - # Generate client certificate - keytool -genkey -alias $(CLIENT_PRIVATE_KEY) -ext san=dns:localhost,ip:127.0.0.1 \ - -keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \ - -validity 3650 -dname $(DNAME_CLIENT) \ - -keystore $(TRUSTSTORE) -storepass $(PASSWORD) - # Generate a host certificate signing request - keytool -certreq -alias $(CLIENT_PRIVATE_KEY) -ext san=dns:localhost,ip:127.0.0.1 -ext BC=ca:true \ - -keyalg RSA -keysize 4096 -sigalg SHA512withRSA \ - -validity 3650 -file "$(CLIENTNAME).csr" \ - -keystore $(TRUSTSTORE) -storepass $(PASSWORD) - # Generate signed certificate with the certificate authority - keytool -gencert -alias ca -ext san=dns:localhost,ip:127.0.0.1 \ - -validity 3650 -sigalg SHA512withRSA \ - -infile "$(CLIENTNAME).csr" -outfile "$(CLIENTNAME).crt" -rfc \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - # Import signed certificate into the truststore - keytool -import -trustcacerts -alias $(CLIENTNAME) -ext san=dns:localhost,ip:127.0.0.1 \ - -file "$(CLIENTNAME).crt" \ - -keystore $(TRUSTSTORE) -storepass $(PASSWORD) - # Export private certificate for importing into a browser - keytool -importkeystore -srcalias $(CLIENT_PRIVATE_KEY) -ext san=dns:localhost,ip:127.0.0.1 \ - -srckeystore $(TRUSTSTORE) -srcstorepass $(PASSWORD) \ - -destkeystore "$(CLIENTNAME).p12" -deststorepass $(PASSWORD) \ - -deststoretype PKCS12 - # Delete client private key as truststore should not contain any private keys - keytool -delete -alias $(CLIENT_PRIVATE_KEY) \ - -keystore $(TRUSTSTORE) -storepass $(PASSWORD) - -clean: - # Remove generated artifacts - 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-modules/spring-security-x509/keystore/keystore.jks b/spring-security-modules/spring-security-x509/keystore/keystore.jks deleted file mode 100644 index 044a820c39..0000000000 Binary files a/spring-security-modules/spring-security-x509/keystore/keystore.jks and /dev/null differ diff --git a/spring-security-modules/spring-security-x509/pom.xml b/spring-security-modules/spring-security-x509/pom.xml index a4ff908eed..d4132f058d 100644 --- a/spring-security-modules/spring-security-x509/pom.xml +++ b/spring-security-modules/spring-security-x509/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties b/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties index f293d6712d..0ba5fa1b8c 100644 --- a/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties +++ b/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties @@ -1,8 +1,8 @@ -server.ssl.key-store=../keystore/keystore.jks +server.ssl.key-store=../store/keystore.jks server.ssl.key-store-password=changeit server.ssl.key-alias=localhost server.ssl.key-password=changeit server.ssl.enabled=true server.port=8443 -security.user.name=Admin -security.user.password=admin \ No newline at end of file +spring.security.user.name=Admin +spring.security.user.password=admin \ No newline at end of file diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1c89f706ab --- /dev/null +++ b/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.security.x509.X509AuthenticationServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = X509AuthenticationServer.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 5c65dd3e8a..0000000000 --- a/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.security.x509.X509AuthenticationServer; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = X509AuthenticationServer.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java index 050423238e..18bbfba835 100644 --- a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java +++ b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java @@ -23,7 +23,11 @@ public class X509AuthenticationServer extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().authenticated().and().x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService()); + http.authorizeRequests().anyRequest().authenticated() + .and() + .x509() + .subjectPrincipalRegex("CN=(.*?)(?:,|$)") + .userDetailsService(userDetailsService()); } @Bean @@ -31,7 +35,7 @@ public class X509AuthenticationServer extends WebSecurityConfigurerAdapter { return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - if (username.equals("cid")) { + if (username.equals("Bob")) { return new User(username, "", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); } throw new UsernameNotFoundException("User not found!"); diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties index 174eba9f98..fc2fc89396 100644 --- a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties +++ b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties @@ -1,11 +1,11 @@ -server.ssl.key-store=../keystore/keystore.jks +server.ssl.key-store=../store/keystore.jks server.ssl.key-store-password=changeit server.ssl.key-alias=localhost server.ssl.key-password=changeit server.ssl.enabled=true server.port=8443 -security.user.name=Admin -security.user.password=admin -server.ssl.trust-store=../keystore/truststore.jks +spring.security.user.name=Admin +spring.security.user.password=admin +server.ssl.trust-store=../store/truststore.jks server.ssl.trust-store-password=changeit server.ssl.client-auth=need \ No newline at end of file diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/keystore.jks b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/keystore.jks deleted file mode 100644 index 044a820c39..0000000000 Binary files a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/keystore.jks and /dev/null differ diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1c89f706ab --- /dev/null +++ b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.security.x509.X509AuthenticationServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = X509AuthenticationServer.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 5c65dd3e8a..0000000000 --- a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.security.x509.X509AuthenticationServer; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = X509AuthenticationServer.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-security-x509/store/clientBob.p12 b/spring-security-modules/spring-security-x509/store/clientBob.p12 new file mode 100644 index 0000000000..b5de8ab129 Binary files /dev/null and b/spring-security-modules/spring-security-x509/store/clientBob.p12 differ diff --git a/spring-security-modules/spring-security-x509/store/keystore.jks b/spring-security-modules/spring-security-x509/store/keystore.jks new file mode 100644 index 0000000000..c317c1d5ba Binary files /dev/null and b/spring-security-modules/spring-security-x509/store/keystore.jks differ diff --git a/spring-security-modules/spring-security-x509/store/localhost.ext b/spring-security-modules/spring-security-x509/store/localhost.ext new file mode 100644 index 0000000000..45324cc75a --- /dev/null +++ b/spring-security-modules/spring-security-x509/store/localhost.ext @@ -0,0 +1,5 @@ +authorityKeyIdentifier=keyid,issuer +basicConstraints=CA:FALSE +subjectAltName = @alt_names +[alt_names] +DNS.1 = localhost diff --git a/spring-security-modules/spring-security-x509/store/rootCA.crt b/spring-security-modules/spring-security-x509/store/rootCA.crt new file mode 100644 index 0000000000..b2ab681744 --- /dev/null +++ b/spring-security-modules/spring-security-x509/store/rootCA.crt @@ -0,0 +1,30 @@ +-----BEGIN CERTIFICATE----- +MIIFDzCCAvegAwIBAgIUDmhG1yLlF83ydOWPit8/MYNbaC8wDQYJKoZIhvcNAQEL +BQAwFzEVMBMGA1UEAwwMQmFlbGR1bmcuY29tMB4XDTIwMDQyMjE1MzEyMFoXDTMw +MDQyMDE1MzEyMFowFzEVMBMGA1UEAwwMQmFlbGR1bmcuY29tMIICIjANBgkqhkiG +9w0BAQEFAAOCAg8AMIICCgKCAgEAmkOSeQRQBQdoJio7Odm19kKVm4Y1ju1zscGM +LBWQ4GU8d3Y5AiOVzHtYUbKyJvmmUSYOH/mYdQ8F5nKKaXhTz92LIMnSXnusAqdD +YSvKa+mBoMLsd4Gl9lljipTvRwkkPlPXGVBDEVzXPf32l+5YxpGZzyVyj0WYT1cP +sZyThbOwue4h6gwer4SZ0HNPSts8TG7oiA4UTZSN5hhhbJmRBc87Xz+hJOMayZp6 +HA3tGTlrTkP/Vc3nii/G9tBeydmTTKj+BGFQW4qzDG6nJVvYyB4iri4ActREREGD +ycPS7SVXqEcA4rvSMR7DYoHVLkOg0uiQDWtj4zYcN9qgWVjcnIlUSPxrCgdJbakl +lRzrVpbkdlOC3hFSytoOBmCPS56gJ5npeLFh6IoPPdoXJwIXIJ1twCWtKzvlvlzb +DkMDytRVk2LYjh7IvtAWPTz5QofRdd2fW6iAWPdWbwcnq1xjO5BT8uGj+zOiA19/ +T2YebwD+pLAUM2w0ykLm+bH+DiSRa76wpKxuo6sSUefkeEt8Avojwh8nNbEOvXhf +El4zyimwTlfUYnaKEllUjRWVPhQPGCeCBHe1ES8UFf8hqGS2LRjKAZK70OcFdLyd +18sas/EXkNbd+Mpgata/zO9Oy/3h+xY426T5bPAt+wU38yMUaE+z5BS84m2GOtuQ +nC3a/HcCAwEAAaNTMFEwHQYDVR0OBBYEFFyRjr/LWlOZHv7JU7kQ1g76nq4SMB8G +A1UdIwQYMBaAFFyRjr/LWlOZHv7JU7kQ1g76nq4SMA8GA1UdEwEB/wQFMAMBAf8w +DQYJKoZIhvcNAQELBQADggIBAJWjUR/HBw5f7ogfyCVK/5fJutOFIIHqzNhExvDe +5wu9msPRAj+5ruGHtMWwOKm5qT82gZKJnAVct8XZXTIHU8mKS5Lbk02hu3e2tR/0 +RCzH4TCCD3fDJaW/jAZyU3oPtvcCaSmPwibG7SvDXtUvSSwCW8Omg7WqhnSWGUOn +WH3105lw8UKRTg57CaNu0GunqO4r0GcrgVShNKjCvNv7nGcP3+KWouZekBdn/iY5 +3Q8llL8WUMOHRwH6Raa6CV+vckCthUSpJdBAgGN44QtkA0iL/afVuE7VuTqsnCBA +nbOz/ssZOP0TUVYwoRiDN50gJdB8IKMHZu9Px2m7fJuGgZ7QDe56+tePypgM9KDq +yx4MKMP3Qc5xLE4pGM9SI1sGo+waW0+gPShNECHY4z8fOHw5bn+J1mrEWQbHfMGg +Z/352qps5Hd6PljLAHmWAJL2nXS2zlXbccdYuv4ZtNIeDUT8eX/9NuJdXrITq9QQ +oSBmyzH1bUJi2/mULcFy0Ibcu+OY/r8t67NrGKwLPLyozScwnFQE9SZR9d2cu6sC +yxQtcd68vdvAIEDTk4DcSldeT44HIJ7RYQuBNZ5NU3SngMLDleec/3AZSUXTExFW +TrbMTb+djM+XcTkRyO0wO0MYpjKGqN3sAGfppx0G9kgmJ9HB38nZfvqj3G1L9YFQ +6kSA +-----END CERTIFICATE----- diff --git a/spring-security-modules/spring-security-x509/store/truststore.jks b/spring-security-modules/spring-security-x509/store/truststore.jks new file mode 100644 index 0000000000..1d0d200580 Binary files /dev/null and b/spring-security-modules/spring-security-x509/store/truststore.jks differ diff --git a/spring-security-sso/spring-security-sso-auth-server/README.md b/spring-security-sso/spring-security-sso-auth-server/README.md deleted file mode 100644 index 845fb50a93..0000000000 --- a/spring-security-sso/spring-security-sso-auth-server/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles - -- [Simple Single Sign-On with Spring Security OAuth2](https://www.baeldung.com/sso-spring-security-oauth2) diff --git a/spring-security-sso/spring-security-sso-ui-2/README.md b/spring-security-sso/spring-security-sso-ui-2/README.md deleted file mode 100644 index aed217bdf0..0000000000 --- a/spring-security-sso/spring-security-sso-ui-2/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Simple Single Sign-On with Spring Security OAuth2](https://www.baeldung.com/sso-spring-security-oauth2) diff --git a/spring-security-sso/spring-security-sso-ui/README.md b/spring-security-sso/spring-security-sso-ui/README.md deleted file mode 100644 index 845fb50a93..0000000000 --- a/spring-security-sso/spring-security-sso-ui/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles - -- [Simple Single Sign-On with Spring Security OAuth2](https://www.baeldung.com/sso-spring-security-oauth2) diff --git a/spring-session/pom.xml b/spring-session/pom.xml index 579d2327e8..42a414afdc 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-session 1.0.0-SNAPSHOT spring-session diff --git a/spring-session/spring-session-jdbc/src/test/java/com/baeldung/SpringContextTest.java b/spring-session/spring-session-jdbc/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8f6c2f2889 --- /dev/null +++ b/spring-session/spring-session-jdbc/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.springsessionjdbc.SpringSessionJdbcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSessionJdbcApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index b69855ba38..0000000000 --- a/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.springsessionjdbc.SpringSessionJdbcApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringSessionJdbcApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-session/spring-session-mongodb/pom.xml b/spring-session/spring-session-mongodb/pom.xml index 00ffec93c0..10d4eb595e 100644 --- a/spring-session/spring-session-mongodb/pom.xml +++ b/spring-session/spring-session-mongodb/pom.xml @@ -25,13 +25,11 @@ org.springframework.session spring-session-data-mongodb - ${spring-session-data-mongodb.version} org.springframework.boot spring-boot-starter-data-mongodb - ${spring-boot-starter-data-mongodb.version} @@ -56,9 +54,4 @@ - - 2.1.3.RELEASE - 2.1.5.RELEASE - - \ No newline at end of file diff --git a/spring-session/spring-session-mongodb/src/test/java/com/baeldung/SpringContextTest.java b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..babcdb2ccf --- /dev/null +++ b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import com.baeldung.springsessionmongodb.SpringSessionMongoDBApplication; +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(classes = SpringSessionMongoDBApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-mongodb/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java index de41019e49..7233d07536 100644 --- a/spring-session/spring-session-mongodb/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java +++ b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; -import org.springframework.session.data.mongo.MongoOperationsSessionRepository; +import org.springframework.session.data.mongo.MongoIndexedSessionRepository; import org.springframework.test.context.junit4.SpringRunner; import java.util.Base64; @@ -24,7 +24,7 @@ public class SpringSessionMongoDBIntegrationTest { private int port; @Autowired - private MongoOperationsSessionRepository repository; + private MongoIndexedSessionRepository repository; private TestRestTemplate restTemplate = new TestRestTemplate(); diff --git a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index cc935b8cfb..0000000000 --- a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import com.baeldung.springsessionmongodb.SpringSessionMongoDBApplication; -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(classes = SpringSessionMongoDBApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-session/spring-session-redis/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-session/spring-session-redis/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..2e33255e01 --- /dev/null +++ b/spring-session/spring-session-redis/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,21 @@ +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; + +import com.baeldung.spring.session.SessionWebApplication; + +/** + * This live test requires: + * redis instance running on the environment + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SessionWebApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index 3a4f14e9e6..0000000000 --- a/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.session.SessionWebApplication; - -/** - * This live test requires: - * redis instance running on the environment - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SessionWebApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-shell/src/main/java/org/baeldung/shell/Main.java b/spring-shell/src/main/java/com/baeldung/shell/Main.java similarity index 87% rename from spring-shell/src/main/java/org/baeldung/shell/Main.java rename to spring-shell/src/main/java/com/baeldung/shell/Main.java index 3d9f7a5860..97871394f7 100644 --- a/spring-shell/src/main/java/org/baeldung/shell/Main.java +++ b/spring-shell/src/main/java/com/baeldung/shell/Main.java @@ -1,4 +1,4 @@ -package org.baeldung.shell; +package com.baeldung.shell; import java.io.IOException; import org.springframework.shell.Bootstrap; diff --git a/spring-shell/src/main/java/org/baeldung/shell/simple/SimpleBannerProvider.java b/spring-shell/src/main/java/com/baeldung/shell/simple/SimpleBannerProvider.java similarity index 96% rename from spring-shell/src/main/java/org/baeldung/shell/simple/SimpleBannerProvider.java rename to spring-shell/src/main/java/com/baeldung/shell/simple/SimpleBannerProvider.java index df7a48cd32..dbfde76f8e 100644 --- a/spring-shell/src/main/java/org/baeldung/shell/simple/SimpleBannerProvider.java +++ b/spring-shell/src/main/java/com/baeldung/shell/simple/SimpleBannerProvider.java @@ -1,4 +1,4 @@ -package org.baeldung.shell.simple; +package com.baeldung.shell.simple; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; diff --git a/spring-shell/src/main/java/org/baeldung/shell/simple/SimpleCLI.java b/spring-shell/src/main/java/com/baeldung/shell/simple/SimpleCLI.java similarity index 98% rename from spring-shell/src/main/java/org/baeldung/shell/simple/SimpleCLI.java rename to spring-shell/src/main/java/com/baeldung/shell/simple/SimpleCLI.java index f73d9bda00..d8a0aef838 100644 --- a/spring-shell/src/main/java/org/baeldung/shell/simple/SimpleCLI.java +++ b/spring-shell/src/main/java/com/baeldung/shell/simple/SimpleCLI.java @@ -1,4 +1,4 @@ -package org.baeldung.shell.simple; +package com.baeldung.shell.simple; import java.io.BufferedReader; import java.io.FileNotFoundException; diff --git a/spring-shell/src/main/java/org/baeldung/shell/simple/SimpleHistoryFileNameProvider.java b/spring-shell/src/main/java/com/baeldung/shell/simple/SimpleHistoryFileNameProvider.java similarity index 93% rename from spring-shell/src/main/java/org/baeldung/shell/simple/SimpleHistoryFileNameProvider.java rename to spring-shell/src/main/java/com/baeldung/shell/simple/SimpleHistoryFileNameProvider.java index cef53adc69..5936006f11 100644 --- a/spring-shell/src/main/java/org/baeldung/shell/simple/SimpleHistoryFileNameProvider.java +++ b/spring-shell/src/main/java/com/baeldung/shell/simple/SimpleHistoryFileNameProvider.java @@ -1,4 +1,4 @@ -package org.baeldung.shell.simple; +package com.baeldung.shell.simple; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; diff --git a/spring-shell/src/main/java/org/baeldung/shell/simple/SimplePromptProvider.java b/spring-shell/src/main/java/com/baeldung/shell/simple/SimplePromptProvider.java similarity index 93% rename from spring-shell/src/main/java/org/baeldung/shell/simple/SimplePromptProvider.java rename to spring-shell/src/main/java/com/baeldung/shell/simple/SimplePromptProvider.java index 9a84954e05..a795d19eed 100644 --- a/spring-shell/src/main/java/org/baeldung/shell/simple/SimplePromptProvider.java +++ b/spring-shell/src/main/java/com/baeldung/shell/simple/SimplePromptProvider.java @@ -1,4 +1,4 @@ -package org.baeldung.shell.simple; +package com.baeldung.shell.simple; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; diff --git a/spring-shell/src/main/java/org/baeldung/shell/simple/SimpleURLConverter.java b/spring-shell/src/main/java/com/baeldung/shell/simple/SimpleURLConverter.java similarity index 96% rename from spring-shell/src/main/java/org/baeldung/shell/simple/SimpleURLConverter.java rename to spring-shell/src/main/java/com/baeldung/shell/simple/SimpleURLConverter.java index 4824cfbf05..7615f31ace 100644 --- a/spring-shell/src/main/java/org/baeldung/shell/simple/SimpleURLConverter.java +++ b/spring-shell/src/main/java/com/baeldung/shell/simple/SimpleURLConverter.java @@ -1,4 +1,4 @@ -package org.baeldung.shell.simple; +package com.baeldung.shell.simple; import java.net.MalformedURLException; import java.net.URL; diff --git a/spring-shell/src/main/resources/META-INF/spring/spring-shell-plugin.xml b/spring-shell/src/main/resources/META-INF/spring/spring-shell-plugin.xml index 1b97ab3b59..3ff60f3c08 100644 --- a/spring-shell/src/main/resources/META-INF/spring/spring-shell-plugin.xml +++ b/spring-shell/src/main/resources/META-INF/spring/spring-shell-plugin.xml @@ -8,6 +8,6 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> - + \ No newline at end of file diff --git a/spring-shell/src/test/java/org/baeldung/shell/simple/SimpleCLIIntegrationTest.java b/spring-shell/src/test/java/com/baeldung/shell/simple/SimpleCLIIntegrationTest.java similarity index 98% rename from spring-shell/src/test/java/org/baeldung/shell/simple/SimpleCLIIntegrationTest.java rename to spring-shell/src/test/java/com/baeldung/shell/simple/SimpleCLIIntegrationTest.java index 3ec756e238..53627700c5 100644 --- a/spring-shell/src/test/java/org/baeldung/shell/simple/SimpleCLIIntegrationTest.java +++ b/spring-shell/src/test/java/com/baeldung/shell/simple/SimpleCLIIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.shell.simple; +package com.baeldung.shell.simple; import org.junit.AfterClass; import org.junit.Assert; diff --git a/spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java b/spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8dc2455e63 --- /dev/null +++ b/spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.session.SleuthWebApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SleuthWebApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java b/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index ff22398ca4..0000000000 --- a/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.session.SleuthWebApp; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SleuthWebApp.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index 9403b70636..d0987329c0 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -58,6 +58,28 @@ + + + org.jvnet.jaxb2.maven2 + maven-jaxb2-plugin + 0.14.0 + + + + generate + + + + + WSDL + ${project.basedir}/src/main/java + com.baeldung.springsoap.client.gen + ${project.basedir}/src/main/resources + + countries.wsdl + + + diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java new file mode 100644 index 0000000000..e0b9172ece --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java @@ -0,0 +1,26 @@ +package com.baeldung.springsoap.client; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ws.client.core.support.WebServiceGatewaySupport; + +import com.baeldung.springsoap.client.gen.GetCountryRequest; +import com.baeldung.springsoap.client.gen.GetCountryResponse; + +public class CountryClient extends WebServiceGatewaySupport { + + private static final Logger logger = LoggerFactory.getLogger(CountryClient.class); + + public GetCountryResponse getCountry(String country) { + + GetCountryRequest request = new GetCountryRequest(); + request.setName(country); + + logger.info("Requesting information for " + country); + + GetCountryResponse response = (GetCountryResponse) getWebServiceTemplate().marshalSendAndReceive(request); + + return response; + } + +} \ No newline at end of file diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java new file mode 100644 index 0000000000..8dabdbc00d --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java @@ -0,0 +1,25 @@ +package com.baeldung.springsoap.client; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; + +@Configuration +public class CountryClientConfig { + + @Bean + public Jaxb2Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + marshaller.setContextPath("com.baeldung.springsoap.client.gen"); + return marshaller; + } + + @Bean + public CountryClient countryClient(Jaxb2Marshaller marshaller) { + CountryClient client = new CountryClient(); + client.setDefaultUri("http://localhost:8080/ws"); + client.setMarshaller(marshaller); + client.setUnmarshaller(marshaller); + return client; + } +} \ No newline at end of file diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java new file mode 100644 index 0000000000..e17dce55f9 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java @@ -0,0 +1,146 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for country complex type. + * + *

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

+ * <complexType name="country">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="population" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ *         <element name="capital" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="currency" type="{http://www.baeldung.com/springsoap/gen}currency"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "country", propOrder = { + "name", + "population", + "capital", + "currency" +}) +public class Country { + + @XmlElement(required = true) + protected String name; + protected int population; + @XmlElement(required = true) + protected String capital; + @XmlElement(required = true) + @XmlSchemaType(name = "string") + protected Currency currency; + + /** + * 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 population property. + * + */ + public int getPopulation() { + return population; + } + + /** + * Sets the value of the population property. + * + */ + public void setPopulation(int value) { + this.population = value; + } + + /** + * Gets the value of the capital property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCapital() { + return capital; + } + + /** + * Sets the value of the capital property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCapital(String value) { + this.capital = value; + } + + /** + * Gets the value of the currency property. + * + * @return + * possible object is + * {@link Currency } + * + */ + public Currency getCurrency() { + return currency; + } + + /** + * Sets the value of the currency property. + * + * @param value + * allowed object is + * {@link Currency } + * + */ + public void setCurrency(Currency value) { + this.currency = value; + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java new file mode 100644 index 0000000000..12fdef58c2 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java @@ -0,0 +1,47 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for currency. + * + *

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

+ *

+ * <simpleType name="currency">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="GBP"/>
+ *     <enumeration value="EUR"/>
+ *     <enumeration value="PLN"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "currency") +@XmlEnum +public enum Currency { + + GBP, + EUR, + PLN; + + public String value() { + return name(); + } + + public static Currency fromValue(String v) { + return valueOf(v); + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java new file mode 100644 index 0000000000..5739ee3b96 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java @@ -0,0 +1,71 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +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 anonymous complex type. + * + *

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

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "name" +}) +@XmlRootElement(name = "getCountryRequest") +public class GetCountryRequest { + + @XmlElement(required = true) + protected String name; + + /** + * 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/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java new file mode 100644 index 0000000000..ba1ab56cf8 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java @@ -0,0 +1,71 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +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 anonymous complex type. + * + *

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

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="country" type="{http://www.baeldung.com/springsoap/gen}country"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "country" +}) +@XmlRootElement(name = "getCountryResponse") +public class GetCountryResponse { + + @XmlElement(required = true) + protected Country country; + + /** + * Gets the value of the country property. + * + * @return + * possible object is + * {@link Country } + * + */ + public Country getCountry() { + return country; + } + + /** + * Sets the value of the country property. + * + * @param value + * allowed object is + * {@link Country } + * + */ + public void setCountry(Country value) { + this.country = value; + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java new file mode 100644 index 0000000000..88b27245be --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java @@ -0,0 +1,63 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.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.springsoap.client.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.springsoap.client.gen + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link GetCountryRequest } + * + */ + public GetCountryRequest createGetCountryRequest() { + return new GetCountryRequest(); + } + + /** + * Create an instance of {@link GetCountryResponse } + * + */ + public GetCountryResponse createGetCountryResponse() { + return new GetCountryResponse(); + } + + /** + * Create an instance of {@link Country } + * + */ + public Country createCountry() { + return new Country(); + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java new file mode 100644 index 0000000000..eefed169a8 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java @@ -0,0 +1,9 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + +@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/springsoap/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package com.baeldung.springsoap.client.gen; diff --git a/spring-soap/src/main/resources/countries.wsdl b/spring-soap/src/main/resources/countries.wsdl new file mode 100644 index 0000000000..2a2eaf05bb --- /dev/null +++ b/spring-soap/src/main/resources/countries.wsdl @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java b/spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java new file mode 100644 index 0000000000..63dbe2a5cf --- /dev/null +++ b/spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java @@ -0,0 +1,36 @@ +package com.baeldung.springsoap.client; + +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; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.springsoap.client.gen.Currency; +import com.baeldung.springsoap.client.gen.GetCountryResponse; + +//Ensure that the server - com.baeldung.springsoap.Application - is running before executing this test +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CountryClientConfig.class, loader = AnnotationConfigContextLoader.class) +public class CountryClientLiveTest { + + @Autowired + CountryClient client; + + @Test + public void givenCountryService_whenCountryPoland_thenCapitalIsWarsaw() { + GetCountryResponse response = client.getCountry("Poland"); + assertEquals("Warsaw", response.getCountry() + .getCapital()); + } + + @Test + public void givenCountryService_whenCountrySpain_thenCurrencyEUR() { + GetCountryResponse response = client.getCountry("Spain"); + assertEquals(Currency.EUR, response.getCountry() + .getCurrency()); + } +} diff --git a/spring-social-login/src/main/java/com/baeldung/config/Application.java b/spring-social-login/src/main/java/com/baeldung/config/Application.java new file mode 100644 index 0000000000..5d083d2d47 --- /dev/null +++ b/spring-social-login/src/main/java/com/baeldung/config/Application.java @@ -0,0 +1,18 @@ +package com.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +@EnableJpaRepositories("com.baeldung.persistence.dao") +@EntityScan("com.baeldung.persistence.model") +public class Application extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java b/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..3d3081fef9 --- /dev/null +++ b/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java @@ -0,0 +1,61 @@ +package com.baeldung.config; + +import com.baeldung.security.FacebookSignInAdapter; +import com.baeldung.security.FacebookConnectionSignup; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.social.connect.ConnectionFactoryLocator; +import org.springframework.social.connect.UsersConnectionRepository; +import org.springframework.social.connect.mem.InMemoryUsersConnectionRepository; +import org.springframework.social.connect.web.ProviderSignInController; + +@Configuration +@EnableWebSecurity +@ComponentScan(basePackages = { "com.baeldung.security" }) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private ConnectionFactoryLocator connectionFactoryLocator; + + @Autowired + private UsersConnectionRepository usersConnectionRepository; + + @Autowired + private FacebookConnectionSignup facebookConnectionSignup; + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/login*","/signin/**","/signup/**").permitAll() + .anyRequest().authenticated() + .and() + .formLogin().loginPage("/login").permitAll() + .and() + .logout(); + } // @formatter:on + + @Bean + // @Primary + public ProviderSignInController providerSignInController() { + ((InMemoryUsersConnectionRepository) usersConnectionRepository).setConnectionSignUp(facebookConnectionSignup); + return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new FacebookSignInAdapter()); + } +} \ No newline at end of file diff --git a/spring-social-login/src/main/java/com/baeldung/config/WebConfig.java b/spring-social-login/src/main/java/com/baeldung/config/WebConfig.java new file mode 100644 index 0000000000..d178cc28a6 --- /dev/null +++ b/spring-social-login/src/main/java/com/baeldung/config/WebConfig.java @@ -0,0 +1,39 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class WebConfig extends WebMvcConfigurerAdapter { + + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + registry.addViewController("/login"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + +} \ No newline at end of file diff --git a/spring-social-login/src/main/java/com/baeldung/persistence/dao/UserRepository.java b/spring-social-login/src/main/java/com/baeldung/persistence/dao/UserRepository.java new file mode 100644 index 0000000000..aeb443dd06 --- /dev/null +++ b/spring-social-login/src/main/java/com/baeldung/persistence/dao/UserRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + + User findByUsername(final String username); + +} diff --git a/spring-social-login/src/main/java/com/baeldung/persistence/model/User.java b/spring-social-login/src/main/java/com/baeldung/persistence/model/User.java new file mode 100644 index 0000000000..ce1774ca2c --- /dev/null +++ b/spring-social-login/src/main/java/com/baeldung/persistence/model/User.java @@ -0,0 +1,55 @@ +package com.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String username; + + private String password; + + public User() { + super(); + } + + 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 String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append("]"); + return builder.toString(); + } + +} diff --git a/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java b/spring-social-login/src/main/java/com/baeldung/security/FacebookConnectionSignup.java similarity index 85% rename from spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java rename to spring-social-login/src/main/java/com/baeldung/security/FacebookConnectionSignup.java index 6a9e30d7d8..e0a9fdc2e7 100644 --- a/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java +++ b/spring-social-login/src/main/java/com/baeldung/security/FacebookConnectionSignup.java @@ -1,9 +1,9 @@ -package org.baeldung.security; +package com.baeldung.security; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import org.baeldung.persistence.dao.UserRepository; -import org.baeldung.persistence.model.User; +import com.baeldung.persistence.dao.UserRepository; +import com.baeldung.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.social.connect.Connection; import org.springframework.social.connect.ConnectionSignUp; diff --git a/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java b/spring-social-login/src/main/java/com/baeldung/security/FacebookSignInAdapter.java similarity index 96% rename from spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java rename to spring-social-login/src/main/java/com/baeldung/security/FacebookSignInAdapter.java index b861609a01..3050941ffa 100644 --- a/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java +++ b/spring-social-login/src/main/java/com/baeldung/security/FacebookSignInAdapter.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.util.Arrays; diff --git a/spring-social-login/src/main/java/com/baeldung/security/MyUserDetailsService.java b/spring-social-login/src/main/java/com/baeldung/security/MyUserDetailsService.java new file mode 100644 index 0000000000..126f02e74a --- /dev/null +++ b/spring-social-login/src/main/java/com/baeldung/security/MyUserDetailsService.java @@ -0,0 +1,34 @@ +package com.baeldung.security; + +import java.util.Arrays; + +import com.baeldung.persistence.dao.UserRepository; +import com.baeldung.persistence.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + private UserRepository userRepository; + + public MyUserDetailsService() { + super(); + } + + // API + + @Override + public UserDetails loadUserByUsername(final String username) { + final User user = userRepository.findByUsername(username); + if (user == null) { + throw new UsernameNotFoundException(username); + } + return new org.springframework.security.core.userdetails.User(username, user.getPassword(), true, true, true, true, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); + } +} diff --git a/spring-social-login/src/main/java/org/baeldung/config/Application.java b/spring-social-login/src/main/java/org/baeldung/config/Application.java deleted file mode 100644 index cf6251a51e..0000000000 --- a/spring-social-login/src/main/java/org/baeldung/config/Application.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.boot.web.support.SpringBootServletInitializer; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -@SpringBootApplication -@EnableJpaRepositories("org.baeldung.persistence.dao") -@EntityScan("org.baeldung.persistence.model") -public class Application extends SpringBootServletInitializer { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} \ No newline at end of file diff --git a/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java deleted file mode 100644 index 8e439653a9..0000000000 --- a/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.baeldung.config; - -import org.baeldung.security.FacebookSignInAdapter; -import org.baeldung.security.FacebookConnectionSignup; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.social.connect.ConnectionFactoryLocator; -import org.springframework.social.connect.UsersConnectionRepository; -import org.springframework.social.connect.mem.InMemoryUsersConnectionRepository; -import org.springframework.social.connect.web.ProviderSignInController; - -@Configuration -@EnableWebSecurity -@ComponentScan(basePackages = { "org.baeldung.security" }) -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private UserDetailsService userDetailsService; - - @Autowired - private ConnectionFactoryLocator connectionFactoryLocator; - - @Autowired - private UsersConnectionRepository usersConnectionRepository; - - @Autowired - private FacebookConnectionSignup facebookConnectionSignup; - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService); - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http - .csrf().disable() - .authorizeRequests() - .antMatchers("/login*","/signin/**","/signup/**").permitAll() - .anyRequest().authenticated() - .and() - .formLogin().loginPage("/login").permitAll() - .and() - .logout(); - } // @formatter:on - - @Bean - // @Primary - public ProviderSignInController providerSignInController() { - ((InMemoryUsersConnectionRepository) usersConnectionRepository).setConnectionSignUp(facebookConnectionSignup); - return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new FacebookSignInAdapter()); - } -} \ No newline at end of file diff --git a/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java b/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java deleted file mode 100644 index 8cfcd6cb41..0000000000 --- a/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@EnableWebMvc -public class WebConfig extends WebMvcConfigurerAdapter { - - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Override - public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/").setViewName("forward:/index"); - registry.addViewController("/index"); - registry.addViewController("/login"); - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } - -} \ No newline at end of file diff --git a/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java deleted file mode 100644 index 679dd6c363..0000000000 --- a/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.User; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface UserRepository extends JpaRepository { - - User findByUsername(final String username); - -} diff --git a/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java b/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java deleted file mode 100644 index a4cffc27d0..0000000000 --- a/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.baeldung.persistence.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class User { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Column(nullable = false, unique = true) - private String username; - - private String password; - - public User() { - super(); - } - - 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 String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append("]"); - return builder.toString(); - } - -} diff --git a/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java deleted file mode 100644 index 5d0d5d793a..0000000000 --- a/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.baeldung.security; - -import java.util.Arrays; - -import org.baeldung.persistence.dao.UserRepository; -import org.baeldung.persistence.model.User; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; - -@Service -public class MyUserDetailsService implements UserDetailsService { - - @Autowired - private UserRepository userRepository; - - public MyUserDetailsService() { - super(); - } - - // API - - @Override - public UserDetails loadUserByUsername(final String username) { - final User user = userRepository.findByUsername(username); - if (user == null) { - throw new UsernameNotFoundException(username); - } - return new org.springframework.security.core.userdetails.User(username, user.getPassword(), true, true, true, true, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); - } -} diff --git a/spring-social-login/src/test/java/com/baeldung/SpringContextTest.java b/spring-social-login/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1d9711b5a4 --- /dev/null +++ b/spring-social-login/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import com.baeldung.config.Application; +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.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java b/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index cfd8759c52..0000000000 --- a/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.baeldung.config.Application; -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.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class SpringContextTest { - - @Test - public void whenLoadApplication_thenSuccess() { - - } -} diff --git a/spring-spel/src/test/java/com/baeldung/SpringContextTest.java b/spring-spel/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..338b8b1e68 --- /dev/null +++ b/spring-spel/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung; + +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(locations = {"classpath:applicationContext.xml"}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-spel/src/test/java/org/baeldung/SpringContextTest.java b/spring-spel/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e25c1bf8e4..0000000000 --- a/spring-spel/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung; - -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(locations = {"classpath:applicationContext.xml"}) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-state-machine/src/test/java/com/baeldung/SpringContextTest.java b/spring-state-machine/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..407cd8ebb0 --- /dev/null +++ b/spring-state-machine/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,23 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.statemachine.config.ForkJoinStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.HierarchicalStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.JunctionStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.SimpleEnumStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SimpleStateMachineConfiguration.class, SimpleEnumStateMachineConfiguration.class, + JunctionStateMachineConfiguration.class, HierarchicalStateMachineConfiguration.class, + ForkJoinStateMachineConfiguration.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java b/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 1e847c0d65..0000000000 --- a/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.spring.statemachine.config.ForkJoinStateMachineConfiguration; -import com.baeldung.spring.statemachine.config.HierarchicalStateMachineConfiguration; -import com.baeldung.spring.statemachine.config.JunctionStateMachineConfiguration; -import com.baeldung.spring.statemachine.config.SimpleEnumStateMachineConfiguration; -import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { SimpleStateMachineConfiguration.class, SimpleEnumStateMachineConfiguration.class, - JunctionStateMachineConfiguration.class, HierarchicalStateMachineConfiguration.class, - ForkJoinStateMachineConfiguration.class }) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-static-resources/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-static-resources/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java new file mode 100644 index 0000000000..d6c54f8099 --- /dev/null +++ b/spring-static-resources/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -0,0 +1,61 @@ +package com.baeldung.security; + +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.DefaultRedirectStrategy; +import org.springframework.security.web.RedirectStrategy; +import org.springframework.security.web.WebAttributes; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); + + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { + handle(request, response, authentication); + HttpSession session = request.getSession(false); + if (session != null) { + session.setMaxInactiveInterval(30); + } + clearAuthenticationAttributes(request); + } + + protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { + String targetUrl = determineTargetUrl(authentication); + + if (response.isCommitted()) { + logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); + return; + } + + redirectStrategy.sendRedirect(request, response, targetUrl); + } + + protected String determineTargetUrl(Authentication authentication) { + + return "/home.html"; + + } + + protected void clearAuthenticationAttributes(HttpServletRequest request) { + HttpSession session = request.getSession(false); + if (session == null) { + return; + } + session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); + } + + public void setRedirectStrategy(RedirectStrategy redirectStrategy) { + this.redirectStrategy = redirectStrategy; + } + + protected RedirectStrategy getRedirectStrategy() { + return redirectStrategy; + } +} \ No newline at end of file diff --git a/spring-static-resources/src/main/java/com/baeldung/spring/AppConfig.java b/spring-static-resources/src/main/java/com/baeldung/spring/AppConfig.java new file mode 100644 index 0000000000..97e7cf96fc --- /dev/null +++ b/spring-static-resources/src/main/java/com/baeldung/spring/AppConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; + +@Configuration +@ComponentScan(basePackages = { "com.baeldung.persistence.service", "com.baeldung.persistence.dao" }) +@Import({ MvcConfig.class, SecSecurityConfig.class }) +@PropertySource("classpath:application.properties") +public class AppConfig { + + @Bean + public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } +} diff --git a/spring-static-resources/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-static-resources/src/main/java/com/baeldung/spring/MvcConfig.java new file mode 100644 index 0000000000..f23fe14fb8 --- /dev/null +++ b/spring-static-resources/src/main/java/com/baeldung/spring/MvcConfig.java @@ -0,0 +1,104 @@ +package com.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.EncodedResourceResolver; +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 = { "com.baeldung.web.controller", "com.baeldung.persistence.service", "com.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 EncodedResourceResolver()).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 EncodedResourceResolver()); + } + // 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/spring-static-resources/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/spring-static-resources/src/main/java/com/baeldung/spring/SecSecurityConfig.java new file mode 100644 index 0000000000..3e630b8729 --- /dev/null +++ b/spring-static-resources/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +@Configuration +@ImportResource({ "classpath:webSecurityConfig.xml" }) +public class SecSecurityConfig { + + public SecSecurityConfig() { + super(); + } + +} diff --git a/spring-static-resources/src/main/java/com/baeldung/web/controller/HomeController.java b/spring-static-resources/src/main/java/com/baeldung/web/controller/HomeController.java new file mode 100644 index 0000000000..dd58c7c2b6 --- /dev/null +++ b/spring-static-resources/src/main/java/com/baeldung/web/controller/HomeController.java @@ -0,0 +1,32 @@ +package com.baeldung.web.controller; + +import java.io.IOException; +import java.text.DateFormat; +import java.util.Date; +import java.util.Locale; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +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.context.request.WebRequest; + +@Controller +public class HomeController { + + @Autowired + Environment env; + + @RequestMapping(value = "/home", method = RequestMethod.GET) + public String showHome(WebRequest request, Model model, Locale locale) throws IOException { + + Date date = new Date(); + DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); + + String formattedDate = dateFormat.format(date); + model.addAttribute("serverTime", formattedDate); + return "home"; + } + +} diff --git a/spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java deleted file mode 100644 index 316642ab6f..0000000000 --- a/spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.baeldung.security; - -import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.core.Authentication; -import org.springframework.security.web.DefaultRedirectStrategy; -import org.springframework.security.web.RedirectStrategy; -import org.springframework.security.web.WebAttributes; -import org.springframework.security.web.authentication.AuthenticationSuccessHandler; - -public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { - private final Logger logger = LoggerFactory.getLogger(getClass()); - - private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - - public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { - handle(request, response, authentication); - HttpSession session = request.getSession(false); - if (session != null) { - session.setMaxInactiveInterval(30); - } - clearAuthenticationAttributes(request); - } - - protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { - String targetUrl = determineTargetUrl(authentication); - - if (response.isCommitted()) { - logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); - return; - } - - redirectStrategy.sendRedirect(request, response, targetUrl); - } - - protected String determineTargetUrl(Authentication authentication) { - - return "/home.html"; - - } - - protected void clearAuthenticationAttributes(HttpServletRequest request) { - HttpSession session = request.getSession(false); - if (session == null) { - return; - } - session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); - } - - public void setRedirectStrategy(RedirectStrategy redirectStrategy) { - this.redirectStrategy = redirectStrategy; - } - - protected RedirectStrategy getRedirectStrategy() { - return redirectStrategy; - } -} \ No newline at end of file diff --git a/spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java deleted file mode 100644 index c379d20047..0000000000 --- a/spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.PropertySource; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; - -@Configuration -@ComponentScan(basePackages = { "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) -@Import({ MvcConfig.class, SecSecurityConfig.class }) -@PropertySource("classpath:application.properties") -public class AppConfig { - - @Bean - public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } -} 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 deleted file mode 100644 index 7bd03617be..0000000000 --- a/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java +++ /dev/null @@ -1,104 +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.WebMvcConfigurer; -import org.springframework.web.servlet.i18n.CookieLocaleResolver; -import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; -import org.springframework.web.servlet.resource.EncodedResourceResolver; -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 EncodedResourceResolver()).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 EncodedResourceResolver()); - } - // 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/spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java deleted file mode 100644 index 4da114c78b..0000000000 --- a/spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; - -@Configuration -@ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecSecurityConfig { - - public SecSecurityConfig() { - super(); - } - -} diff --git a/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 deleted file mode 100644 index 44645a1471..0000000000 --- a/spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.baeldung.web.controller; - -import java.io.IOException; -import java.text.DateFormat; -import java.util.Date; -import java.util.Locale; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -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.context.request.WebRequest; - -@Controller -public class HomeController { - - @Autowired - Environment env; - - @RequestMapping(value = "/home", method = RequestMethod.GET) - public String showHome(WebRequest request, Model model, Locale locale) throws IOException { - - Date date = new Date(); - DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); - - String formattedDate = dateFormat.format(date); - model.addAttribute("serverTime", formattedDate); - return "home"; - } - -} diff --git a/spring-static-resources/src/main/resources/webSecurityConfig.xml b/spring-static-resources/src/main/resources/webSecurityConfig.xml index ea64ad5aea..2278cb6138 100644 --- a/spring-static-resources/src/main/resources/webSecurityConfig.xml +++ b/spring-static-resources/src/main/resources/webSecurityConfig.xml @@ -23,7 +23,7 @@ - + diff --git a/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java index 0dcbba3221..153b290de7 100644 --- a/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ package com.baeldung; -import org.baeldung.spring.SecSecurityConfig; +import com.baeldung.spring.SecSecurityConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-swagger-codegen/pom.xml b/spring-swagger-codegen/pom.xml index dee9415679..39d8902956 100644 --- a/spring-swagger-codegen/pom.xml +++ b/spring-swagger-codegen/pom.xml @@ -15,6 +15,7 @@ spring-swagger-codegen-api-client + spring-openapi-generator-api-client spring-swagger-codegen-app diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator-ignore b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator/VERSION b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator/VERSION new file mode 100644 index 0000000000..ec87108d82 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.2.3 \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/.travis.yml b/spring-swagger-codegen/spring-openapi-generator-api-client/.travis.yml new file mode 100644 index 0000000000..e3bdf2af1b --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/README.md b/spring-swagger-codegen/spring-openapi-generator-api-client/README.md new file mode 100644 index 0000000000..01fd596268 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/README.md @@ -0,0 +1,174 @@ +# spring-openapi-generator-api-client + +Swagger Petstore + +- API version: 1.0.3 + +- Build date: 2020-03-15T06:14:01.568992-05:00[America/Chicago] + +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. + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: + +1. Java 1.8+ +2. Maven/Gradle + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + com.baeldung + spring-openapi-generator-api-client + 0.0.1-SNAPSHOT + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "com.baeldung:spring-openapi-generator-api-client:0.0.1-SNAPSHOT" +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +- `target/spring-openapi-generator-api-client-0.0.1-SNAPSHOT.jar` +- `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import com.baeldung.petstore.client.invoker.*; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.model.*; +import com.baeldung.petstore.client.api.PetApi; + +public class PetApiExample { + + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [Category](docs/Category.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### petstore_auth + + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: https://petstore.swagger.io/oauth/authorize +- **Scopes**: + - read:pets: read your pets + - write:pets: modify pets in your account + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + +apiteam@swagger.io + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/build.gradle b/spring-swagger-codegen/spring-openapi-generator-api-client/build.gradle new file mode 100644 index 0000000000..d86deb75b8 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/build.gradle @@ -0,0 +1,120 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'com.baeldung' +version = '0.0.1-SNAPSHOT' + +buildscript { + repositories { + maven { url "https://repo1.maven.org/maven2" } + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + install { + repositories.mavenInstaller { + pom.artifactId = 'spring-openapi-generator-api-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.22" + jackson_version = "2.10.1" + jackson_databind_version = "2.10.1" + jackson_databind_nullable_version = "0.2.1" + spring_web_version = "4.3.9.RELEASE" + jodatime_version = "2.9.9" + junit_version = "4.13" + jackson_threeten_version = "2.9.10" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.google.code.findbugs:jsr305:3.0.2" + compile "org.springframework:spring-web:$spring_web_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" + compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" + compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_threeten_version" + testCompile "junit:junit:$junit_version" +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/build.sbt b/spring-swagger-codegen/spring-openapi-generator-api-client/build.sbt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Category.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Category.md new file mode 100644 index 0000000000..848fb61818 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Category.md @@ -0,0 +1,13 @@ + + +# Category + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/ModelApiResponse.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/ModelApiResponse.md new file mode 100644 index 0000000000..14fb7f1ed2 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/ModelApiResponse.md @@ -0,0 +1,14 @@ + + +# ModelApiResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Order.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Order.md new file mode 100644 index 0000000000..409fc4cc96 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Order.md @@ -0,0 +1,27 @@ + + +# Order + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum + +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Pet.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Pet.md new file mode 100644 index 0000000000..37ac007b79 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Pet.md @@ -0,0 +1,27 @@ + + +# Pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum + +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/PetApi.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/PetApi.md new file mode 100644 index 0000000000..56e81ea3aa --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/PetApi.md @@ -0,0 +1,581 @@ +# PetApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +## addPet + +> addPet(body) + +Add a new pet to the store + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + + +## deletePet + +> deletePet(petId, apiKey) + +Deletes a pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | Pet id to delete + String apiKey = "apiKey_example"; // String | + try { + apiInstance.deletePet(petId, apiKey); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +## findPetsByStatus + +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List status = Arrays.asList("available"); // List | Status values that need to be considered for filter + try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + + +## findPetsByTags + +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List tags = Arrays.asList(); // List | Tags to filter by + try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + + +## getPetById + +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to return + try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +## updatePet + +> updatePet(body) + +Update an existing pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.updatePet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + + +## updatePetWithForm + +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet that needs to be updated + String name = "name_example"; // String | Updated name of the pet + String status = "status_example"; // String | Updated status of the pet + try { + apiInstance.updatePetWithForm(petId, name, status); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + + +## uploadFile + +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + File file = new File("/path/to/file"); // File | file to upload + try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/StoreApi.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/StoreApi.md new file mode 100644 index 0000000000..7a70c0bdbc --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/StoreApi.md @@ -0,0 +1,276 @@ +# StoreApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +## deleteOrder + +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Long orderId = 56L; // Long | ID of the order that needs to be deleted + try { + apiInstance.deleteOrder(orderId); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## getInventory + +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + StoreApi apiInstance = new StoreApi(defaultClient); + try { + Map result = apiInstance.getInventory(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Map<String, Integer>** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## getOrderById + +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Long orderId = 56L; // Long | ID of pet that needs to be fetched + try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## placeOrder + +> Order placeOrder(body) + +Place an order for a pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Order body = new Order(); // Order | order placed for purchasing the pet + try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Tag.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Tag.md new file mode 100644 index 0000000000..f24eba7d22 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Tag.md @@ -0,0 +1,13 @@ + + +# Tag + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/User.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/User.md new file mode 100644 index 0000000000..c4ea94b7fc --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/User.md @@ -0,0 +1,19 @@ + + +# User + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/UserApi.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/UserApi.md new file mode 100644 index 0000000000..ff3815e352 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/UserApi.md @@ -0,0 +1,525 @@ +# UserApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +## createUser + +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + User body = new User(); // User | Created user object + try { + apiInstance.createUser(body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## createUsersWithArrayInput + +> createUsersWithArrayInput(body) + +Creates list of users with given input array + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List body = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithArrayInput(body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## createUsersWithListInput + +> createUsersWithListInput(body) + +Creates list of users with given input array + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List body = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithListInput(body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## deleteUser + +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be deleted + try { + apiInstance.deleteUser(username); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## getUserByName + +> User getUserByName(username) + +Get user by user name + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. + try { + User result = apiInstance.getUserByName(username); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## loginUser + +> String loginUser(username, password) + +Logs user into the system + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The user name for login + String password = "password_example"; // String | The password for login in clear text + try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
* X-Expires-After - date in UTC when token expires
| +| **400** | Invalid username/password supplied | - | + + +## logoutUser + +> logoutUser() + +Logs out current logged in user session + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + try { + apiInstance.logoutUser(); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## updateUser + +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | name that need to be updated + User body = new User(); // User | Updated user object + try { + apiInstance.updateUser(username, body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be updated | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/git_push.sh b/spring-swagger-codegen/spring-openapi-generator-api-client/git_push.sh new file mode 100644 index 0000000000..ced3be2b0c --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradle.properties b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle.properties new file mode 100644 index 0000000000..05644f0754 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.jar b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..cc4fdc293d Binary files /dev/null and b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.jar differ diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.properties b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..94920145f3 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew new file mode 100644 index 0000000000..2fe81a7d95 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# 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 +# +# https://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. +# + +############################################################################## +## +## 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='"-Xmx64m" "-Xms64m"' + +# 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 or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; 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=`expr $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" + +exec "$JAVACMD" "$@" diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew.bat b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew.bat new file mode 100644 index 0000000000..9618d8d960 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@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="-Xmx64m" "-Xms64m" + +@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/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml new file mode 100644 index 0000000000..cc70a9f654 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml @@ -0,0 +1,274 @@ + + 4.0.0 + com.baeldung + spring-openapi-generator-api-client + jar + spring-openapi-generator-api-client + 0.0.1-SNAPSHOT + https://github.com/openapitools/openapi-generator + OpenAPI Java + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + OpenAPI-Generator Contributors + team@openapitools.org + OpenAPITools.org + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + + org.springframework + spring-web + ${spring-web-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind-version} + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${jackson-threetenbp-version} + + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.5.22 + 4.3.9.RELEASE + 2.10.1 + 2.10.1 + 0.2.1 + 2.9.10 + 1.0.0 + 4.13 + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/settings.gradle b/spring-swagger-codegen/spring-openapi-generator-api-client/settings.gradle new file mode 100644 index 0000000000..06a087cb49 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "spring-openapi-generator-api-client" \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/AndroidManifest.xml b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..cd581f9f78 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java new file mode 100644 index 0000000000..b7256c81fb --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java @@ -0,0 +1,477 @@ +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.model.ModelApiResponse; +import com.baeldung.petstore.client.model.Pet; + +import java.io.File; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +@Component("com.baeldung.petstore.client.api.PetApi") +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(new ApiClient()); + } + + @Autowired + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a new pet to the store + * + *

405 - Invalid input + * @param body Pet object that needs to be added to the store (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void addPet(Pet body) throws RestClientException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + *

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

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deletePet(Long petId, String apiKey) throws RestClientException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + *

400 - Invalid ID supplied + *

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

200 - successful operation + *

400 - Invalid status value + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public List findPetsByStatus(List status) throws RestClientException { + return findPetsByStatusWithHttpInfo(status).getBody(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + *

200 - successful operation + *

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

200 - successful operation + *

400 - Invalid tag value + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + @Deprecated + public List findPetsByTags(List tags) throws RestClientException { + return findPetsByTagsWithHttpInfo(tags).getBody(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + *

200 - successful operation + *

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

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId ID of pet to return (required) + * @return Pet + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Pet getPetById(Long petId) throws RestClientException { + return getPetByIdWithHttpInfo(petId).getBody(); + } + + /** + * Find pet by ID + * Returns a single pet + *

200 - successful operation + *

400 - Invalid ID supplied + *

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

400 - Invalid ID supplied + *

404 - Pet not found + *

405 - Validation exception + * @param body Pet object that needs to be added to the store (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updatePet(Pet body) throws RestClientException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + *

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

405 - Invalid input + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updatePetWithForm(Long petId, String name, String status) throws RestClientException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + *

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

200 - successful operation + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { + return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody(); + } + + /** + * uploads an image + * + *

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

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of the order that needs to be deleted (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteOrder(Long orderId) throws RestClientException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + *

400 - Invalid ID supplied + *

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

200 - successful operation + * @return Map<String, Integer> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Map getInventory() throws RestClientException { + return getInventoryWithHttpInfo().getBody(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + *

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

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Order getOrderById(Long orderId) throws RestClientException { + return getOrderByIdWithHttpInfo(orderId).getBody(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + *

200 - successful operation + *

400 - Invalid ID supplied + *

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

200 - successful operation + *

400 - Invalid Order + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Order placeOrder(Order body) throws RestClientException { + return placeOrderWithHttpInfo(body).getBody(); + } + + /** + * Place an order for a pet + * + *

200 - successful operation + *

400 - Invalid Order + * @param body order placed for purchasing the pet (required) + * @return ResponseEntity<Order> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity placeOrderWithHttpInfo(Order body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling placeOrder"); + } + + String path = apiClient.expandPath("/store/order", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java new file mode 100644 index 0000000000..c7cb0b803d --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java @@ -0,0 +1,441 @@ +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.model.User; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +@Component("com.baeldung.petstore.client.api.UserApi") +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(new ApiClient()); + } + + @Autowired + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create user + * This can only be done by the logged in user. + *

0 - successful operation + * @param body Created user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUser(User body) throws RestClientException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + *

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

0 - successful operation + * @param body List of user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUsersWithArrayInput(List body) throws RestClientException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + *

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

0 - successful operation + * @param body List of user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUsersWithListInput(List body) throws RestClientException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + *

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

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be deleted (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteUser(String username) throws RestClientException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + *

400 - Invalid username supplied + *

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

200 - successful operation + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public User getUserByName(String username) throws RestClientException { + return getUserByNameWithHttpInfo(username).getBody(); + } + + /** + * Get user by user name + * + *

200 - successful operation + *

400 - Invalid username supplied + *

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

200 - successful operation + *

400 - Invalid username/password supplied + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String loginUser(String username, String password) throws RestClientException { + return loginUserWithHttpInfo(username, password).getBody(); + } + + /** + * Logs user into the system + * + *

200 - successful operation + *

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

0 - successful operation + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void logoutUser() throws RestClientException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + *

0 - successful operation + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity logoutUserWithHttpInfo() throws RestClientException { + Object postBody = null; + + String path = apiClient.expandPath("/user/logout", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Updated user + * This can only be done by the logged in user. + *

400 - Invalid user supplied + *

404 - User not found + * @param username name that need to be updated (required) + * @param body Updated user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updateUser(String username, User body) throws RestClientException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + *

400 - Invalid user supplied + *

404 - User not found + * @param username name that need to be updated (required) + * @param body Updated user object (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateUserWithHttpInfo(String username, User body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updateUser"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + String path = apiClient.expandPath("/user/{username}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java new file mode 100644 index 0000000000..5a10828c47 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java @@ -0,0 +1,750 @@ +package com.baeldung.petstore.client.invoker; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; + +import com.baeldung.petstore.client.invoker.auth.ApiKeyAuth; +import com.baeldung.petstore.client.invoker.auth.Authentication; +import com.baeldung.petstore.client.invoker.auth.HttpBasicAuth; +import com.baeldung.petstore.client.invoker.auth.HttpBearerAuth; +import com.baeldung.petstore.client.invoker.auth.OAuth; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TimeZone; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openapitools.jackson.nullable.JsonNullableModule; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpRequest; +import org.springframework.http.InvalidMediaTypeException; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.RequestEntity.BodyBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; +import org.threeten.bp.*; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +@Component("com.baeldung.petstore.client.invoker.ApiClient") +public class ApiClient { + public enum CollectionFormat { + CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null); + + private final String separator; + private CollectionFormat(String separator) { + this.separator = separator; + } + + private String collectionToString(Collection collection) { + return StringUtils.collectionToDelimitedString(collection, separator); + } + } + + private boolean debugging = false; + + private HttpHeaders defaultHeaders = new HttpHeaders(); + private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + + private String basePath = "https://petstore.swagger.io/v2"; + + private RestTemplate restTemplate; + + private Map authentications; + + private DateFormat dateFormat; + + public ApiClient() { + this.restTemplate = buildRestTemplate(); + init(); + } + + @Autowired + public ApiClient(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + init(); + } + + protected void init() { + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new RFC3339DateFormat(); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + // Set default User-Agent. + setUserAgent("Java-SDK"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Get the current base path + * @return String the base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set the base path, which should include the host + * @param basePath the base path + * @return ApiClient this client + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * @return Map the currently configured authentication types + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set token for HTTP bearer authentication. + * @param bearerToken the token + */ + public void setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * @param username the username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * @param password the password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * @param apiKey the API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix the API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * @param accessToken the access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent the user agent string + * @return ApiClient this client + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param name The header's name + * @param value The header's value + * @return ApiClient this client + */ + public ApiClient addDefaultHeader(String name, String value) { + if (defaultHeaders.containsKey(name)) { + defaultHeaders.remove(name); + } + defaultHeaders.add(name, value); + return this; + } + + /** + * Add a default cookie. + * + * @param name The cookie's name + * @param value The cookie's value + * @return ApiClient this client + */ + public ApiClient addDefaultCookie(String name, String value) { + if (defaultCookies.containsKey(name)) { + defaultCookies.remove(name); + } + defaultCookies.add(name, value); + return this; + } + + public void setDebugging(boolean debugging) { + List currentInterceptors = this.restTemplate.getInterceptors(); + if(debugging) { + if (currentInterceptors == null) { + currentInterceptors = new ArrayList(); + } + ClientHttpRequestInterceptor interceptor = new ApiClientHttpRequestInterceptor(); + currentInterceptors.add(interceptor); + this.restTemplate.setInterceptors(currentInterceptors); + } else { + if (currentInterceptors != null && !currentInterceptors.isEmpty()) { + Iterator iter = currentInterceptors.iterator(); + while (iter.hasNext()) { + ClientHttpRequestInterceptor interceptor = iter.next(); + if (interceptor instanceof ApiClientHttpRequestInterceptor) { + iter.remove(); + } + } + this.restTemplate.setInterceptors(currentInterceptors); + } + } + this.debugging = debugging; + } + + /** + * Check that whether debugging is enabled for this API client. + * @return boolean true if this client is enabled for debugging, false otherwise + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Get the date format used to parse/format date parameters. + * @return DateFormat format + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + for(HttpMessageConverter converter:restTemplate.getMessageConverters()){ + if(converter instanceof AbstractJackson2HttpMessageConverter){ + ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper(); + mapper.setDateFormat(dateFormat); + } + } + return this; + } + + /** + * Parse the given string into Date object. + * @param str the string to parse + * @return the Date parsed from the string + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + * @param date the date to format + * @return the formatted date as string + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + * @param param the object to convert + * @return String the parameter represented as a String + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate( (Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection) param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param values The values of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(CollectionFormat collectionFormat, Collection values) { + // create the value based on the collection format + if (CollectionFormat.MULTI.equals(collectionFormat)) { + // not valid for path params + return parameterToString(values); + } + + // collectionFormat is assumed to be "csv" by default + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + return collectionFormat.collectionToString(values); + } + + /** + * Converts a parameter to a {@link MultiValueMap} for use in REST requests + * @param collectionFormat The format to convert to + * @param name The name of the parameter + * @param value The parameter's value + * @return a Map containing the String value(s) of the input parameter + */ + public MultiValueMap parameterToMultiValueMap(CollectionFormat collectionFormat, String name, Object value) { + final MultiValueMap params = new LinkedMultiValueMap(); + + if (name == null || name.isEmpty() || value == null) { + return params; + } + + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(name, parameterToString(value)); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + if (collectionFormat.equals(CollectionFormat.MULTI)) { + for (Object item : valueCollection) { + params.add(name, parameterToString(item)); + } + return params; + } + + List values = new ArrayList(); + for(Object o : valueCollection) { + values.add(parameterToString(o)); + } + params.add(name, collectionFormat.collectionToString(values)); + + return params; + } + + /** + * Check if the given {@code String} is a JSON MIME. + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(String mediaType) { + // "* / *" is default to JSON + if ("*/*".equals(mediaType)) { + return true; + } + + try { + return isJsonMime(MediaType.parseMediaType(mediaType)); + } catch (InvalidMediaTypeException e) { + } + return false; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(MediaType mediaType) { + return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return List The list of MediaTypes to use for the Accept header + */ + public List selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + MediaType mediaType = MediaType.parseMediaType(accept); + if (isJsonMime(mediaType)) { + return Collections.singletonList(mediaType); + } + } + return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts)); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return MediaType The Content-Type header to use. If the given array is empty, JSON will be used. + */ + public MediaType selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return MediaType.APPLICATION_JSON; + } + for (String contentType : contentTypes) { + MediaType mediaType = MediaType.parseMediaType(contentType); + if (isJsonMime(mediaType)) { + return mediaType; + } + } + return MediaType.parseMediaType(contentTypes[0]); + } + + /** + * Select the body to use for the request + * @param obj the body object + * @param formParams the form parameters + * @param contentType the content type of the request + * @return Object the selected body + */ + protected Object selectBody(Object obj, MultiValueMap formParams, MediaType contentType) { + boolean isForm = MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType) || MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType); + return isForm ? formParams : obj; + } + + /** + * Expand path template with variables + * @param pathTemplate path template with placeholders + * @param variables variables to replace + * @return path with placeholders replaced by variables + */ + public String expandPath(String pathTemplate, Map variables) { + return restTemplate.getUriTemplateHandler().expand(pathTemplate, variables).toString(); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param the return type to use + * @param path The sub-path of the HTTP URL + * @param method The request method + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return ResponseEntity<T> The response of the chosen type + */ + public ResponseEntity invokeAPI(String path, HttpMethod method, MultiValueMap queryParams, Object body, HttpHeaders headerParams, MultiValueMap cookieParams, MultiValueMap formParams, List accept, MediaType contentType, String[] authNames, ParameterizedTypeReference returnType) throws RestClientException { + updateParamsForAuth(authNames, queryParams, headerParams, cookieParams); + + final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path); + if (queryParams != null) { + //encode the query parameters in case they contain unsafe characters + for (List values : queryParams.values()) { + if (values != null) { + for (int i = 0; i < values.size(); i++) { + try { + values.set(i, URLEncoder.encode(values.get(i), "utf8")); + } catch (UnsupportedEncodingException e) { + + } + } + } + } + builder.queryParams(queryParams); + } + + URI uri; + try { + uri = new URI(builder.build().toUriString()); + } catch(URISyntaxException ex) { + throw new RestClientException("Could not build URL: " + builder.toUriString(), ex); + } + + final BodyBuilder requestBuilder = RequestEntity.method(method, uri); + if(accept != null) { + requestBuilder.accept(accept.toArray(new MediaType[accept.size()])); + } + if(contentType != null) { + requestBuilder.contentType(contentType); + } + + addHeadersToRequest(headerParams, requestBuilder); + addHeadersToRequest(defaultHeaders, requestBuilder); + addCookiesToRequest(cookieParams, requestBuilder); + addCookiesToRequest(defaultCookies, requestBuilder); + + RequestEntity requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); + + ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + return responseEntity; + } else { + // The error handler built into the RestTemplate should handle 400 and 500 series errors. + throw new RestClientException("API returned " + responseEntity.getStatusCode() + " and it wasn't handled by the RestTemplate error handler"); + } + } + + /** + * Add headers to the request that is being built + * @param headers The headers to add + * @param requestBuilder The current request + */ + protected void addHeadersToRequest(HttpHeaders headers, BodyBuilder requestBuilder) { + for (Entry> entry : headers.entrySet()) { + List values = entry.getValue(); + for(String value : values) { + if (value != null) { + requestBuilder.header(entry.getKey(), value); + } + } + } + } + + /** + * Add cookies to the request that is being built + * @param cookies The cookies to add + * @param requestBuilder The current request + */ + protected void addCookiesToRequest(MultiValueMap cookies, BodyBuilder requestBuilder) { + if (!cookies.isEmpty()) { + requestBuilder.header("Cookie", buildCookieHeader(cookies)); + } + } + + /** + * Build cookie header. Keeps a single value per cookie (as per + * RFC6265 section 5.3). + * + * @param cookies map all cookies + * @return header string for cookies. + */ + private String buildCookieHeader(MultiValueMap cookies) { + final StringBuilder cookieValue = new StringBuilder(); + String delimiter = ""; + for (final Map.Entry> entry : cookies.entrySet()) { + final String value = entry.getValue().get(entry.getValue().size() - 1); + cookieValue.append(String.format("%s%s=%s", delimiter, entry.getKey(), value)); + delimiter = "; "; + } + return cookieValue.toString(); + } + + /** + * Build the RestTemplate used to make HTTP requests. + * @return RestTemplate + */ + protected RestTemplate buildRestTemplate() { + RestTemplate restTemplate = new RestTemplate(); + for(HttpMessageConverter converter:restTemplate.getMessageConverters()){ + if(converter instanceof AbstractJackson2HttpMessageConverter){ + ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper(); + ThreeTenModule module = new ThreeTenModule(); + module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); + module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); + module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); + mapper.registerModule(module); + mapper.registerModule(new JsonNullableModule()); + } + } + // This allows us to read the response more than once - Necessary for debugging. + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory())); + return restTemplate; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams The query parameters + * @param headerParams The header parameters + */ + private void updateParamsForAuth(String[] authNames, MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RestClientException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams, cookieParams); + } + } + + private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { + private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + logRequest(request, body); + ClientHttpResponse response = execution.execute(request, body); + logResponse(response); + return response; + } + + private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException { + log.info("URI: " + request.getURI()); + log.info("HTTP Method: " + request.getMethod()); + log.info("HTTP Headers: " + headersToString(request.getHeaders())); + log.info("Request Body: " + new String(body, StandardCharsets.UTF_8)); + } + + private void logResponse(ClientHttpResponse response) throws IOException { + log.info("HTTP Status Code: " + response.getRawStatusCode()); + log.info("Status Text: " + response.getStatusText()); + log.info("HTTP Headers: " + headersToString(response.getHeaders())); + log.info("Response Body: " + bodyToString(response.getBody())); + } + + private String headersToString(HttpHeaders headers) { + StringBuilder builder = new StringBuilder(); + for(Entry> entry : headers.entrySet()) { + builder.append(entry.getKey()).append("=["); + for(String value : entry.getValue()) { + builder.append(value).append(","); + } + builder.setLength(builder.length() - 1); // Get rid of trailing comma + builder.append("],"); + } + builder.setLength(builder.length() - 1); // Get rid of trailing comma + return builder.toString(); + } + + private String bodyToString(InputStream body) throws IOException { + StringBuilder builder = new StringBuilder(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); + String line = bufferedReader.readLine(); + while (line != null) { + builder.append(line).append(System.lineSeparator()); + line = bufferedReader.readLine(); + } + bufferedReader.close(); + return builder.toString(); + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/CustomInstantDeserializer.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/CustomInstantDeserializer.java new file mode 100644 index 0000000000..6957818fb4 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/CustomInstantDeserializer.java @@ -0,0 +1,233 @@ +package com.baeldung.petstore.client.invoker; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonTokenId; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils; +import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase; +import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction; +import com.fasterxml.jackson.datatype.threetenbp.function.Function; + +import java.io.IOException; +import java.math.BigDecimal; + +import org.threeten.bp.DateTimeException; +import org.threeten.bp.DateTimeUtils; +import org.threeten.bp.Instant; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneId; +import org.threeten.bp.ZonedDateTime; +import org.threeten.bp.format.DateTimeFormatter; +import org.threeten.bp.temporal.Temporal; +import org.threeten.bp.temporal.TemporalAccessor; + +/** + * Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s. + * Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format. + * + * @author Nick Williams + */ +public class CustomInstantDeserializer + extends ThreeTenDateTimeDeserializerBase { + private static final long serialVersionUID = 1L; + + public static final CustomInstantDeserializer INSTANT = new CustomInstantDeserializer( + Instant.class, DateTimeFormatter.ISO_INSTANT, + new Function() { + @Override + public Instant apply(TemporalAccessor temporalAccessor) { + return Instant.from(temporalAccessor); + } + }, + new Function() { + @Override + public Instant apply(FromIntegerArguments a) { + return Instant.ofEpochMilli(a.value); + } + }, + new Function() { + @Override + public Instant apply(FromDecimalArguments a) { + return Instant.ofEpochSecond(a.integer, a.fraction); + } + }, + null + ); + + public static final CustomInstantDeserializer OFFSET_DATE_TIME = new CustomInstantDeserializer( + OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME, + new Function() { + @Override + public OffsetDateTime apply(TemporalAccessor temporalAccessor) { + return OffsetDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromIntegerArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromDecimalArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public OffsetDateTime apply(OffsetDateTime d, ZoneId z) { + return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())); + } + } + ); + + public static final CustomInstantDeserializer ZONED_DATE_TIME = new CustomInstantDeserializer( + ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME, + new Function() { + @Override + public ZonedDateTime apply(TemporalAccessor temporalAccessor) { + return ZonedDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromIntegerArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromDecimalArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) { + return zonedDateTime.withZoneSameInstant(zoneId); + } + } + ); + + protected final Function fromMilliseconds; + + protected final Function fromNanoseconds; + + protected final Function parsedToValue; + + protected final BiFunction adjust; + + protected CustomInstantDeserializer(Class supportedType, + DateTimeFormatter parser, + Function parsedToValue, + Function fromMilliseconds, + Function fromNanoseconds, + BiFunction adjust) { + super(supportedType, parser); + this.parsedToValue = parsedToValue; + this.fromMilliseconds = fromMilliseconds; + this.fromNanoseconds = fromNanoseconds; + this.adjust = adjust == null ? new BiFunction() { + @Override + public T apply(T t, ZoneId zoneId) { + return t; + } + } : adjust; + } + + @SuppressWarnings("unchecked") + protected CustomInstantDeserializer(CustomInstantDeserializer base, DateTimeFormatter f) { + super((Class) base.handledType(), f); + parsedToValue = base.parsedToValue; + fromMilliseconds = base.fromMilliseconds; + fromNanoseconds = base.fromNanoseconds; + adjust = base.adjust; + } + + @Override + protected JsonDeserializer withDateFormat(DateTimeFormatter dtf) { + if (dtf == _formatter) { + return this; + } + return new CustomInstantDeserializer(this, dtf); + } + + @Override + public T deserialize(JsonParser parser, DeserializationContext context) throws IOException { + //NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only + //string values have to be adjusted to the configured TZ. + switch (parser.getCurrentTokenId()) { + case JsonTokenId.ID_NUMBER_FLOAT: { + BigDecimal value = parser.getDecimalValue(); + long seconds = value.longValue(); + int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds); + return fromNanoseconds.apply(new FromDecimalArguments( + seconds, nanoseconds, getZone(context))); + } + + case JsonTokenId.ID_NUMBER_INT: { + long timestamp = parser.getLongValue(); + if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { + return this.fromNanoseconds.apply(new FromDecimalArguments( + timestamp, 0, this.getZone(context) + )); + } + return this.fromMilliseconds.apply(new FromIntegerArguments( + timestamp, this.getZone(context) + )); + } + + case JsonTokenId.ID_STRING: { + String string = parser.getText().trim(); + if (string.length() == 0) { + return null; + } + if (string.endsWith("+0000")) { + string = string.substring(0, string.length() - 5) + "Z"; + } + T value; + try { + TemporalAccessor acc = _formatter.parse(string); + value = parsedToValue.apply(acc); + if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) { + return adjust.apply(value, this.getZone(context)); + } + } catch (DateTimeException e) { + throw _peelDTE(e); + } + return value; + } + } + throw context.mappingException("Expected type float, integer, or string."); + } + + private ZoneId getZone(DeserializationContext context) { + // Instants are always in UTC, so don't waste compute cycles + return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone()); + } + + private static class FromIntegerArguments { + public final long value; + public final ZoneId zoneId; + + private FromIntegerArguments(long value, ZoneId zoneId) { + this.value = value; + this.zoneId = zoneId; + } + } + + private static class FromDecimalArguments { + public final long integer; + public final int fraction; + public final ZoneId zoneId; + + private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) { + this.integer = integer; + this.fraction = fraction; + this.zoneId = zoneId; + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java new file mode 100644 index 0000000000..46083815a6 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.baeldung.petstore.client.invoker; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java new file mode 100644 index 0000000000..b494b52050 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java @@ -0,0 +1,62 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location.equals("query")) { + queryParams.add(paramName, value); + } else if (location.equals("header")) { + headerParams.add(paramName, value); + } else if (location.equals("cookie")) { + cookieParams.add(paramName, value); + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java new file mode 100644 index 0000000000..8d55110d1b --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java @@ -0,0 +1,14 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +public interface Authentication { + /** + * Apply authentication settings to header and / or query parameters. + * @param queryParams The query parameters for the request + * @param headerParams The header parameters for the request + * @param cookieParams The cookie parameters for the request + */ + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams); +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java new file mode 100644 index 0000000000..4c1dad6e7c --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java @@ -0,0 +1,38 @@ +package com.baeldung.petstore.client.invoker.auth; + +import java.nio.charset.StandardCharsets; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.Base64Utils; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBearerAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBearerAuth.java new file mode 100644 index 0000000000..46ab6cabce --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBearerAuth.java @@ -0,0 +1,34 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private String bearerToken; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + public String getBearerToken() { + return bearerToken; + } + + public void setBearerToken(String bearerToken) { + this.bearerToken = bearerToken; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (bearerToken == null) { + return; + } + headerParams.add(HttpHeaders.AUTHORIZATION, (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java new file mode 100644 index 0000000000..b9e0f986ac --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java @@ -0,0 +1,24 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (accessToken != null) { + headerParams.add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java new file mode 100644 index 0000000000..235e0b7f55 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java @@ -0,0 +1,5 @@ +package com.baeldung.petstore.client.invoker.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java new file mode 100644 index 0000000000..2bb7ebe9f6 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java @@ -0,0 +1,131 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Category + */ +@JsonPropertyOrder({ + Category.JSON_PROPERTY_ID, + Category.JSON_PROPERTY_NAME +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Category { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + + public Category id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Category name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java new file mode 100644 index 0000000000..107e08b8b9 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java @@ -0,0 +1,162 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * ModelApiResponse + */ +@JsonPropertyOrder({ + ModelApiResponse.JSON_PROPERTY_CODE, + ModelApiResponse.JSON_PROPERTY_TYPE, + ModelApiResponse.JSON_PROPERTY_MESSAGE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class ModelApiResponse { + public static final String JSON_PROPERTY_CODE = "code"; + private Integer code; + + public static final String JSON_PROPERTY_TYPE = "type"; + private String type; + + public static final String JSON_PROPERTY_MESSAGE = "message"; + private String message; + + + public ModelApiResponse code(Integer code) { + + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_CODE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Integer getCode() { + return code; + } + + + public void setCode(Integer code) { + this.code = code; + } + + + public ModelApiResponse type(String type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getType() { + return type; + } + + + public void setType(String type) { + this.type = type; + } + + + public ModelApiResponse message(String message) { + + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_MESSAGE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getMessage() { + return message; + } + + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java new file mode 100644 index 0000000000..b041595785 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java @@ -0,0 +1,296 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonValue; + +import java.util.Objects; + +import org.threeten.bp.OffsetDateTime; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Order + */ +@JsonPropertyOrder({ + Order.JSON_PROPERTY_ID, + Order.JSON_PROPERTY_PET_ID, + Order.JSON_PROPERTY_QUANTITY, + Order.JSON_PROPERTY_SHIP_DATE, + Order.JSON_PROPERTY_STATUS, + Order.JSON_PROPERTY_COMPLETE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Order { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_PET_ID = "petId"; + private Long petId; + + public static final String JSON_PROPERTY_QUANTITY = "quantity"; + private Integer quantity; + + public static final String JSON_PROPERTY_SHIP_DATE = "shipDate"; + private OffsetDateTime shipDate; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_STATUS = "status"; + private StatusEnum status; + + public static final String JSON_PROPERTY_COMPLETE = "complete"; + private Boolean complete; + + + public Order id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Order petId(Long petId) { + + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_PET_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getPetId() { + return petId; + } + + + public void setPetId(Long petId) { + this.petId = petId; + } + + + public Order quantity(Integer quantity) { + + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_QUANTITY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Integer getQuantity() { + return quantity; + } + + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + public Order shipDate(OffsetDateTime shipDate) { + + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_SHIP_DATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public OffsetDateTime getShipDate() { + return shipDate; + } + + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + + public Order status(StatusEnum status) { + + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "Order Status") + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public StatusEnum getStatus() { + return status; + } + + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + public Order complete(Boolean complete) { + + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_COMPLETE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Boolean getComplete() { + return complete; + } + + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java new file mode 100644 index 0000000000..3709cd5371 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java @@ -0,0 +1,310 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.baeldung.petstore.client.model.Category; +import com.baeldung.petstore.client.model.Tag; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Pet + */ +@JsonPropertyOrder({ + Pet.JSON_PROPERTY_ID, + Pet.JSON_PROPERTY_CATEGORY, + Pet.JSON_PROPERTY_NAME, + Pet.JSON_PROPERTY_PHOTO_URLS, + Pet.JSON_PROPERTY_TAGS, + Pet.JSON_PROPERTY_STATUS +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Pet { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_CATEGORY = "category"; + private Category category; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + public static final String JSON_PROPERTY_PHOTO_URLS = "photoUrls"; + private List photoUrls = new ArrayList<>(); + + public static final String JSON_PROPERTY_TAGS = "tags"; + private List tags = null; + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_STATUS = "status"; + private StatusEnum status; + + + public Pet id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Pet category(Category category) { + + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_CATEGORY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Category getCategory() { + return category; + } + + + public void setCategory(Category category) { + this.category = category; + } + + + public Pet name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + public Pet photoUrls(List photoUrls) { + + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty(JSON_PROPERTY_PHOTO_URLS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getPhotoUrls() { + return photoUrls; + } + + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + public Pet tags(List tags) { + + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_TAGS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getTags() { + return tags; + } + + + public void setTags(List tags) { + this.tags = tags; + } + + + public Pet status(StatusEnum status) { + + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "pet status in the store") + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public StatusEnum getStatus() { + return status; + } + + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java new file mode 100644 index 0000000000..7ee50c69b0 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java @@ -0,0 +1,131 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Tag + */ +@JsonPropertyOrder({ + Tag.JSON_PROPERTY_ID, + Tag.JSON_PROPERTY_NAME +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Tag { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + + public Tag id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Tag name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/User.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/User.java new file mode 100644 index 0000000000..ba12953ed3 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/User.java @@ -0,0 +1,317 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * User + */ +@JsonPropertyOrder({ + User.JSON_PROPERTY_ID, + User.JSON_PROPERTY_USERNAME, + User.JSON_PROPERTY_FIRST_NAME, + User.JSON_PROPERTY_LAST_NAME, + User.JSON_PROPERTY_EMAIL, + User.JSON_PROPERTY_PASSWORD, + User.JSON_PROPERTY_PHONE, + User.JSON_PROPERTY_USER_STATUS +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class User { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_USERNAME = "username"; + private String username; + + public static final String JSON_PROPERTY_FIRST_NAME = "firstName"; + private String firstName; + + public static final String JSON_PROPERTY_LAST_NAME = "lastName"; + private String lastName; + + public static final String JSON_PROPERTY_EMAIL = "email"; + private String email; + + public static final String JSON_PROPERTY_PASSWORD = "password"; + private String password; + + public static final String JSON_PROPERTY_PHONE = "phone"; + private String phone; + + public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; + private Integer userStatus; + + + public User id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public User username(String username) { + + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_USERNAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getUsername() { + return username; + } + + + public void setUsername(String username) { + this.username = username; + } + + + public User firstName(String firstName) { + + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_FIRST_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getFirstName() { + return firstName; + } + + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + public User lastName(String lastName) { + + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_LAST_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getLastName() { + return lastName; + } + + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + public User email(String email) { + + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_EMAIL) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getEmail() { + return email; + } + + + public void setEmail(String email) { + this.email = email; + } + + + public User password(String password) { + + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_PASSWORD) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getPassword() { + return password; + } + + + public void setPassword(String password) { + this.password = password; + } + + + public User phone(String phone) { + + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_PHONE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getPhone() { + return phone; + } + + + public void setPhone(String phone) { + this.phone = phone; + } + + + public User userStatus(Integer userStatus) { + + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "User Status") + @JsonProperty(JSON_PROPERTY_USER_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Integer getUserStatus() { + return userStatus; + } + + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java new file mode 100644 index 0000000000..8854e8e3d4 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java @@ -0,0 +1,167 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.model.ModelApiResponse; +import com.baeldung.petstore.client.model.Pet; + +import java.io.File; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * 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 + * + * Multiple 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-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java new file mode 100644 index 0000000000..444429bd42 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java @@ -0,0 +1,95 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.model.Order; + +import java.util.Map; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * 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-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java new file mode 100644 index 0000000000..c73b47ecb2 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java @@ -0,0 +1,161 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.model.User; + +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * 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-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/CategoryTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/CategoryTest.java new file mode 100644 index 0000000000..7be1b285c3 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/CategoryTest.java @@ -0,0 +1,49 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/ModelApiResponseTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/ModelApiResponseTest.java new file mode 100644 index 0000000000..55f742f862 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/ModelApiResponseTest.java @@ -0,0 +1,57 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for ModelApiResponse + */ +public class ModelApiResponseTest { + private final ModelApiResponse model = new ModelApiResponse(); + + /** + * Model tests for ModelApiResponse + */ + @Test + public void testModelApiResponse() { + // TODO: test ModelApiResponse + } + + /** + * Test the property 'code' + */ + @Test + public void codeTest() { + // TODO: test code + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'message' + */ + @Test + public void messageTest() { + // TODO: test message + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/OrderTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/OrderTest.java new file mode 100644 index 0000000000..edbacea028 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/OrderTest.java @@ -0,0 +1,81 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Order + */ +public class OrderTest { + private final Order model = new Order(); + + /** + * Model tests for Order + */ + @Test + public void testOrder() { + // TODO: test Order + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/PetTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/PetTest.java new file mode 100644 index 0000000000..78951acaba --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/PetTest.java @@ -0,0 +1,81 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/TagTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/TagTest.java new file mode 100644 index 0000000000..16efed2570 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/TagTest.java @@ -0,0 +1,49 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/UserTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/UserTest.java new file mode 100644 index 0000000000..d84cfb21ca --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/UserTest.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. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for User + */ +public class UserTest { + private final User model = new User(); + + /** + * Model tests for User + */ + @Test + public void testUser() { + // TODO: test User + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md deleted file mode 100644 index cffab6b9c7..0000000000 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md +++ /dev/null @@ -1,159 +0,0 @@ -## Spring Swagger Codegen API Client - -This module contains the code for [Generate Spring Boot REST Client with Swagger](http://www.baeldung.com/spring-boot-rest-client-swagger-codegen). - -## Requirements - -Building the API client library requires [Maven](https://maven.apache.org/) to be installed. - -## Installation - -To install the API client library to your local Maven repository, simply execute: - -```shell -mvn install -``` - -To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: - -```shell -mvn deploy -``` - -Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. - -### Maven users - -Add this dependency to your project's POM: - -```xml - - com.baeldung - spring-swagger-codegen-api-client - 0.0.1-SNAPSHOT - compile - -``` - -### Gradle users - -Add this dependency to your project's build file: - -```groovy -compile "com.baeldung:spring-swagger-codegen-api-client:0.0.1-SNAPSHOT" -``` - -### Others - -At first generate the JAR by executing: - - mvn package - -Then manually install the following JARs: - -* target/spring-swagger-codegen-api-client-0.0.1-SNAPSHOT.jar -* target/lib/*.jar - -## Getting Started - -Please follow the [installation](#installation) instruction and execute the following Java code: - -```java - -import com.baeldung.petstore.client.invoker.*; -import com.baeldung.petstore.client.invoker.auth.*; -import com.baeldung.petstore.client.model.*; -import com.baeldung.petstore.client.api.PetApi; - -import java.io.File; -import java.util.*; - -public class PetApiExample { - - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(); - Pet body = new Pet(); // Pet | Pet object that needs to be added to the store - try { - apiInstance.addPet(body); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#addPet"); - e.printStackTrace(); - } - } -} - -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://petstore.swagger.io/v2* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet -*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user -*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user - - -## Documentation for Models - - - [Category](docs/Category.md) - - [ModelApiResponse](docs/ModelApiResponse.md) - - [Order](docs/Order.md) - - [Pet](docs/Pet.md) - - [Tag](docs/Tag.md) - - [User](docs/User.md) - - -## Documentation for Authorization - -Authentication schemes defined for the API: -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - -### petstore_auth - -- **Type**: OAuth -- **Flow**: implicit -- **Authorization URL**: http://petstore.swagger.io/oauth/dialog -- **Scopes**: - - write:pets: modify pets in your account - - read:pets: read your pets - - -## Recommendation - -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. - -## Author - -apiteam@swagger.io - - - diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/README.md b/spring-swagger-codegen/spring-swagger-codegen-app/README.md index 1cb9e35d99..8740b17ba3 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/README.md +++ b/spring-swagger-codegen/spring-swagger-codegen-app/README.md @@ -1,3 +1,3 @@ ## Spring Swagger Codegen App -This module contains the code for [Generate Spring Boot REST Client with Swagger](http://www.baeldung.com/spring-boot-rest-client-swagger-codegen). +This module contains the code for Generate Spring Boot REST Client with Swagger. diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/com/baeldung/SpringContextTest.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..54949598aa --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.petstore.app.PetStoreApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PetStoreApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 79b2b7fa88..0000000000 --- a/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.petstore.app.PetStoreApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = PetStoreApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-threads/README.md b/spring-threads/README.md new file mode 100644 index 0000000000..c3762cd86f --- /dev/null +++ b/spring-threads/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize](https://www.baeldung.com/java-threadpooltaskexecutor-core-vs-max-poolsize) diff --git a/spring-threads/pom.xml b/spring-threads/pom.xml new file mode 100644 index 0000000000..4513c627b9 --- /dev/null +++ b/spring-threads/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + spring-threads + 0.0.1-SNAPSHOT + spring-threads + jar + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + org.springframework + spring-context + ${spring.version} + + + + diff --git a/spring-threads/src/test/java/com/baeldung/threading/ThreadPoolTaskExecutorUnitTest.java b/spring-threads/src/test/java/com/baeldung/threading/ThreadPoolTaskExecutorUnitTest.java new file mode 100644 index 0000000000..0d927ebe69 --- /dev/null +++ b/spring-threads/src/test/java/com/baeldung/threading/ThreadPoolTaskExecutorUnitTest.java @@ -0,0 +1,98 @@ +package com.baeldung.threading; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ThreadLocalRandom; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +public class ThreadPoolTaskExecutorUnitTest { + + void startThreads(ThreadPoolTaskExecutor taskExecutor, CountDownLatch countDownLatch, int numThreads) { + for (int i = 0; i < numThreads; i++) { + taskExecutor.execute(() -> { + try { + Thread.sleep(100L * ThreadLocalRandom.current().nextLong(1, 10)); + countDownLatch.countDown(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } + } + + @Test + public void whenUsingDefaults_thenSingleThread() { + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + taskExecutor.afterPropertiesSet(); + + CountDownLatch countDownLatch = new CountDownLatch(10); + this.startThreads(taskExecutor, countDownLatch, 10); + + while (countDownLatch.getCount() > 0) { + Assert.assertEquals(1, taskExecutor.getPoolSize()); + } + } + + @Test + public void whenCorePoolSizeFive_thenFiveThreads() { + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + taskExecutor.setCorePoolSize(5); + taskExecutor.afterPropertiesSet(); + + CountDownLatch countDownLatch = new CountDownLatch(10); + this.startThreads(taskExecutor, countDownLatch, 10); + + while (countDownLatch.getCount() > 0) { + Assert.assertEquals(5, taskExecutor.getPoolSize()); + } + } + + @Test + public void whenCorePoolSizeFiveAndMaxPoolSizeTen_thenFiveThreads() { + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + taskExecutor.setCorePoolSize(5); + taskExecutor.setMaxPoolSize(10); + taskExecutor.afterPropertiesSet(); + + CountDownLatch countDownLatch = new CountDownLatch(10); + this.startThreads(taskExecutor, countDownLatch, 10); + + while (countDownLatch.getCount() > 0) { + Assert.assertEquals(5, taskExecutor.getPoolSize()); + } + } + + @Test + public void whenCorePoolSizeFiveAndMaxPoolSizeTenAndQueueCapacityZero_thenTenThreads() { + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + taskExecutor.setCorePoolSize(5); + taskExecutor.setMaxPoolSize(10); + taskExecutor.setQueueCapacity(0); + taskExecutor.afterPropertiesSet(); + + CountDownLatch countDownLatch = new CountDownLatch(10); + this.startThreads(taskExecutor, countDownLatch, 10); + + while (countDownLatch.getCount() > 0) { + Assert.assertEquals(10, taskExecutor.getPoolSize()); + } + } + + @Test + public void whenCorePoolSizeFiveAndMaxPoolSizeTenAndQueueCapacityTen_thenTenThreads() { + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + taskExecutor.setCorePoolSize(5); + taskExecutor.setMaxPoolSize(10); + taskExecutor.setQueueCapacity(10); + taskExecutor.afterPropertiesSet(); + + CountDownLatch countDownLatch = new CountDownLatch(20); + this.startThreads(taskExecutor, countDownLatch, 20); + + while (countDownLatch.getCount() > 0) { + Assert.assertEquals(10, taskExecutor.getPoolSize()); + } + } +} diff --git a/spring-thymeleaf-2/README.md b/spring-thymeleaf-2/README.md index d5c5ead43d..a8c067a443 100644 --- a/spring-thymeleaf-2/README.md +++ b/spring-thymeleaf-2/README.md @@ -13,4 +13,5 @@ This module contains articles about Spring with Thymeleaf - [Working with Boolean in Thymeleaf](https://www.baeldung.com/thymeleaf-boolean) - [Working With Custom HTML Attributes in Thymeleaf](https://www.baeldung.com/thymeleaf-custom-html-attributes) - [How to Create an Executable JAR with Maven](https://www.baeldung.com/executable-jar-with-maven) +- [Spring MVC Data and Thymeleaf](https://www.baeldung.com/spring-mvc-thymeleaf-data) - [[<-- prev]](/spring-thymeleaf) diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java new file mode 100644 index 0000000000..19f0101cf2 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.thymeleaf.mvcdata; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@Configuration +public class BeanConfig { + @Bean + public EmailData emailData() { + return new EmailData(); + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java new file mode 100644 index 0000000000..1bfe3f3428 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java @@ -0,0 +1,63 @@ +package com.baeldung.thymeleaf.mvcdata; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpSession; + +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.RequestParam; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@Controller +public class EmailController { + private EmailData emailData = new EmailData(); + private ServletContext servletContext; + + public EmailController(ServletContext servletContext) { + this.servletContext = servletContext; + } + + @GetMapping(value = "/email/modelattributes") + public String emailModel(Model model) { + model.addAttribute("emaildata", emailData); + return "mvcdata/email-model-attributes"; + } + + @ModelAttribute("emailModelAttribute") + EmailData emailModelAttribute() { + return emailData; + } + + @GetMapping(value = "/email/requestparameters") + public String emailRequestParameters( + @RequestParam(value = "emailsubject") String emailSubject, + @RequestParam(value = "emailcontent") String emailContent, + @RequestParam(value = "emailaddress") String emailAddress1, + @RequestParam(value = "emailaddress") String emailAddress2, + @RequestParam(value = "emaillocale") String emailLocale) { + return "mvcdata/email-request-parameters"; + } + + @GetMapping("/email/sessionattributes") + public String emailSessionAttributes(HttpSession httpSession) { + httpSession.setAttribute("emaildata", emailData); + return "mvcdata/email-session-attributes"; + } + + @GetMapping("/email/servletcontext") + public String emailServletContext() { + servletContext.setAttribute("emailsubject", emailData.getEmailSubject()); + servletContext.setAttribute("emailcontent", emailData.getEmailBody()); + servletContext.setAttribute("emailaddress", emailData.getEmailAddress1()); + servletContext.setAttribute("emaillocale", emailData.getEmailLocale()); + return "mvcdata/email-servlet-context"; + } + + @GetMapping("/email/beandata") + public String emailBeanData() { + return "mvcdata/email-bean-data"; + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java new file mode 100644 index 0000000000..9dc25bdaa7 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java @@ -0,0 +1,48 @@ +package com.baeldung.thymeleaf.mvcdata.repository; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class EmailData implements Serializable { + private String emailSubject; + private String emailBody; + private String emailLocale; + private String emailAddress1; + private String emailAddress2; + + public EmailData() { + this.emailSubject = "You have received a new message"; + this.emailBody = "Good morning !"; + this.emailLocale = "en-US"; + this.emailAddress1 = "jhon.doe@example.com"; + this.emailAddress2 = "mark.jakob@example.com"; + } + + public String getEmailSubject() { + return this.emailSubject; + } + + public String getEmailBody() { + return this.emailBody; + } + + public String getEmailLocale() { + return this.emailLocale; + } + + public String getEmailAddress1() { + return this.emailAddress1; + } + + public String getEmailAddress2() { + return this.emailAddress2; + } + + public List getEmailAddresses() { + List emailAddresses = new ArrayList<>(); + emailAddresses.add(getEmailAddress1()); + emailAddresses.add(getEmailAddress2()); + return emailAddresses; + } +} diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html new file mode 100644 index 0000000000..59073b51c6 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html @@ -0,0 +1,14 @@ + + + +

Subject

+

Subject

+

Content

+

Body

+

Email address

+

Email address

+

Language

+

Language

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html new file mode 100644 index 0000000000..caf136383a --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html @@ -0,0 +1,16 @@ + + + +

Subject

+

Subject

+

Content

+

+

Email addresses

+

+ +

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html new file mode 100644 index 0000000000..8bcd3e1c62 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html @@ -0,0 +1,20 @@ + + + +

Subject

+

Subject

+

Content

+

+

Email addresses

+

+ +

+

Email address 1

+

+

Email address 2

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html new file mode 100644 index 0000000000..b07573047e --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html @@ -0,0 +1,14 @@ + + + +

Subject

+

+

Content

+

+

Email address

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html new file mode 100644 index 0000000000..9227171fc6 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html @@ -0,0 +1,14 @@ + + + +

Subject

+

+

Content

+

+

Email address

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java b/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java new file mode 100644 index 0000000000..5e1190e174 --- /dev/null +++ b/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.thymeleaf.mvcdata; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +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.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.request.MockMvcRequestBuilders; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc(printOnlyOnFailure = false) +public class EmailControllerUnitTest { + + EmailData emailData = new EmailData(); + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenCallModelAttributes_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/modelattributes")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("You have received a new message"))); + } + + @Test + public void whenCallRequestParameters_thenReturnEmailData() throws Exception { + MultiValueMap params = new LinkedMultiValueMap<>(); + params.add("emailsubject", emailData.getEmailSubject()); + params.add("emailcontent", emailData.getEmailBody()); + params.add("emailaddress", emailData.getEmailAddress1()); + params.add("emailaddress", emailData.getEmailAddress2()); + params.add("emaillocale", emailData.getEmailLocale()); + mockMvc.perform(MockMvcRequestBuilders.get("/email/requestparameters") + .params(params)) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("en-US"))); + } + + @Test + public void whenCallSessionAttributes_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/sessionattributes")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("Good morning !"))); + } + + @Test + public void whenCallServletContext_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/servletcontext")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("jhon.doe@example.com"))); + } + + @Test + public void whenCallBeanData_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/beandata")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("jhon.doe@example.com"))); + } + +} diff --git a/spring-thymeleaf-3/README.md b/spring-thymeleaf-3/README.md new file mode 100644 index 0000000000..a8e234b067 --- /dev/null +++ b/spring-thymeleaf-3/README.md @@ -0,0 +1,6 @@ +## Spring Thymeleaf 3 + +This module contains articles about Spring with Thymeleaf + +## Relevant Articles: +- [Add CSS and JS to Thymeleaf](https://www.baeldung.com/spring-thymeleaf-css-js) diff --git a/spring-thymeleaf-3/pom.xml b/spring-thymeleaf-3/pom.xml new file mode 100644 index 0000000000..7677e50d79 --- /dev/null +++ b/spring-thymeleaf-3/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + spring-thymeleaf-3 + spring-thymeleaf-3 + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.thymeleaf.cssandjs.CssAndJsApplication + JAR + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + ${tomcat7-maven-plugin.version} + + + tomcat-run + + exec-war-only + + package + + / + false + webapp.jar + utf-8 + + + + + + spring-thymeleaf-3 + + + + 1.8 + 1.8 + 2.2 + + + diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java new file mode 100644 index 0000000000..2ccca82497 --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.thymeleaf; + +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-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java new file mode 100644 index 0000000000..fc6c142b8b --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.thymeleaf.cssandjs; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CssAndJsApplication { + public static void main(String[] args) { + SpringApplication.run(CssAndJsApplication.class, args); + } +} diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java new file mode 100644 index 0000000000..b56a7b468e --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java @@ -0,0 +1,15 @@ +package com.baeldung.thymeleaf.cssandjs; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class CssAndJsController { + + @GetMapping("/styled-page") + public String getStyledPage(Model model) { + model.addAttribute("name", "Baeldung Reader"); + return "cssandjs/styledPage"; + } +} diff --git a/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js b/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js new file mode 100644 index 0000000000..e192e6358e --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js @@ -0,0 +1,7 @@ +function showAlert() { + alert("The button was clicked!"); +} + +function showName(name) { + alert("Here's the name: " + name); +} \ No newline at end of file diff --git a/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css b/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css new file mode 100644 index 0000000000..1f57b4616a --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css @@ -0,0 +1,18 @@ +h2 { + font-family: sans-serif; + font-size: 1.5em; + text-transform: uppercase; +} + +strong { + font-weight: 700; + background-color: yellow; +} + +p { + font-family: sans-serif; +} + +label { + font-weight: 600; +} \ No newline at end of file diff --git a/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html b/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html new file mode 100644 index 0000000000..12e4fc9227 --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html @@ -0,0 +1,20 @@ + + + + + Add CSS and JS to Thymeleaf + + + + + +

Carefully Styled Heading

+

+ This is text on which we want to apply very special styling. +

+

+ + + \ No newline at end of file diff --git a/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..b7cfa140f0 --- /dev/null +++ b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java @@ -0,0 +1,13 @@ +package com.baeldung.thymeleaf; + +import org.junit.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +public class ApplicationIntegrationTest { + + @Test + public void contextLoads() { + + } +} diff --git a/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java new file mode 100644 index 0000000000..365608bd2a --- /dev/null +++ b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.thymeleaf.cssandjs; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +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.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; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = CssAndJsApplication.class) +public class CssAndJsControllerIntegrationTest { + @Autowired + private WebApplicationContext context; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); + } + + @Test + public void whenCalledGetStyledPage_thenReturnContent() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/styled-page")) + .andExpect(status().isOk()) + .andExpect(view().name("cssandjs/styledPage")) + .andExpect(content().string(containsString("Carefully Styled Heading"))); + } +} diff --git a/spring-vault/src/main/java/com/baeldung/springvault/Credentials.java b/spring-vault/src/main/java/com/baeldung/springvault/Credentials.java new file mode 100644 index 0000000000..548ebd4ff6 --- /dev/null +++ b/spring-vault/src/main/java/com/baeldung/springvault/Credentials.java @@ -0,0 +1,30 @@ +package com.baeldung.springvault; + +public class Credentials { + + private String username; + private String password; + + public Credentials() { + + } + + public Credentials(String username, String password) { + this.username = username; + this.password = password; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + @Override + public String toString() { + return "Credential [username=" + username + ", password=" + password + "]"; + } + +} diff --git a/spring-vault/src/main/java/org/baeldung/springvault/CredentialsService.java b/spring-vault/src/main/java/com/baeldung/springvault/CredentialsService.java similarity index 76% rename from spring-vault/src/main/java/org/baeldung/springvault/CredentialsService.java rename to spring-vault/src/main/java/com/baeldung/springvault/CredentialsService.java index 87c24bd947..6a4b7cb784 100644 --- a/spring-vault/src/main/java/org/baeldung/springvault/CredentialsService.java +++ b/spring-vault/src/main/java/com/baeldung/springvault/CredentialsService.java @@ -1,16 +1,10 @@ -package org.baeldung.springvault; +package com.baeldung.springvault; -import java.net.URI; import java.net.URISyntaxException; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import org.springframework.vault.authentication.TokenAuthentication; -import org.springframework.vault.client.VaultEndpoint; import org.springframework.vault.core.VaultTemplate; -import org.springframework.vault.core.env.VaultPropertySource; -import org.springframework.vault.support.VaultResponse; import org.springframework.vault.support.VaultResponseSupport; /** diff --git a/spring-vault/src/main/java/org/baeldung/springvault/SpringVaultApplication.java b/spring-vault/src/main/java/com/baeldung/springvault/SpringVaultApplication.java similarity index 91% rename from spring-vault/src/main/java/org/baeldung/springvault/SpringVaultApplication.java rename to spring-vault/src/main/java/com/baeldung/springvault/SpringVaultApplication.java index 916a809be5..979b2fb42e 100644 --- a/spring-vault/src/main/java/org/baeldung/springvault/SpringVaultApplication.java +++ b/spring-vault/src/main/java/com/baeldung/springvault/SpringVaultApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.springvault; +package com.baeldung.springvault; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-vault/src/main/java/org/baeldung/springvault/VaultConfig.java b/spring-vault/src/main/java/com/baeldung/springvault/VaultConfig.java similarity index 95% rename from spring-vault/src/main/java/org/baeldung/springvault/VaultConfig.java rename to spring-vault/src/main/java/com/baeldung/springvault/VaultConfig.java index 106a1a3d42..f13c605bd8 100644 --- a/spring-vault/src/main/java/org/baeldung/springvault/VaultConfig.java +++ b/spring-vault/src/main/java/com/baeldung/springvault/VaultConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.springvault; +package com.baeldung.springvault; import org.springframework.context.annotation.Configuration; import org.springframework.vault.authentication.ClientAuthentication; diff --git a/spring-vault/src/main/java/org/baeldung/springvault/VaultEnvironmentConfig.java b/spring-vault/src/main/java/com/baeldung/springvault/VaultEnvironmentConfig.java similarity index 95% rename from spring-vault/src/main/java/org/baeldung/springvault/VaultEnvironmentConfig.java rename to spring-vault/src/main/java/com/baeldung/springvault/VaultEnvironmentConfig.java index 6c796bc718..4f5777e94c 100644 --- a/spring-vault/src/main/java/org/baeldung/springvault/VaultEnvironmentConfig.java +++ b/spring-vault/src/main/java/com/baeldung/springvault/VaultEnvironmentConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.springvault; +package com.baeldung.springvault; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; diff --git a/spring-vault/src/main/java/org/baeldung/springvault/Credentials.java b/spring-vault/src/main/java/org/baeldung/springvault/Credentials.java deleted file mode 100644 index f90ab66a4e..0000000000 --- a/spring-vault/src/main/java/org/baeldung/springvault/Credentials.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.baeldung.springvault; - -public class Credentials { - - private String username; - private String password; - - public Credentials() { - - } - - public Credentials(String username, String password) { - this.username = username; - this.password = password; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - @Override - public String toString() { - return "Credential [username=" + username + ", password=" + password + "]"; - } - -} diff --git a/spring-vault/src/test/java/com/baeldung/springvault/SpringContextLiveTest.java b/spring-vault/src/test/java/com/baeldung/springvault/SpringContextLiveTest.java new file mode 100644 index 0000000000..8139522745 --- /dev/null +++ b/spring-vault/src/test/java/com/baeldung/springvault/SpringContextLiveTest.java @@ -0,0 +1,25 @@ +package com.baeldung.springvault; + +import com.baeldung.springvault.SpringVaultApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * This live test requires: + * vault server up and running on the environment + * + *
+ * For more info on setting up the vault server: + * https://www.baeldung.com/vault + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringVaultApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-vault/src/test/java/org/baeldung/springvault/VaultInitializer.java b/spring-vault/src/test/java/com/baeldung/springvault/VaultInitializer.java similarity index 99% rename from spring-vault/src/test/java/org/baeldung/springvault/VaultInitializer.java rename to spring-vault/src/test/java/com/baeldung/springvault/VaultInitializer.java index c7db5eb199..a823a4cd27 100644 --- a/spring-vault/src/test/java/org/baeldung/springvault/VaultInitializer.java +++ b/spring-vault/src/test/java/com/baeldung/springvault/VaultInitializer.java @@ -1,4 +1,4 @@ -package org.baeldung.springvault; +package com.baeldung.springvault; import java.io.BufferedReader; import java.io.Closeable; diff --git a/spring-vault/src/test/java/org/baeldung/springvault/VaultIntegrationTest.java b/spring-vault/src/test/java/com/baeldung/springvault/VaultIntegrationTest.java similarity index 98% rename from spring-vault/src/test/java/org/baeldung/springvault/VaultIntegrationTest.java rename to spring-vault/src/test/java/com/baeldung/springvault/VaultIntegrationTest.java index 9f4b5d82a4..dd8797aacc 100644 --- a/spring-vault/src/test/java/org/baeldung/springvault/VaultIntegrationTest.java +++ b/spring-vault/src/test/java/com/baeldung/springvault/VaultIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.springvault; +package com.baeldung.springvault; import org.junit.FixMethodOrder; import org.junit.Ignore; diff --git a/spring-vault/src/test/java/org/baeldung/springvault/VaultTestConfiguration.java b/spring-vault/src/test/java/com/baeldung/springvault/VaultTestConfiguration.java similarity index 96% rename from spring-vault/src/test/java/org/baeldung/springvault/VaultTestConfiguration.java rename to spring-vault/src/test/java/com/baeldung/springvault/VaultTestConfiguration.java index 09a1445788..42f0bfbce9 100644 --- a/spring-vault/src/test/java/org/baeldung/springvault/VaultTestConfiguration.java +++ b/spring-vault/src/test/java/com/baeldung/springvault/VaultTestConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.springvault; +package com.baeldung.springvault; import java.net.URI; import java.net.URISyntaxException; diff --git a/spring-vault/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-vault/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index 60dc119f13..0000000000 --- a/spring-vault/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung; - -import org.baeldung.springvault.SpringVaultApplication; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * This live test requires: - * vault server up and running on the environment - * - *
- * For more info on setting up the vault server: - * https://www.baeldung.com/vault - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringVaultApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-vertx/src/main/java/com/baeldung/vertxspring/config/PortConfiguration.java b/spring-vertx/src/main/java/com/baeldung/vertxspring/config/PortConfiguration.java new file mode 100644 index 0000000000..23ca74ae80 --- /dev/null +++ b/spring-vertx/src/main/java/com/baeldung/vertxspring/config/PortConfiguration.java @@ -0,0 +1,31 @@ +package com.baeldung.vertxspring.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import java.io.IOException; +import java.net.ServerSocket; + +@Configuration +public class PortConfiguration { + + private static final int DEFAULT_PORT = 8069; + + @Profile("default") + @Bean + public Integer defaultPort() { + return DEFAULT_PORT; + } + + @Profile("test") + @Bean + public Integer randomPort() { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + + } catch (IOException e) { + return DEFAULT_PORT; + } + } +} diff --git a/spring-vertx/src/main/java/com/baeldung/vertxspring/verticles/ServerVerticle.java b/spring-vertx/src/main/java/com/baeldung/vertxspring/verticles/ServerVerticle.java index 3c23cb15bc..a84845f030 100644 --- a/spring-vertx/src/main/java/com/baeldung/vertxspring/verticles/ServerVerticle.java +++ b/spring-vertx/src/main/java/com/baeldung/vertxspring/verticles/ServerVerticle.java @@ -1,5 +1,6 @@ package com.baeldung.vertxspring.verticles; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import io.vertx.core.AbstractVerticle; @@ -9,6 +10,9 @@ import io.vertx.ext.web.RoutingContext; @Component public class ServerVerticle extends AbstractVerticle { + @Autowired + private Integer defaultPort; + private void getAllArticlesHandler(RoutingContext routingContext) { vertx.eventBus() .send(ArticleRecipientVerticle.GET_ALL_ARTICLES, "", result -> { @@ -36,7 +40,7 @@ public class ServerVerticle extends AbstractVerticle { vertx.createHttpServer() .requestHandler(router::accept) - .listen(config().getInteger("http.port", 8080)); + .listen(config().getInteger("http.port", defaultPort)); } } diff --git a/spring-vertx/src/test/java/com/baeldung/SpringContextTest.java b/spring-vertx/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..386d83b47b --- /dev/null +++ b/spring-vertx/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.vertxspring.VertxSpringApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = VertxSpringApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-vertx/src/test/java/com/baeldung/vertxspring/VertxSpringApplicationIntegrationTest.java b/spring-vertx/src/test/java/com/baeldung/vertxspring/VertxSpringApplicationIntegrationTest.java index bfb902e5d4..1eda45eb3b 100644 --- a/spring-vertx/src/test/java/com/baeldung/vertxspring/VertxSpringApplicationIntegrationTest.java +++ b/spring-vertx/src/test/java/com/baeldung/vertxspring/VertxSpringApplicationIntegrationTest.java @@ -1,27 +1,33 @@ package com.baeldung.vertxspring; -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.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import static org.junit.Assert.assertEquals; + @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest +@ActiveProfiles("test") public class VertxSpringApplicationIntegrationTest { + @Autowired + private Integer port; + private TestRestTemplate restTemplate = new TestRestTemplate(); @Test public void givenUrl_whenReceivedArticles_thenSuccess() throws InterruptedException { - ResponseEntity responseEntity = restTemplate.getForEntity("http://localhost:8080/api/baeldung/articles", String.class); + ResponseEntity responseEntity = restTemplate + .getForEntity("http://localhost:" + port + "/api/baeldung/articles", String.class); assertEquals(200, responseEntity.getStatusCodeValue()); } - } diff --git a/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java b/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 4ce94ec16a..0000000000 --- a/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.vertxspring.VertxSpringApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = VertxSpringApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-webflux-amqp/pom.xml b/spring-webflux-amqp/pom.xml index f9b14eea06..7a7f6ef600 100755 --- a/spring-webflux-amqp/pom.xml +++ b/spring-webflux-amqp/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung.spring + com.baeldung.spring spring-webflux-amqp 1.0.0-SNAPSHOT spring-webflux-amqp diff --git a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/AmqpReactiveController.java b/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/AmqpReactiveController.java similarity index 94% rename from spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/AmqpReactiveController.java rename to spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/AmqpReactiveController.java index 52f6d924fa..b71c32bd05 100644 --- a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/AmqpReactiveController.java +++ b/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/AmqpReactiveController.java @@ -1,11 +1,9 @@ -package org.baeldung.spring.amqp; +package com.baeldung.spring.amqp; import java.time.Duration; -import java.util.Date; import javax.annotation.PostConstruct; -import org.baeldung.spring.amqp.DestinationsConfig.DestinationInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.AmqpAdmin; @@ -29,7 +27,6 @@ import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; @RestController public class AmqpReactiveController { @@ -105,7 +102,7 @@ public class AmqpReactiveController { public Mono> sendMessageToQueue(@PathVariable String name, @RequestBody String payload) { // Lookup exchange details - final DestinationInfo d = destinationsConfig.getQueues() + final DestinationsConfig.DestinationInfo d = destinationsConfig.getQueues() .get(name); if (d == null) { @@ -135,7 +132,7 @@ public class AmqpReactiveController { @GetMapping(value = "/queue/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux receiveMessagesFromQueue(@PathVariable String name) { - DestinationInfo d = destinationsConfig.getQueues() + DestinationsConfig.DestinationInfo d = destinationsConfig.getQueues() .get(name); if (d == null) { @@ -201,7 +198,7 @@ public class AmqpReactiveController { public Mono> sendMessageToTopic(@PathVariable String name, @RequestBody String payload) { // Lookup exchange details - final DestinationInfo d = destinationsConfig.getTopics() + final DestinationsConfig.DestinationInfo d = destinationsConfig.getTopics() .get(name); if (d == null) { // Destination not found. @@ -223,7 +220,7 @@ public class AmqpReactiveController { @GetMapping(value = "/topic/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux receiveMessagesFromTopic(@PathVariable String name) { - DestinationInfo d = destinationsConfig.getTopics() + DestinationsConfig.DestinationInfo d = destinationsConfig.getTopics() .get(name); if (d == null) { @@ -281,7 +278,7 @@ public class AmqpReactiveController { } - private Queue createTopicQueue(DestinationInfo destination) { + private Queue createTopicQueue(DestinationsConfig.DestinationInfo destination) { Exchange ex = ExchangeBuilder.topicExchange(destination.getExchange()) .durable(true) diff --git a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/DestinationsConfig.java b/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/DestinationsConfig.java old mode 100755 new mode 100644 similarity index 93% rename from spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/DestinationsConfig.java rename to spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/DestinationsConfig.java index 410b87c764..0f9a0d890f --- a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/DestinationsConfig.java +++ b/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/DestinationsConfig.java @@ -1,59 +1,59 @@ -package org.baeldung.spring.amqp; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties("destinations") -public class DestinationsConfig { - - - private Map queues = new HashMap<>(); - - private Map topics = new HashMap<>(); - - - - public Map getQueues() { - return queues; - } - - public void setQueues(Map queues) { - this.queues = queues; - } - - public Map getTopics() { - return topics; - } - - public void setTopics(Map topics) { - this.topics = topics; - } - - // DestinationInfo stores the Exchange name and routing key used - // by our producers when posting messages - static class DestinationInfo { - - private String exchange; - private String routingKey; - - - public String getExchange() { - return exchange; - } - public void setExchange(String exchange) { - this.exchange = exchange; - } - public String getRoutingKey() { - return routingKey; - } - public void setRoutingKey(String routingKey) { - this.routingKey = routingKey; - } - - - - } - -} +package com.baeldung.spring.amqp; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties("destinations") +public class DestinationsConfig { + + + private Map queues = new HashMap<>(); + + private Map topics = new HashMap<>(); + + + + public Map getQueues() { + return queues; + } + + public void setQueues(Map queues) { + this.queues = queues; + } + + public Map getTopics() { + return topics; + } + + public void setTopics(Map topics) { + this.topics = topics; + } + + // DestinationInfo stores the Exchange name and routing key used + // by our producers when posting messages + static class DestinationInfo { + + private String exchange; + private String routingKey; + + + public String getExchange() { + return exchange; + } + public void setExchange(String exchange) { + this.exchange = exchange; + } + public String getRoutingKey() { + return routingKey; + } + public void setRoutingKey(String routingKey) { + this.routingKey = routingKey; + } + + + + } + +} diff --git a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/MessageListenerContainerFactory.java b/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/MessageListenerContainerFactory.java similarity index 96% rename from spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/MessageListenerContainerFactory.java rename to spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/MessageListenerContainerFactory.java index 29b8d28a80..d868e6afa8 100644 --- a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/MessageListenerContainerFactory.java +++ b/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/MessageListenerContainerFactory.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.amqp; +package com.baeldung.spring.amqp; import org.springframework.amqp.core.AcknowledgeMode; import org.springframework.amqp.rabbit.connection.ConnectionFactory; diff --git a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java b/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java old mode 100755 new mode 100644 similarity index 97% rename from spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java rename to spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java index 8a31299333..d6a7a84d30 --- a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java +++ b/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.amqp; +package com.baeldung.spring.amqp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-webflux-amqp/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-webflux-amqp/src/test/java/com/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..c443042d3d --- /dev/null +++ b/spring-webflux-amqp/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -0,0 +1,25 @@ +package com.baeldung; + +import com.baeldung.spring.amqp.SpringWebfluxAmqpApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * This live test requires: + * rabbitmq instance running on the environment + * + *
+ * To run rabbitmq using docker image: + * (e.g. `docker run -d --name rabbitmq -p 5672:5672 rabbitmq:3`) + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringWebfluxAmqpApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-webflux-amqp/src/test/java/org/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java b/spring-webflux-amqp/src/test/java/com/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java old mode 100755 new mode 100644 similarity index 93% rename from spring-webflux-amqp/src/test/java/org/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java rename to spring-webflux-amqp/src/test/java/com/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java index bda490c189..81782ce575 --- a/spring-webflux-amqp/src/test/java/org/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java +++ b/spring-webflux-amqp/src/test/java/com/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.amqp; +package com.baeldung.spring.amqp; import org.junit.Test; import org.springframework.test.web.reactive.server.WebTestClient; diff --git a/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index 4d9f658cdc..0000000000 --- a/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.amqp.SpringWebfluxAmqpApplication; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * This live test requires: - * rabbitmq instance running on the environment - * - *
- * To run rabbitmq using docker image: - * (e.g. `docker run -d --name rabbitmq -p 5672:5672 rabbitmq:3`) - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringWebfluxAmqpApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-websockets/README.md b/spring-websockets/README.md new file mode 100644 index 0000000000..26e1c6db7c --- /dev/null +++ b/spring-websockets/README.md @@ -0,0 +1,7 @@ +## Spring WebSockets + +This module contains articles about Spring WebSockets. + +### Relevant articles +- [Intro to WebSockets with Spring](https://www.baeldung.com/websockets-spring) +- [A Quick Example of Spring Websockets’ @SendToUser Annotation](https://www.baeldung.com/spring-websockets-sendtouser) diff --git a/spring-websockets/pom.xml b/spring-websockets/pom.xml new file mode 100644 index 0000000000..ddfd512476 --- /dev/null +++ b/spring-websockets/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + spring-websockets + spring-websockets + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-websocket + + + com.google.code.gson + gson + + + + + spring-websockets + + + src/main/resources + true + + + + + diff --git a/spring-websockets/src/main/java/com/baeldung/SpringBootApp.java b/spring-websockets/src/main/java/com/baeldung/SpringBootApp.java new file mode 100644 index 0000000000..ea2a461dfc --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/SpringBootApp.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication +public class SpringBootApp extends SpringBootServletInitializer { + public static void main(String[] args) { + SpringApplication.run(SpringBootApp.class, args); + } +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketSendToUserConfig.java b/spring-websockets/src/main/java/com/baeldung/sendtouser/WebSocketSendToUserConfig.java similarity index 98% rename from spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketSendToUserConfig.java rename to spring-websockets/src/main/java/com/baeldung/sendtouser/WebSocketSendToUserConfig.java index dbd52e20ba..76837d27f5 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketSendToUserConfig.java +++ b/spring-websockets/src/main/java/com/baeldung/sendtouser/WebSocketSendToUserConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.web.config; +package com.baeldung.sendtouser; import org.springframework.context.annotation.Configuration; import org.springframework.http.server.ServerHttpRequest; diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/WebsocketSendToUserController.java b/spring-websockets/src/main/java/com/baeldung/sendtouser/WebsocketSendToUserController.java similarity index 96% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/WebsocketSendToUserController.java rename to spring-websockets/src/main/java/com/baeldung/sendtouser/WebsocketSendToUserController.java index 4b55bcc00f..12475ad055 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/WebsocketSendToUserController.java +++ b/spring-websockets/src/main/java/com/baeldung/sendtouser/WebsocketSendToUserController.java @@ -1,15 +1,14 @@ -package com.baeldung.web.controller; - -import java.security.Principal; -import java.util.Map; +package com.baeldung.sendtouser; +import com.google.gson.Gson; 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; +import java.security.Principal; +import java.util.Map; @Controller public class WebsocketSendToUserController { diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ChatController.java b/spring-websockets/src/main/java/com/baeldung/websockets/ChatController.java similarity index 83% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/ChatController.java rename to spring-websockets/src/main/java/com/baeldung/websockets/ChatController.java index f4bed1950b..4ac78c2730 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ChatController.java +++ b/spring-websockets/src/main/java/com/baeldung/websockets/ChatController.java @@ -1,7 +1,5 @@ -package com.baeldung.web.controller; +package com.baeldung.websockets; -import com.baeldung.model.Message; -import com.baeldung.model.OutputMessage; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; diff --git a/spring-websockets/src/main/java/com/baeldung/websockets/Message.java b/spring-websockets/src/main/java/com/baeldung/websockets/Message.java new file mode 100644 index 0000000000..dd147a7bf5 --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/websockets/Message.java @@ -0,0 +1,15 @@ +package com.baeldung.websockets; + +public class Message { + + private String from; + private String text; + + public String getText() { + return text; + } + + public String getFrom() { + return from; + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java b/spring-websockets/src/main/java/com/baeldung/websockets/OutputMessage.java similarity index 93% rename from spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java rename to spring-websockets/src/main/java/com/baeldung/websockets/OutputMessage.java index 9aad564b1e..33d1f42743 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java +++ b/spring-websockets/src/main/java/com/baeldung/websockets/OutputMessage.java @@ -1,4 +1,4 @@ -package com.baeldung.model; +package com.baeldung.websockets; public class OutputMessage { diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java b/spring-websockets/src/main/java/com/baeldung/websockets/WebSocketConfig.java similarity index 95% rename from spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java rename to spring-websockets/src/main/java/com/baeldung/websockets/WebSocketConfig.java index 0793658e90..7b53dbc3f3 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java +++ b/spring-websockets/src/main/java/com/baeldung/websockets/WebSocketConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.web.config; +package com.baeldung.websockets; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; diff --git a/spring-mvc-java/src/main/webapp/resources/chat.html b/spring-websockets/src/main/webapp/resources/chat.html similarity index 96% rename from spring-mvc-java/src/main/webapp/resources/chat.html rename to spring-websockets/src/main/webapp/resources/chat.html index 92a54534fd..17c8494dd8 100644 --- a/spring-mvc-java/src/main/webapp/resources/chat.html +++ b/spring-websockets/src/main/webapp/resources/chat.html @@ -1,88 +1,88 @@ - - - Chat WebSocket - - - - - - - - - - -
- - -
- -
-
-
- - -
-
-
- - -

-
-
- - + + + Chat WebSocket + + + + + + + + + + +
+ + +
+ +
+
+
+ + +
+
+
+ + +

+
+
+ + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/resources/js/sockjs-0.3.4.js b/spring-websockets/src/main/webapp/resources/js/sockjs-0.3.4.js similarity index 100% rename from spring-mvc-java/src/main/webapp/resources/js/sockjs-0.3.4.js rename to spring-websockets/src/main/webapp/resources/js/sockjs-0.3.4.js diff --git a/spring-mvc-java/src/main/webapp/resources/js/stomp.js b/spring-websockets/src/main/webapp/resources/js/stomp.js similarity index 100% rename from spring-mvc-java/src/main/webapp/resources/js/stomp.js rename to spring-websockets/src/main/webapp/resources/js/stomp.js diff --git a/spring-mvc-java/src/main/webapp/resources/js/webSocketSendToUserApp.js b/spring-websockets/src/main/webapp/resources/js/webSocketSendToUserApp.js similarity index 100% rename from spring-mvc-java/src/main/webapp/resources/js/webSocketSendToUserApp.js rename to spring-websockets/src/main/webapp/resources/js/webSocketSendToUserApp.js diff --git a/stripe/pom.xml b/stripe/pom.xml index 07d2968f5f..48505c9e4e 100644 --- a/stripe/pom.xml +++ b/stripe/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -28,9 +28,6 @@ org.projectlombok lombok - ${lombok.version} - com.stripe diff --git a/stripe/src/main/java/com/baeldung/stripe/ChargeRequest.java b/stripe/src/main/java/com/baeldung/stripe/ChargeRequest.java index a5c056b659..190911afb3 100644 --- a/stripe/src/main/java/com/baeldung/stripe/ChargeRequest.java +++ b/stripe/src/main/java/com/baeldung/stripe/ChargeRequest.java @@ -13,4 +13,27 @@ public class ChargeRequest { private Currency currency; private String stripeEmail; private String stripeToken; + public String getDescription() { + return description; + } + public int getAmount() { + return amount; + } + public Currency getCurrency() { + return currency; + } + public String getStripeEmail() { + return stripeEmail; + } + public String getStripeToken() { + return stripeToken; + } + public void setDescription(String description) { + this.description = description; + } + public void setCurrency(Currency currency) { + this.currency = currency; + } + + } diff --git a/stripe/src/main/resources/application.properties b/stripe/src/main/resources/application.properties new file mode 100644 index 0000000000..f36df33897 --- /dev/null +++ b/stripe/src/main/resources/application.properties @@ -0,0 +1,2 @@ +STRIPE_SECRET_KEY= +STRIPE_PUBLIC_KEY= \ No newline at end of file diff --git a/stripe/src/main/resources/static/index.html b/stripe/src/main/resources/static/index.html index 090a01e91d..d7ba2bef91 100644 --- a/stripe/src/main/resources/static/index.html +++ b/stripe/src/main/resources/static/index.html @@ -1,7 +1,7 @@ - + diff --git a/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowGraph.java b/tensorflow-java/src/main/java/com/baeldung/tensorflow/TensorflowGraph.java similarity index 98% rename from tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowGraph.java rename to tensorflow-java/src/main/java/com/baeldung/tensorflow/TensorflowGraph.java index a44ef4c4ee..5d9a85a491 100644 --- a/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowGraph.java +++ b/tensorflow-java/src/main/java/com/baeldung/tensorflow/TensorflowGraph.java @@ -1,4 +1,4 @@ -package org.baeldung.tensorflow; +package com.baeldung.tensorflow; import org.tensorflow.DataType; import org.tensorflow.Graph; diff --git a/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowSavedModel.java b/tensorflow-java/src/main/java/com/baeldung/tensorflow/TensorflowSavedModel.java similarity index 93% rename from tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowSavedModel.java rename to tensorflow-java/src/main/java/com/baeldung/tensorflow/TensorflowSavedModel.java index 4259a787e8..96a063dff2 100644 --- a/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowSavedModel.java +++ b/tensorflow-java/src/main/java/com/baeldung/tensorflow/TensorflowSavedModel.java @@ -1,4 +1,4 @@ -package org.baeldung.tensorflow; +package com.baeldung.tensorflow; import org.tensorflow.SavedModelBundle; import org.tensorflow.Tensor; diff --git a/tensorflow-java/src/test/java/org/baeldung/tensorflow/TensorflowGraphUnitTest.java b/tensorflow-java/src/test/java/com/baeldung/tensorflow/TensorflowGraphUnitTest.java similarity index 92% rename from tensorflow-java/src/test/java/org/baeldung/tensorflow/TensorflowGraphUnitTest.java rename to tensorflow-java/src/test/java/com/baeldung/tensorflow/TensorflowGraphUnitTest.java index 51df6a4322..c2799a4bb1 100644 --- a/tensorflow-java/src/test/java/org/baeldung/tensorflow/TensorflowGraphUnitTest.java +++ b/tensorflow-java/src/test/java/com/baeldung/tensorflow/TensorflowGraphUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.tensorflow; +package com.baeldung.tensorflow; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/terraform/README.md b/terraform/README.md new file mode 100644 index 0000000000..19abd2ff20 --- /dev/null +++ b/terraform/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Terraform](https://www.baeldung.com/ops/terraform-intro) diff --git a/terraform/best-practices/README.md b/terraform/best-practices/README.md new file mode 100644 index 0000000000..fd488b1afb --- /dev/null +++ b/terraform/best-practices/README.md @@ -0,0 +1,10 @@ +# Terraform Sample Code + +This folder contains Terraform project samples that illustrates topics covered in the +"Best practices when using Terraform" article. Setup instructions are available in each sample's folder. + +List of available samples: + + * k8s-basic: "Hello world" project that just connects to a Kubernetes cluster and create a new namespace. + * ec2-basic: "Hello world" project that creates a single EC2 instance + * k8s-modules: A more elaborate sample that creates a simple set of services in a Kubernetes cluster diff --git a/terraform/best-practices/ec2-simple/.gitignore b/terraform/best-practices/ec2-simple/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/ec2-simple/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/ec2-simple/SETUP.md b/terraform/best-practices/ec2-simple/SETUP.md new file mode 100644 index 0000000000..3f906b6933 --- /dev/null +++ b/terraform/best-practices/ec2-simple/SETUP.md @@ -0,0 +1,23 @@ +# EC2 Basic Sample + +This Terraform sample project creates a single EC2 instance in the configured region. + +IMPORTANT NOTICE: In order to run this sample you must have an active AWS Account. As you probably know, creating resources on AWS +may result in additional charges in your bill. We recommend creating a test account to run this test as you can then use AWS's free tier +to play around. When finished, ALWAYS REMEMBER TO DESTROY YOUR RESOURCES !!! + +# Setup instructions + +1. Make sure you have a working AWS environment. Use a simple command such as _aws ec2 describe-instances_ and check its output. + If you get a list of existing EC2 instances, you're good to go. Otherwise, please refer to AWS documentation in order to setup your CLI. +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _aws ec2 describe-instances_. The output should list the newly creates EC2 instance +6. Run _terraform destroy_ to remove the previously creates namespace. + diff --git a/terraform/best-practices/ec2-simple/main.tf b/terraform/best-practices/ec2-simple/main.tf new file mode 100644 index 0000000000..57fb9d1757 --- /dev/null +++ b/terraform/best-practices/ec2-simple/main.tf @@ -0,0 +1,33 @@ +# +# Resource definitions +# + +data "aws_ami" "apache" { + filter { + name = "name" + values = [var.ami_name] + } + + filter { + name = "virtualization-type" + values = ["hvm"] + } + + owners = [var.ami_owner] + + most_recent = true +} + +resource "aws_instance" "web" { + ami = data.aws_ami.apache.id + instance_type = "t2.micro" + subnet_id = aws_subnet.frontend.id +} +resource "aws_subnet" "frontend" { + vpc_id = aws_vpc.apps.id + cidr_block = "10.0.1.0/24" +} + +resource "aws_vpc" "apps" { + cidr_block = "10.0.0.0/16" +} diff --git a/terraform/best-practices/ec2-simple/providers.tf b/terraform/best-practices/ec2-simple/providers.tf new file mode 100644 index 0000000000..fa5826b067 --- /dev/null +++ b/terraform/best-practices/ec2-simple/providers.tf @@ -0,0 +1,6 @@ +# +# Providers definitions +# +provider "aws" { + version = "~> 2.53" +} \ No newline at end of file diff --git a/terraform/best-practices/ec2-simple/variables.tf b/terraform/best-practices/ec2-simple/variables.tf new file mode 100644 index 0000000000..2a7fddcd33 --- /dev/null +++ b/terraform/best-practices/ec2-simple/variables.tf @@ -0,0 +1,15 @@ +# +# Variables +# + +variable "ami_name" { + type = string + description = "AMI name to use for our EC2 instance. Defaults to Ubuntu 18.04 (Bionic)" + default = "ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-*" +} + +variable "ami_owner" { + type = string + description = "AMI Owner ID to use for our EC2 instance. Defaults to 099720109477 (Canonical)" + default = "099720109477" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/.gitignore b/terraform/best-practices/k8s-basic/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/k8s-basic/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/k8s-basic/SETUP.md b/terraform/best-practices/k8s-basic/SETUP.md new file mode 100644 index 0000000000..35e690d88e --- /dev/null +++ b/terraform/best-practices/k8s-basic/SETUP.md @@ -0,0 +1,14 @@ +# Setup instructions + +1. Make sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. + If you get a list of nodes that contains at least one _ready_ module, you're good to go +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _kubectl get namespaces_. The output should now have a new "hello-terraform" namespace. +6. Run _terraform destroy_ to remove the previously creates namespace. diff --git a/terraform/best-practices/k8s-basic/main.tf b/terraform/best-practices/k8s-basic/main.tf new file mode 100644 index 0000000000..5eb3749930 --- /dev/null +++ b/terraform/best-practices/k8s-basic/main.tf @@ -0,0 +1,12 @@ +# +# Resource definitions +# + +resource "kubernetes_namespace" "hello" { + metadata { + labels = { + terraform = "true" + } + name = var.namespace_name + } +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/providers.tf b/terraform/best-practices/k8s-basic/providers.tf new file mode 100644 index 0000000000..385f857a11 --- /dev/null +++ b/terraform/best-practices/k8s-basic/providers.tf @@ -0,0 +1,6 @@ +# +# Providers definitions +# +provider "kubernetes" { + version = "~> 1.11" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/variables.tf b/terraform/best-practices/k8s-basic/variables.tf new file mode 100644 index 0000000000..b9217079bf --- /dev/null +++ b/terraform/best-practices/k8s-basic/variables.tf @@ -0,0 +1,9 @@ +# +# Variables +# + +variable "namespace_name" { + type = string + description = "Name to use for the created namespace" + default = "hello-terraform" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/.gitignore b/terraform/best-practices/k8s-modules/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/k8s-modules/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/k8s-modules/SETUP.md b/terraform/best-practices/k8s-modules/SETUP.md new file mode 100644 index 0000000000..f00247a293 --- /dev/null +++ b/terraform/best-practices/k8s-modules/SETUP.md @@ -0,0 +1,20 @@ +# Kubernetes multimodule sample + +This sample deploys two services behind a Kubernetes ingress. + +# Setup instructions + +1. Make sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. + If you get a list of nodes that contains at least one _ready_ module, you're good to go +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _kubectl get services_. The output should now have a few services. +6. Run _terraform destroy_ to remove the previously creates namespace. + + diff --git a/terraform/best-practices/k8s-modules/main.tf b/terraform/best-practices/k8s-modules/main.tf new file mode 100644 index 0000000000..86426b33db --- /dev/null +++ b/terraform/best-practices/k8s-modules/main.tf @@ -0,0 +1,27 @@ +/* + * Top-level definitions + */ + +//================================================================== Ingress + +module "ingress_www_petshop_com_br" { + source = "./modules/ingress/www.petshop.com.br" + ingress_host = "www.petshop.com.br" +} + +//================================================================== Deployments + +module "SvcCustomer" { + source = "./modules/SvcCustomer" +} + +module "SvcFeedback" { + source = "./modules/SvcFeedback" +} + + + + + + + diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf new file mode 100644 index 0000000000..1ca0c91545 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf @@ -0,0 +1,68 @@ +/* + * SvcCustomer deployment resources + */ + +resource "kubernetes_deployment" "SvcCustomer" { + + metadata { + name = "svccustomer" + labels = { + app = "SvcCustomer" + } + } + + spec { + replicas = 1 + + selector { + match_labels = { + app = "SvcCustomer" + } + } + + template { + metadata { + labels = { + app = "SvcCustomer" + } + } + + spec { + image_pull_secrets { + name = "docker-config" + } + + + container { + image = "inanimate/echo-server" + name = "svccustomer-httpd" + env { + name = "PORT" + value = "80" + } + } + } + } + } +} + +resource "kubernetes_service" "SvcCustomer" { + metadata { + name = "svccustomer" + } + + spec { + + selector = { + app = "SvcCustomer" + } + + session_affinity = "ClientIP" + port { + port = 80 + } + + //type = "LoadBalancer" + } + } + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf new file mode 100644 index 0000000000..8a37fdf375 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf @@ -0,0 +1,3 @@ +/* + * SvcCustomer output values + */ diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf new file mode 100644 index 0000000000..3dfcfcd264 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf @@ -0,0 +1,5 @@ +/* + * SvcCustomer deployment variables + */ + + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf new file mode 100644 index 0000000000..0f84c9163e --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf @@ -0,0 +1,69 @@ +/* + * SvcFeedback deployment resources + */ + +resource "kubernetes_deployment" "SvcFeedback" { + + metadata { + name = "svcfeedback" + labels = { + app = "SvcFeedback" + } + } + + spec { + replicas = 1 + + selector { + match_labels = { + app = "SvcFeedback" + } + } + + template { + metadata { + labels = { + app = "SvcFeedback" + } + } + + spec { + image_pull_secrets { + name = "docker-config" + } + + + container { + image = "inanimate/echo-server" + name = "svcfeedback-httpd" + env { + name = "PORT" + value = "80" + } + } + + } + } + } +} + +resource "kubernetes_service" "SvcFeedback" { + metadata { + name = "svcfeedback" + } + + spec { + + selector = { + app = "SvcFeedback" + } + + session_affinity = "ClientIP" + port { + port = 80 + } + + //type = "LoadBalancer" + } + } + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf new file mode 100644 index 0000000000..e08c17d4b4 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf @@ -0,0 +1,3 @@ +/* + * SvcFeedback output values + */ diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf new file mode 100644 index 0000000000..d8076d41a4 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf @@ -0,0 +1,5 @@ +/* + * SvcFeedback deployment variables + */ + + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf new file mode 100644 index 0000000000..0dbda48981 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf @@ -0,0 +1,41 @@ +/* + * Kubernetes Ingress module + */ +locals { + iname = var.ingress_name == "" ? join("-",["ingress",sha1(uuid())]) : var.ingress_name +} + +resource "kubernetes_ingress" "ingress" { + metadata { + name = local.iname + annotations = map( + "nginx.ingress.kubernetes.io/rewrite-target","/" + ) + } + spec { + rule { + http { + path { + backend { + service_name = "svccustomer" + service_port = 80 + } + path = "/customers" + } + path { + backend { + service_name = "svcfeedback" + service_port = 80 + } + path = "/feedback" + } + } + } +/* + tls { + secret_name = "tls-secret" + } +*/ + } +} + diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf new file mode 100644 index 0000000000..e604417b05 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf @@ -0,0 +1,5 @@ +/* + * Output variables + */ + + diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf new file mode 100644 index 0000000000..9b06128ec5 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf @@ -0,0 +1,20 @@ +/* + * Kubernetes Ingress module + */ + + +variable "ingress_name" { + type = string + description = "Ingress name. Defaults to a random name." + default = "" +} + +variable "ingress_host" { + type = string + description = "Ingress hostname" + default = "www.petshop.com.br" +} + + + + diff --git a/terraform/best-practices/k8s-modules/provider.tf b/terraform/best-practices/k8s-modules/provider.tf new file mode 100644 index 0000000000..bb90d66ecf --- /dev/null +++ b/terraform/best-practices/k8s-modules/provider.tf @@ -0,0 +1,13 @@ +# +# Provider configurations +# This file will *NOT* be overwriten upon regeneration, so it's safe +# to add your own customizations +# + +provider "kubernetes" { + version = "~> 1.10" +} + +provider "random" { + version = "~> 2.2" +} \ No newline at end of file diff --git a/terraform/hello-terraform/.gitignore b/terraform/hello-terraform/.gitignore new file mode 100644 index 0000000000..452502c50f --- /dev/null +++ b/terraform/hello-terraform/.gitignore @@ -0,0 +1,6 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform +hello.txt + diff --git a/terraform/hello-terraform/main.tf b/terraform/hello-terraform/main.tf new file mode 100644 index 0000000000..d6a726fa36 --- /dev/null +++ b/terraform/hello-terraform/main.tf @@ -0,0 +1,7 @@ +provider "local" { + version = "~> 1.4" +} +resource "local_file" "hello" { + content = "Hello, Terraform" + filename = "hello.txt" +} diff --git a/testing-modules/gatling/README.md b/testing-modules/gatling/README.md index 941ab75f06..7352479d1b 100644 --- a/testing-modules/gatling/README.md +++ b/testing-modules/gatling/README.md @@ -1,5 +1,6 @@ ### Relevant Articles: - [Intro to Gatling](http://www.baeldung.com/introduction-to-gatling) +- [Run Gatling Tests From Jenkins](https://www.baeldung.com/jenkins-run-gatling-tests) ### Running a simualtion - To run a simulation use "simulation" profile, command - `mvn install -Psimulation -Dgib.enabled=false` diff --git a/testing-modules/hamcrest/pom.xml b/testing-modules/hamcrest/pom.xml index cfd5bf5fac..ec9177d8f2 100644 --- a/testing-modules/hamcrest/pom.xml +++ b/testing-modules/hamcrest/pom.xml @@ -18,13 +18,13 @@ org.hamcrest java-hamcrest - ${hamcrest.version} + ${java-hamcrest.version} test - 2.0.0.0 + 2.0.0.0
diff --git a/testing-modules/junit-4/README.md b/testing-modules/junit-4/README.md index d19a0a1e47..6cc3981ed4 100644 --- a/testing-modules/junit-4/README.md +++ b/testing-modules/junit-4/README.md @@ -4,3 +4,4 @@ - [Custom JUnit 4 Test Runners](http://www.baeldung.com/junit-4-custom-runners) - [Introduction to JUnitParams](http://www.baeldung.com/junit-params) - [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java) +- [Introduction to Lambda Behave](https://www.baeldung.com/lambda-behave) diff --git a/testing-modules/junit5-annotations/README.md b/testing-modules/junit5-annotations/README.md index 02d4cd652a..bd51bb3d2d 100644 --- a/testing-modules/junit5-annotations/README.md +++ b/testing-modules/junit5-annotations/README.md @@ -7,3 +7,4 @@ This module contains articles about JUnit 5 Annotations - [JUnit 5 Conditional Test Execution with Annotations](https://www.baeldung.com/junit-5-conditional-test-execution) - [JUnit5 Programmatic Extension Registration with @RegisterExtension](https://www.baeldung.com/junit-5-registerextension-annotation) - [Guide to JUnit 5 Parameterized Tests](https://www.baeldung.com/parameterized-tests-junit-5) +- [Writing Templates for Test Cases Using JUnit 5](https://www.baeldung.com/junit5-test-templates) diff --git a/testing-modules/junit5-annotations/pom.xml b/testing-modules/junit5-annotations/pom.xml index 080844c30b..9e51d0ab55 100644 --- a/testing-modules/junit5-annotations/pom.xml +++ b/testing-modules/junit5-annotations/pom.xml @@ -46,12 +46,19 @@ ${junit.platform.version} test + + org.assertj + assertj-core + ${assertj-core.version} + test + - 5.4.2 - 1.4.2 + 5.6.2 + 1.6.0 2.8.2 + 3.11.1 diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java new file mode 100644 index 0000000000..f19adb13c8 --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java @@ -0,0 +1,5 @@ +package com.baeldung.junit5.templates; + +public interface UserIdGenerator { + String generate(String firstName, String lastName); +} diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java new file mode 100644 index 0000000000..b39b07bc4b --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java @@ -0,0 +1,15 @@ +package com.baeldung.junit5.templates; + +public class UserIdGeneratorImpl implements UserIdGenerator { + private boolean isFeatureEnabled; + + public UserIdGeneratorImpl(boolean isFeatureEnabled) { + this.isFeatureEnabled = isFeatureEnabled; + } + + public String generate(String firstName, String lastName) { + String initialAndLastName = firstName.substring(0, 1) + .concat(lastName); + return isFeatureEnabled ? "bael".concat(initialAndLastName) : initialAndLastName; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/conditional/ConditionalAnnotationsUnitTest.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/conditional/ConditionalAnnotationsUnitTest.java index ddceb78cac..ba840a1c33 100644 --- a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/conditional/ConditionalAnnotationsUnitTest.java +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/conditional/ConditionalAnnotationsUnitTest.java @@ -10,6 +10,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; public class ConditionalAnnotationsUnitTest { + @Test @EnabledOnOs({OS.WINDOWS, OS.MAC}) public void shouldRunBothWindowsAndMac() { @@ -28,6 +29,18 @@ public class ConditionalAnnotationsUnitTest { System.out.println("runs with java 10 and 11"); } + @Test + @EnabledForJreRange(min = JRE.JAVA_8, max = JRE.JAVA_13) + public void shouldOnlyRunOnJava8UntilJava13() { + System.out.println("runs with Java 8, 9, 10, 11, 12 and 13!"); + } + + @Test + @DisabledForJreRange(min = JRE.JAVA_14, max = JRE.JAVA_15) + public void shouldNotBeRunOnJava14AndJava15() { + System.out.println("Shouldn't be run on Java 14 and 15."); + } + @Test @DisabledOnJre(JRE.OTHER) public void thisTestOnlyRunsWithUpToDateJREs() { @@ -58,36 +71,38 @@ public class ConditionalAnnotationsUnitTest { System.out.println("will not run if environment variable LC_TIME is UTF-8"); } + // Commented codes are going to work prior JUnit 5.5 + @Test - @EnabledIf("'FR' == systemProperty.get('user.country')") + // @EnabledIf("'FR' == systemProperty.get('user.country')") public void onlyFrenchPeopleWillRunThisMethod() { System.out.println("will run only if user.country is FR"); } @Test - @DisabledIf("java.lang.System.getProperty('os.name').toLowerCase().contains('mac')") + // @DisabledIf("java.lang.System.getProperty('os.name').toLowerCase().contains('mac')") public void shouldNotRunOnMacOS() { System.out.println("will not run if our os.name is mac"); } @Test - @EnabledIf(value = { - "load('nashorn:mozilla_compat.js')", - "importPackage(java.time)", - "", - "var thisMonth = LocalDate.now().getMonth().name()", - "var february = Month.FEBRUARY.name()", - "thisMonth.equals(february)" + /*@EnabledIf(value = { + "load('nashorn:mozilla_compat.js')", + "importPackage(java.time)", + "", + "var thisMonth = LocalDate.now().getMonth().name()", + "var february = Month.FEBRUARY.name()", + "thisMonth.equals(february)" }, - engine = "nashorn", - reason = "Self-fulfilling: {result}") + engine = "nashorn", + reason = "Self-fulfilling: {result}")*/ public void onlyRunsInFebruary() { System.out.println("this test only runs in February"); } @Test - @DisabledIf("systemEnvironment.get('XPC_SERVICE_NAME') != null " + - "&& systemEnvironment.get('XPC_SERVICE_NAME').contains('intellij')") + /*@DisabledIf("systemEnvironment.get('XPC_SERVICE_NAME') != null " + + "&& systemEnvironment.get('XPC_SERVICE_NAME').contains('intellij')")*/ public void notValidForIntelliJ() { System.out.println("this test will run if our ide is INTELLIJ"); } @@ -107,7 +122,7 @@ public class ConditionalAnnotationsUnitTest { @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) - @DisabledIf("Math.random() >= 0.5") + // @DisabledIf("Math.random() >= 0.5") @interface CoinToss { } diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java new file mode 100644 index 0000000000..cd8b7b677d --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java @@ -0,0 +1,27 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExecutionCondition; +import org.junit.jupiter.api.extension.ExtensionContext; + +import java.io.IOException; +import java.util.Properties; + +public class DisabledOnQAEnvironmentExtension implements ExecutionCondition { + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + Properties properties = new Properties(); + try { + properties.load(DisabledOnQAEnvironmentExtension.class.getClassLoader() + .getResourceAsStream("application.properties")); + if ("qa".equalsIgnoreCase(properties.getProperty("env"))) { + String reason = String.format("The test '%s' is disabled on QA environment", context.getDisplayName()); + System.out.println(reason); + return ConditionEvaluationResult.disabled(reason); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + return ConditionEvaluationResult.enabled("Test enabled"); + } +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java new file mode 100644 index 0000000000..76321be101 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java @@ -0,0 +1,26 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +public class GenericTypedParameterResolver implements ParameterResolver { + T data; + + public GenericTypedParameterResolver(T data) { + this.data = data; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + return parameterContext.getParameter() + .getType() + .isInstance(data); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + return data; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java new file mode 100644 index 0000000000..a2306154a6 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UserIdGeneratorImplUnitTest { + @TestTemplate + @ExtendWith(UserIdGeneratorTestInvocationContextProvider.class) + public void whenUserIdRequested_thenUserIdIsReturnedInCorrectFormat(UserIdGeneratorTestCase testCase) { + UserIdGenerator userIdGenerator = new UserIdGeneratorImpl(testCase.isFeatureEnabled()); + + String actualUserId = userIdGenerator.generate(testCase.getFirstName(), testCase.getLastName()); + + assertThat(actualUserId).isEqualTo(testCase.getExpectedUserId()); + } +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java new file mode 100644 index 0000000000..dd41dd5a27 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java @@ -0,0 +1,37 @@ +package com.baeldung.junit5.templates; + +public class UserIdGeneratorTestCase { + private String displayName; + private boolean isFeatureEnabled; + private String firstName; + private String lastName; + private String expectedUserId; + + public UserIdGeneratorTestCase(String displayName, boolean isFeatureEnabled, String firstName, String lastName, String expectedUserId) { + this.displayName = displayName; + this.isFeatureEnabled = isFeatureEnabled; + this.firstName = firstName; + this.lastName = lastName; + this.expectedUserId = expectedUserId; + } + + public String getDisplayName() { + return displayName; + } + + public boolean isFeatureEnabled() { + return isFeatureEnabled; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public String getExpectedUserId() { + return expectedUserId; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java new file mode 100644 index 0000000000..277ec03f05 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java @@ -0,0 +1,87 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.*; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class UserIdGeneratorTestInvocationContextProvider implements TestTemplateInvocationContextProvider { + + @Override + public boolean supportsTestTemplate(ExtensionContext extensionContext) { + return true; + } + + @Override + public Stream provideTestTemplateInvocationContexts(ExtensionContext extensionContext) { + boolean featureDisabled = false; + boolean featureEnabled = true; + return Stream.of( + featureDisabledContext( + new UserIdGeneratorTestCase( + "Given feature switch disabled When user name is John Smith Then generated userid is JSmith", + featureDisabled, "John", "Smith", "JSmith")), + featureEnabledContext( + new UserIdGeneratorTestCase( + "Given feature switch enabled When user name is John Smith Then generated userid is baelJSmith", + featureEnabled, "John", "Smith", "baelJSmith")) + ); + } + + private TestTemplateInvocationContext featureDisabledContext(UserIdGeneratorTestCase userIdGeneratorTestCase) { + return new TestTemplateInvocationContext() { + @Override + public String getDisplayName(int invocationIndex) { + return userIdGeneratorTestCase.getDisplayName(); + } + + @Override + public List getAdditionalExtensions() { + return asList( + new GenericTypedParameterResolver(userIdGeneratorTestCase), + new BeforeTestExecutionCallback() { + @Override + public void beforeTestExecution(ExtensionContext extensionContext) { + System.out.println("BeforeTestExecutionCallback:Disabled context"); + } + }, + new AfterTestExecutionCallback() { + @Override + public void afterTestExecution(ExtensionContext extensionContext) { + System.out.println("AfterTestExecutionCallback:Disabled context"); + } + }); + } + }; + } + + private TestTemplateInvocationContext featureEnabledContext(UserIdGeneratorTestCase userIdGeneratorTestCase) { + return new TestTemplateInvocationContext() { + @Override + public String getDisplayName(int invocationIndex) { + return userIdGeneratorTestCase.getDisplayName(); + } + + @Override + public List getAdditionalExtensions() { + return asList( + new GenericTypedParameterResolver(userIdGeneratorTestCase), + new DisabledOnQAEnvironmentExtension(), + new BeforeEachCallback() { + @Override + public void beforeEach(ExtensionContext extensionContext) { + System.out.println("BeforeEachCallback:Enabled context"); + } + }, + new AfterEachCallback() { + @Override + public void afterEach(ExtensionContext extensionContext) { + System.out.println("AfterEachCallback:Enabled context"); + } + }); + } + }; + } +} diff --git a/testing-modules/junit5-annotations/src/test/resources/application.properties b/testing-modules/junit5-annotations/src/test/resources/application.properties new file mode 100644 index 0000000000..bbfa14d866 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/resources/application.properties @@ -0,0 +1 @@ +env=qa \ No newline at end of file diff --git a/testing-modules/junit5-migration/README.md b/testing-modules/junit5-migration/README.md index 84e540b466..5cc9db8bd3 100644 --- a/testing-modules/junit5-migration/README.md +++ b/testing-modules/junit5-migration/README.md @@ -5,6 +5,6 @@ This module contains articles about migrating to JUnit 5. The code for the JUnit 4 - JUnit 5 E-book is in `com.baeldung.junit4` and `com.baeldung.junit5`. ### Relevant Articles: -- [JUnit 5 Migration](https://www.baeldung.com/junit-5-migration) + - [A Quick JUnit vs TestNG Comparison](https://www.baeldung.com/junit-vs-testng) - [Assertions in JUnit 4 and JUnit 5](https://www.baeldung.com/junit-assertions) diff --git a/testing-modules/mockito-2/README.md b/testing-modules/mockito-2/README.md index 1d1bd6af7c..329228186f 100644 --- a/testing-modules/mockito-2/README.md +++ b/testing-modules/mockito-2/README.md @@ -3,5 +3,6 @@ - [Mockito’s Java 8 Features](https://www.baeldung.com/mockito-2-java-8) - [Lazy Verification with Mockito 2](https://www.baeldung.com/mockito-2-lazy-verification) - [Mockito Strict Stubbing and The UnnecessaryStubbingException](https://www.baeldung.com/mockito-unnecessary-stubbing-exception) -- [Quick Guide to BDDMockito](https://www.baeldung.com/bdd-mockito) -- [Mockito – Using Spies](https://www.baeldung.com/mockito-spy) +- [Mockito and Fluent APIs](https://www.baeldung.com/mockito-fluent-apis) +- [Mocking the ObjectMapper readValue() Method](https://www.baeldung.com/mockito-mock-jackson-read-value) +- [Introduction to Mockito’s AdditionalAnswers](https://www.baeldung.com/mockito-additionalanswers) diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index 76608a3039..340af89c82 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -14,8 +14,23 @@ ../../ + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + org.mockito + mockito-junit-jupiter + ${mockito.version} + test + + + 2.21.0 + 2.10.3 diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/Book.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/Book.java new file mode 100644 index 0000000000..fa021f8cba --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/Book.java @@ -0,0 +1,58 @@ +package com.baeldung.mockito.additionalanswers; + +public class Book { + + private Long bookId; + + private String title; + + private String author; + + private int numberOfPages; + + public Book(String title, String author, int numberOfPages) { + this.title = title; + this.author = author; + this.numberOfPages = numberOfPages; + } + + public Book(Long bookId, String title, String author, int numberOfPages) { + this.bookId = bookId; + this.title = title; + this.author = author; + this.numberOfPages = numberOfPages; + } + + public Long getBookId() { + return bookId; + } + + public void setBookId(Long bookId) { + this.bookId = bookId; + } + + 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 int getNumberOfPages() { + return numberOfPages; + } + + public void setNumberOfPages(int numberOfPages) { + this.numberOfPages = numberOfPages; + } +} + diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java new file mode 100644 index 0000000000..677ee502b4 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java @@ -0,0 +1,24 @@ +package com.baeldung.mockito.additionalanswers; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class BookRepository { + public Book getByBookId(Long bookId) { + return new Book(bookId, "To Kill a Mocking Bird", "Harper Lee", 256); + } + + public Book save(Book book) { + return new Book(book.getBookId(), book.getTitle(), book.getAuthor(), book.getNumberOfPages()); + } + + public Book selectRandomBook(Book bookOne, Book bookTwo, Book bookThree) { + List selection = new ArrayList<>(); + selection.add(bookOne); + selection.add(bookTwo); + selection.add(bookThree); + Random random = new Random(); + return selection.get(random.nextInt(selection.size())); + } +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java new file mode 100644 index 0000000000..4499a6524b --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java @@ -0,0 +1,22 @@ +package com.baeldung.mockito.additionalanswers; + +public class BookService { + private final BookRepository bookRepository; + + public BookService(BookRepository bookRepository) { + this.bookRepository = bookRepository; + } + + public Book getByBookId(Long id) { + return bookRepository.getByBookId(id); + } + + public Book save(Book book) { + return bookRepository.save(book); + } + + public Book selectRandomBook(Book book1, Book book2, Book book3) { + return bookRepository.selectRandomBook(book1, book2, book3); + } +} + diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/Flower.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/Flower.java new file mode 100644 index 0000000000..bc366a39f9 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/Flower.java @@ -0,0 +1,32 @@ +package com.baeldung.mockito.objectmapper; + +public class Flower { + + private String name; + private Integer petals; + + public Flower(String name, Integer petals) { + this.name = name; + this.petals = petals; + } + + public Flower() { + } + + 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/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidator.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidator.java new file mode 100644 index 0000000000..91bad66e6d --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidator.java @@ -0,0 +1,17 @@ +package com.baeldung.mockito.objectmapper; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class FlowerJsonStringValidator { + private ObjectMapper objectMapper; + + public FlowerJsonStringValidator(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + public boolean flowerHasPetals(String jsonFlowerAsString) throws JsonProcessingException { + Flower flower = objectMapper.readValue(jsonFlowerAsString, Flower.class); + return flower.getPetals() > 0; + } +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java new file mode 100644 index 0000000000..ee32bcf70c --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.mockito.additionalanswers; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.AdditionalAnswers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; + +@RunWith(MockitoJUnitRunner.class) +public class BookServiceUnitTest { + @InjectMocks + private BookService bookService; + + @Mock + private BookRepository bookRepository; + + @Test + public void givenSaveMethodMocked_whenSaveInvoked_ThenReturnFirstArgument_UnitTest() { + Book book = new Book("To Kill a Mocking Bird", "Harper Lee", 256); + Mockito.when(bookRepository.save(any(Book.class))).then(AdditionalAnswers.returnsFirstArg()); + + Book savedBook = bookService.save(book); + + assertEquals(savedBook, book); + } + + @Test + public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnSecondArgument_UnitTest() { + Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456); + Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); + Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); + + Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsSecondArg()); + + Book secondBook = bookService.selectRandomBook(book1, book2, book3); + + assertEquals(secondBook, book2); + } + + @Test + public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnLastArgument_UnitTest() { + Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456); + Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); + Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); + + Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsLastArg()); + + Book lastBook = bookService.selectRandomBook(book1, book2, book3); + assertEquals(lastBook, book3); + } + + @Test + public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnArgumentAtIndex_UnitTest() { + Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456); + Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); + Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); + + Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsArgAt(1)); + + Book bookOnIndex = bookService.selectRandomBook(book1, book2, book3); + + assertEquals(bookOnIndex, book2); + } +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidatorUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidatorUnitTest.java new file mode 100644 index 0000000000..31c3f0d01d --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidatorUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.mockito.objectmapper; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class FlowerJsonStringValidatorUnitTest { + + @Mock + private ObjectMapper objectMapper; + + private FlowerJsonStringValidator flowerJsonStringValidator; + + @BeforeEach + public void setUp() { + flowerJsonStringValidator = new FlowerJsonStringValidator(objectMapper); + } + + @Test + public void whenCallingHasPetalsWithPetals_thenReturnsTrue() throws JsonProcessingException { + Flower rose = new Flower("testFlower", 100); + + when(objectMapper.readValue(anyString(), eq(Flower.class))).thenReturn(rose); + + assertTrue(flowerJsonStringValidator.flowerHasPetals("this can be a very long json flower")); + + verify(objectMapper, times(1)).readValue(anyString(), eq(Flower.class)); + } + + @Test + public void whenCallingHasPetalsWithZeroPetal_thenReturnsFalse() throws JsonProcessingException { + Flower rose = new Flower("testFlowerWithoutPetal", 0); + + when(objectMapper.readValue(anyString(), eq(Flower.class))).thenReturn(rose); + + assertFalse(flowerJsonStringValidator.flowerHasPetals("this can be a very long json flower")); + + verify(objectMapper, times(1)).readValue(anyString(), eq(Flower.class)); + } +} diff --git a/testing-modules/mockito/README.md b/testing-modules/mockito/README.md index 7cef9ee8f6..5f307c2f0b 100644 --- a/testing-modules/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -8,8 +8,6 @@ - [Mockito When/Then Cookbook](https://www.baeldung.com/mockito-behavior) - [Getting Started with Mockito @Mock, @Spy, @Captor and @InjectMocks](https://www.baeldung.com/mockito-annotations) - [Mockito’s Mock Methods](https://www.baeldung.com/mockito-mock-methods) -- [Introduction to PowerMock](https://www.baeldung.com/intro-to-powermock) -- [Mocking of Private Methods Using PowerMock](https://www.baeldung.com/powermock-private-method) - [Mocking Exception Throwing using Mockito](https://www.baeldung.com/mockito-exceptions) - [Mocking Void Methods with Mockito](https://www.baeldung.com/mockito-void-methods) - [Mock Final Classes and Methods with Mockito](https://www.baeldung.com/mockito-final) diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index 0fb11d23ab..ea5ef4c322 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -44,19 +44,6 @@ - - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.version} - test - org.springframework.boot spring-boot-starter @@ -90,7 +77,6 @@ 2.0.2 - 2.0.0.0 2.1.1 diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java index 731183bae2..27e3258efb 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java @@ -75,7 +75,53 @@ public class MockitoAnnotationUnitTest { Mockito.doReturn(100).when(spiedList).size(); assertEquals(100, spiedList.size()); } + + @Test + public void whenSpyingOnList_thenCorrect() { + List list = new ArrayList(); + List spyList = Mockito.spy(list); + + spyList.add("one"); + spyList.add("two"); + + Mockito.verify(spyList).add("one"); + Mockito.verify(spyList).add("two"); + + assertEquals(2, spyList.size()); + } + @Test + public void whenUsingTheSpyAnnotation_thenObjectIsSpied() { + spiedList.add("one"); + spiedList.add("two"); + + Mockito.verify(spiedList).add("one"); + Mockito.verify(spiedList).add("two"); + + assertEquals(2, spiedList.size()); + } + + @Test + public void whenStubASpy_thenStubbed() { + List list = new ArrayList(); + List spyList = Mockito.spy(list); + + assertEquals(0, spyList.size()); + + Mockito.doReturn(100).when(spyList).size(); + assertEquals(100, spyList.size()); + } + + @Test + public void whenCreateSpy_thenCreate() { + List spyList = Mockito.spy(new ArrayList<>()); + + spyList.add("one"); + Mockito.verify(spyList).add("one"); + + assertEquals(1, spyList.size()); + } + @Test public void whenNotUseCaptorAnnotation_thenCorrect() { final List mockList = Mockito.mock(List.class); diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java new file mode 100644 index 0000000000..ed50732183 --- /dev/null +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.mockito; + +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; + +import java.util.List; + +public class MockitoAnnotationsUninitializedUnitTest { + + @Mock + List mockedList; + + @Test(expected = NullPointerException.class) + public void whenMockitoAnnotationsUninitialized_thenNPEThrown() { + Mockito.when(mockedList.size()).thenReturn(1); + } +} diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java index dd41d98b57..9dd98f184b 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java @@ -16,48 +16,51 @@ public class MockitoVoidMethodsUnitTest { @Test public void whenAddCalledVerified() { - MyList mockVoid = mock(MyList.class); - mockVoid.add(0, ""); - verify(mockVoid, times(1)).add(0, ""); + MyList myList = mock(MyList.class); + myList.add(0, ""); + + verify(myList, 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); + MyList myList = mock(MyList.class); + doThrow().when(myList).add(isA(Integer.class), isNull()); + + myList.add(0, null); } @Test public void whenAddCalledValueCaptured() { - MyList mockVoid = mock(MyList.class); + MyList myList = mock(MyList.class); ArgumentCaptor valueCapture = ArgumentCaptor.forClass(String.class); - doNothing().when(mockVoid).add(any(Integer.class), valueCapture.capture()); - mockVoid.add(0, "captured"); + doNothing().when(myList).add(any(Integer.class), valueCapture.capture()); + myList.add(0, "captured"); + assertEquals("captured", valueCapture.getValue()); } @Test public void whenAddCalledAnswered() { - MyList mockVoid = mock(MyList.class); - doAnswer((Answer) invocation -> { + MyList myList = mock(MyList.class); + doAnswer(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"); + }).when(myList).add(any(Integer.class), any(String.class)); + myList.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"); + MyList myList = mock(MyList.class); + doCallRealMethod().when(myList).add(any(Integer.class), any(String.class)); + myList.add(1, "real"); + + verify(myList, times(1)).add(1, "real"); } } diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java b/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java index 799e7721e0..1aafa28a6a 100644 --- a/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java +++ b/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java @@ -15,5 +15,5 @@ public interface ExpectationsCollaborator { void methodForArgThat(Object o); String methodReturnsString(); int methodReturnsInt(); - Object methodForDelegate(int i); + int methodForDelegate(int i); } diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java index 8b0c3ab4ec..1ff90111d1 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java @@ -1,21 +1,21 @@ package com.baeldung.jmockit; -import com.baeldung.jmockit.ExpectationsCollaborator; -import com.baeldung.jmockit.Model; -import mockit.Delegate; -import mockit.Expectations; -import mockit.Mocked; -import mockit.Verifications; -import mockit.integration.junit4.JMockit; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Test; import org.junit.runner.RunWith; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; +import mockit.Delegate; +import mockit.Expectations; +import mockit.Mocked; +import mockit.Verifications; +import mockit.integration.junit4.JMockit; @RunWith(JMockit.class) @SuppressWarnings("unchecked") @@ -112,17 +112,16 @@ public class ExpectationsIntegrationTest { result = "foo"; result = new Exception(); result = "bar"; - mock.methodReturnsInt(); - result = new int[]{1, 2, 3}; - mock.methodReturnsString(); returns("foo", "bar"); mock.methodReturnsInt(); + result = new int[]{1, 2, 3}; result = 1; }}; assertEquals("Should return foo", "foo", mock.methodReturnsString()); try { mock.methodReturnsString(); + fail("Shouldn't reach here"); } catch (Exception e) { // NOOP } @@ -134,13 +133,14 @@ public class ExpectationsIntegrationTest { assertEquals("Should return bar", "bar", mock.methodReturnsString()); assertEquals("Should return 1", 1, mock.methodReturnsInt()); } - + @Test public void testDelegate(@Mocked ExpectationsCollaborator mock) { new Expectations() {{ mock.methodForDelegate(anyInt); - result = new Delegate() { - public int delegate(int i) throws Exception { + + result = new Delegate() { + int delegate(int i) throws Exception { if (i < 3) { return 5; } else { @@ -153,6 +153,7 @@ public class ExpectationsIntegrationTest { assertEquals("Should return 5", 5, mock.methodForDelegate(1)); try { mock.methodForDelegate(3); + fail("Shouldn't reach here"); } catch (Exception e) { } } diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/LoginControllerIntegrationTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/LoginControllerIntegrationTest.java index 4dbe94991f..df3eeccca2 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/LoginControllerIntegrationTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/LoginControllerIntegrationTest.java @@ -130,30 +130,33 @@ public class LoginControllerIntegrationTest { }; } + @Test public void partialMocking() { - // use partial mock - final LoginService partialLoginService = new LoginService(); + LoginService partialLoginService = new LoginService(); partialLoginService.setLoginDao(loginDao); loginController.loginService = partialLoginService; - final UserForm userForm = new UserForm(); + UserForm userForm = new UserForm(); userForm.username = "foo"; - // let service's login use implementation so let's mock DAO call - new Expectations() {{ - loginDao.login(userForm); - result = 1; - // no expectation for loginService.login + + new Expectations(partialLoginService) {{ + // let's mock DAO call + loginDao.login(userForm); result = 1; + + // no expectation for login method so that real implementation is used + + // mock setCurrentUser call partialLoginService.setCurrentUser("foo"); }}; String login = loginController.login(userForm); Assert.assertEquals("OK", login); - // verify mocked call - new FullVerifications(partialLoginService) { - }; - new FullVerifications(loginDao) { - }; + // verify mocked call + new Verifications() {{ + partialLoginService.setCurrentUser("foo"); + }}; + } } diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index f4a8368581..b467b3c503 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -33,6 +33,7 @@ selenium-junit-testng spring-testing test-containers + testing-assertions testng junit-5-basics easymock @@ -40,6 +41,7 @@ xmlunit-2 junit-4 testing-libraries + powermock diff --git a/testing-modules/powermock/README.md b/testing-modules/powermock/README.md new file mode 100644 index 0000000000..df9fb0088c --- /dev/null +++ b/testing-modules/powermock/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Introduction to PowerMock](https://www.baeldung.com/intro-to-powermock) +- [Mocking of Private Methods Using PowerMock](https://www.baeldung.com/powermock-private-method) diff --git a/testing-modules/powermock/pom.xml b/testing-modules/powermock/pom.xml new file mode 100644 index 0000000000..21b2e98af0 --- /dev/null +++ b/testing-modules/powermock/pom.xml @@ -0,0 +1,33 @@ + + + + testing-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + powermock + + + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.version} + test + + + + + 2.21.0 + 2.0.2 + + \ No newline at end of file diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java similarity index 98% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java index 4943b0486a..1b2bb99896 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java +++ b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java @@ -68,7 +68,7 @@ public class PowerMockitoUnitTest { when(mock.finalMethod()).thenReturn("I am a final mock method."); returnValue = mock.finalMethod(); - verify(mock,times(3)).finalMethod(); + verify(mock).finalMethod(); assertEquals("I am a final mock method.", returnValue); when(mock, "privateMethod").thenReturn("I am a private mock method."); diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 74935bcf6f..0b027312d6 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -147,16 +147,6 @@ wiremock ${wiremock.version} - - com.github.fge - json-schema-validator - ${github-json-schema-validator.version} - - - com.github.fge - json-schema-core - ${json-schema-core.version} - commons-collections commons-collections @@ -208,12 +198,6 @@ 2.4.7 2.4.1 - 2.2.6 - 1.2.5 - - 3.0.1 - 3.0.1 - 2.5.3 diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java index 805d67271d..c579f1c260 100644 --- a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java @@ -17,8 +17,7 @@ import static io.restassured.RestAssured.with; import static org.hamcrest.Matchers.hasItems; public class RestAssured2IntegrationTest { - private static final int PORT = 8084; - private static WireMockServer wireMockServer = new WireMockServer(PORT); + private static WireMockServer wireMockServer; private static final String EVENTS_PATH = "/odds"; private static final String APPLICATION_JSON = "application/json"; @@ -27,9 +26,11 @@ public class RestAssured2IntegrationTest { @BeforeClass public static void before() throws Exception { System.out.println("Setting up!"); + final int port = Util.getAvailablePort(); + wireMockServer = new WireMockServer(port); wireMockServer.start(); - configureFor("localhost", PORT); - RestAssured.port = PORT; + configureFor("localhost", port); + RestAssured.port = port; stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( aResponse().withStatus(200) .withHeader("Content-Type", APPLICATION_JSON) diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java index 4ad3cea22c..e4279897e2 100644 --- a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java @@ -21,8 +21,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItems; public class RestAssuredIntegrationTest { - private static final int PORT = 8083; - private static WireMockServer wireMockServer = new WireMockServer(PORT); + private static WireMockServer wireMockServer; private static final String EVENTS_PATH = "/events?id=390"; private static final String APPLICATION_JSON = "application/json"; @@ -31,9 +30,11 @@ public class RestAssuredIntegrationTest { @BeforeClass public static void before() throws Exception { System.out.println("Setting up!"); + final int port = Util.getAvailablePort(); + wireMockServer = new WireMockServer(port); wireMockServer.start(); - RestAssured.port = PORT; - configureFor("localhost", PORT); + RestAssured.port = port; + configureFor("localhost", port); stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( aResponse().withStatus(200) .withHeader("Content-Type", APPLICATION_JSON) diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java index 4a29d8832f..f71cce603c 100644 --- a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java @@ -12,11 +12,11 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static io.restassured.RestAssured.get; +import static io.restassured.RestAssured.port; import static org.hamcrest.Matchers.hasItems; public class RestAssuredXML2IntegrationTest { - private static final int PORT = 8082; - private static WireMockServer wireMockServer = new WireMockServer(PORT); + private static WireMockServer wireMockServer; private static final String EVENTS_PATH = "/teachers"; private static final String APPLICATION_XML = "application/xml"; @@ -25,9 +25,11 @@ public class RestAssuredXML2IntegrationTest { @BeforeClass public static void before() throws Exception { System.out.println("Setting up!"); + final int port = Util.getAvailablePort(); + wireMockServer = new WireMockServer(port); wireMockServer.start(); - RestAssured.port = PORT; - configureFor("localhost", PORT); + RestAssured.port = port; + configureFor("localhost", port); stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( aResponse().withStatus(200) .withHeader("Content-Type", APPLICATION_XML) diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java index f1a22831f4..082dace526 100644 --- a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java @@ -17,8 +17,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.xml.HasXPath.hasXPath; public class RestAssuredXMLIntegrationTest { - private static final int PORT = 8081; - private static WireMockServer wireMockServer = new WireMockServer(PORT); + private static WireMockServer wireMockServer; private static final String EVENTS_PATH = "/employees"; private static final String APPLICATION_XML = "application/xml"; @@ -27,9 +26,11 @@ public class RestAssuredXMLIntegrationTest { @BeforeClass public static void before() throws Exception { System.out.println("Setting up!"); + final int port = Util.getAvailablePort(); + wireMockServer = new WireMockServer(port); wireMockServer.start(); - configureFor("localhost", PORT); - RestAssured.port = PORT; + configureFor("localhost", port); + RestAssured.port = port; stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn( aResponse().withStatus(200) .withHeader("Content-Type", APPLICATION_XML) diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/Util.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/Util.java index 02dec87927..70c595f562 100644 --- a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/Util.java +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/Util.java @@ -1,10 +1,15 @@ package com.baeldung.restassured; +import java.io.IOException; import java.io.InputStream; +import java.net.ServerSocket; +import java.util.Random; import java.util.Scanner; final class Util { + private static final int DEFAULT_PORT = 8069; + private Util() { } @@ -12,4 +17,22 @@ final class Util { Scanner s = new Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } + + static int getAvailablePort() { + return new Random() + .ints(6000, 9000) + .filter(Util::isFree) + .findFirst() + .orElse(DEFAULT_PORT); + } + + + private static boolean isFree(int port) { + try { + new ServerSocket(port).close(); + return true; + } catch (IOException e) { + return false; + } + } } diff --git a/testing-modules/selenium-junit-testng/README.md b/testing-modules/selenium-junit-testng/README.md index 0137212290..198247d7bf 100644 --- a/testing-modules/selenium-junit-testng/README.md +++ b/testing-modules/selenium-junit-testng/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng) - [Testing with Selenium/WebDriver and the Page Object Pattern](http://www.baeldung.com/selenium-webdriver-page-object) +- [Using Cookies With Selenium WebDriver in Java](https://www.baeldung.com/java-selenium-webdriver-cookies) diff --git a/testing-modules/selenium-junit-testng/pom.xml b/testing-modules/selenium-junit-testng/pom.xml index 0616cdaa29..3734bf72c9 100644 --- a/testing-modules/selenium-junit-testng/pom.xml +++ b/testing-modules/selenium-junit-testng/pom.xml @@ -38,7 +38,7 @@ org.hamcrest hamcrest-all - ${org.hamcrest.version} + ${hamcrest-all.version} @@ -71,4 +71,4 @@ 3.4.0 - \ No newline at end of file + diff --git a/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumCookiesJUnitLiveTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumCookiesJUnitLiveTest.java new file mode 100644 index 0000000000..0cbbf52454 --- /dev/null +++ b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumCookiesJUnitLiveTest.java @@ -0,0 +1,110 @@ +package test.java.com.baeldung.selenium.junit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openqa.selenium.Capabilities; +import org.openqa.selenium.Cookie; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.remote.DesiredCapabilities; + +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +public class SeleniumCookiesJUnitLiveTest { + + private WebDriver driver; + private String navUrl; + + @Before + public void setUp() { + Capabilities capabilities = DesiredCapabilities.firefox(); + driver = new FirefoxDriver(capabilities); + navUrl = "https://baeldung.com"; + driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); + System.setProperty("webdriver.gecko.driver", "geckodriver.exe"); + } + + @After + public void teardown() { + driver.quit(); + } + + @Test + public void whenNavigate_thenCookiesExist() { + driver.navigate().to(navUrl); + Set cookies = driver.manage().getCookies(); + + assertThat(cookies, is(not(empty()))); + } + + @Test + public void whenNavigate_thenLpCookieExists() { + driver.navigate().to(navUrl); + Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(lpCookie, is(not(nullValue()))); + } + + @Test + public void whenNavigate_thenLpCookieIsHasCorrectValue() { + driver.navigate().to(navUrl); + Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(lpCookie.getValue(), containsString("www.baeldung.com")); + } + + @Test + public void whenNavigate_thenLpCookieHasCorrectProps() { + driver.navigate().to(navUrl); + Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(lpCookie.getDomain(), equalTo(".baeldung.com")); + assertThat(lpCookie.getPath(), equalTo("/")); + assertThat(lpCookie.getExpiry(), is(not(nullValue()))); + assertThat(lpCookie.isSecure(), equalTo(false)); + assertThat(lpCookie.isHttpOnly(), equalTo(false)); + } + + @Test + public void whenAddingCookie_thenItIsPresent() { + driver.navigate().to(navUrl); + Cookie cookie = new Cookie("foo", "bar"); + driver.manage().addCookie(cookie); + Cookie driverCookie = driver.manage().getCookieNamed("foo"); + + assertThat(driverCookie.getValue(), equalTo("bar")); + } + + @Test + public void whenDeletingCookie_thenItIsAbsent() { + driver.navigate().to(navUrl); + Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(lpCookie, is(not(nullValue()))); + + driver.manage().deleteCookie(lpCookie); + Cookie deletedCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(deletedCookie, is(nullValue())); + } + + @Test + public void whenOverridingCookie_thenItIsUpdated() { + driver.navigate().to(navUrl); + Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); + driver.manage().deleteCookie(lpCookie); + + Cookie newLpCookie = new Cookie("lp_120073", "foo"); + driver.manage().addCookie(newLpCookie); + + Cookie overriddenCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(overriddenCookie.getValue(), equalTo("foo")); + } + +} diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index 38e7a0dd46..c5e94f3afc 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -19,7 +19,7 @@ org.hamcrest java-hamcrest - ${hamcrest.version} + ${java-hamcrest.version} @@ -114,7 +114,7 @@ - 2.0.0.0 + 2.0.0.0 3.1.6 5.5.0 1.5.2 diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml new file mode 100644 index 0000000000..0a7c4b0860 --- /dev/null +++ b/testing-modules/testing-assertions/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + testing-assertions + 0.0.1-SNAPSHOT + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + ch.qos.logback + logback-classic + 1.2.3 + + + org.assertj + assertj-core + 3.15.0 + test + + + diff --git a/testing-modules/testing-assertions/src/main/java/com/baeldung/junit/log/BusinessWorker.java b/testing-modules/testing-assertions/src/main/java/com/baeldung/junit/log/BusinessWorker.java new file mode 100644 index 0000000000..86cd38824c --- /dev/null +++ b/testing-modules/testing-assertions/src/main/java/com/baeldung/junit/log/BusinessWorker.java @@ -0,0 +1,16 @@ +package com.baeldung.junit.log; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BusinessWorker { + private static Logger LOGGER = LoggerFactory.getLogger(BusinessWorker.class); + + public void generateLogs(String msg) { + LOGGER.trace(msg); + LOGGER.debug(msg); + LOGGER.info(msg); + LOGGER.warn(msg); + LOGGER.error(msg); + } +} diff --git a/testing-modules/testing-assertions/src/main/resources/logback.xml b/testing-modules/testing-assertions/src/main/resources/logback.xml new file mode 100644 index 0000000000..d485da62ff --- /dev/null +++ b/testing-modules/testing-assertions/src/main/resources/logback.xml @@ -0,0 +1,16 @@ + + + + + + %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n + + + + + + + + + + \ No newline at end of file diff --git a/testing-modules/testing-assertions/src/test/java/com/baeldung/junit/log/BusinessWorkerUnitTest.java b/testing-modules/testing-assertions/src/test/java/com/baeldung/junit/log/BusinessWorkerUnitTest.java new file mode 100644 index 0000000000..9200caf13d --- /dev/null +++ b/testing-modules/testing-assertions/src/test/java/com/baeldung/junit/log/BusinessWorkerUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.junit.log; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; + +public class BusinessWorkerUnitTest { + private static MemoryAppender memoryAppender; + private static final String LOGGER_NAME = "com.baeldung.junit.log"; + private static final String MSG = "This is a test message!!!"; + + @Before + public void setup() { + Logger logger = (Logger) LoggerFactory.getLogger(LOGGER_NAME); + memoryAppender = new MemoryAppender(); + memoryAppender.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); + logger.setLevel(Level.DEBUG); + logger.addAppender(memoryAppender); + memoryAppender.start(); + + } + + @After + public void cleanUp() { + memoryAppender.reset(); + memoryAppender.stop(); + } + + @Test + public void test() { + BusinessWorker worker = new BusinessWorker(); + worker.generateLogs(MSG); + + // I check that I only have 4 messages (all but trace) + assertThat(memoryAppender.countEventsForLogger(LOGGER_NAME)).isEqualTo(4); + // I look for a specific message at a specific level, and I only have 1 + assertThat(memoryAppender.search(MSG, Level.INFO).size()).isEqualTo(1); + // I check that the entry that is not present is the trace level + assertThat(memoryAppender.contains(MSG, Level.TRACE)).isFalse(); + } +} diff --git a/testing-modules/testing-assertions/src/test/java/com/baeldung/junit/log/MemoryAppender.java b/testing-modules/testing-assertions/src/test/java/com/baeldung/junit/log/MemoryAppender.java new file mode 100644 index 0000000000..31c5c69766 --- /dev/null +++ b/testing-modules/testing-assertions/src/test/java/com/baeldung/junit/log/MemoryAppender.java @@ -0,0 +1,51 @@ +package com.baeldung.junit.log; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; + +/** + * In memory slf4j appender
+ * Convenient appender to be able to check slf4j invocations + */ +public class MemoryAppender extends ListAppender { + public void reset() { + this.list.clear(); + } + + public boolean contains(String string, Level level) { + return this.list.stream() + .anyMatch(event -> event.getMessage().toString().contains(string) + && event.getLevel().equals(level)); + } + + public int countEventsForLogger(String loggerName) { + return (int) this.list.stream() + .filter(event -> event.getLoggerName().contains(loggerName)).count(); + } + + public List search(String string) { + return this.list.stream() + .filter(event -> event.getMessage().toString().contains(string)) + .collect(Collectors.toList()); + } + + public List search(String string, Level level) { + return this.list.stream() + .filter(event -> event.getMessage().toString().contains(string) + && event.getLevel().equals(level)) + .collect(Collectors.toList()); + } + + public int getSize() { + return this.list.size(); + } + + public List getLoggedEvents() { + return Collections.unmodifiableList(this.list); + } +} diff --git a/testing-modules/testing-assertions/src/test/resources/logback.xml b/testing-modules/testing-assertions/src/test/resources/logback.xml new file mode 100644 index 0000000000..980ce897ff --- /dev/null +++ b/testing-modules/testing-assertions/src/test/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + + %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n + + + + + + + \ No newline at end of file diff --git a/testing-modules/testing-libraries/README.md b/testing-modules/testing-libraries/README.md index d76b7b1308..b1e1575e63 100644 --- a/testing-modules/testing-libraries/README.md +++ b/testing-modules/testing-libraries/README.md @@ -5,8 +5,8 @@ - [Intro to JaCoCo](http://www.baeldung.com/jacoco) - [Cucumber and Scenario Outline](http://www.baeldung.com/cucumber-scenario-outline) - [Cucumber Java 8 Support](http://www.baeldung.com/cucumber-java-8-support) -- [Introduction to Lambda Behave](http://www.baeldung.com/lambda-behave) - [Introduction to CheckStyle](https://www.baeldung.com/checkstyle-java) - [Introduction to FindBugs](https://www.baeldung.com/intro-to-findbugs) - - +- [Cucumber Data Tables](https://www.baeldung.com/cucumber-data-tables) +- [Cucumber Background](https://www.baeldung.com/java-cucumber-background) +- [Cucumber Hooks](https://www.baeldung.com/java-cucumber-hooks) diff --git a/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/Book.java b/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/Book.java new file mode 100644 index 0000000000..dc8f1dcf64 --- /dev/null +++ b/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/Book.java @@ -0,0 +1,35 @@ +package com.baeldung.cucumberhooks.books; + +public class Book { + + private String title; + private String author; + + public Book(String title, String author) { + this.title = title; + this.author = author; + } + + public Book() {} + + 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 String toString() { + return "Book [title=" + title + ", author=" + author + "]"; + } +} diff --git a/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/BookStore.java b/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/BookStore.java new file mode 100644 index 0000000000..cc4e42d28f --- /dev/null +++ b/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/BookStore.java @@ -0,0 +1,28 @@ +package com.baeldung.cucumberhooks.books; + +import java.util.*; +import java.util.stream.Collectors; + +public class BookStore { + private List books = new ArrayList<>(); + + public void addBook(Book book) { + books.add(book); + } + + public void addAllBooks(Collection books) { + this.books.addAll(books); + } + + public List booksByAuthor(String author) { + return books.stream() + .filter(book -> Objects.equals(author, book.getAuthor())) + .collect(Collectors.toList()); + } + + public Optional bookByTitle(String title) { + return books.stream() + .filter(book -> book.getTitle().equals(title)) + .findFirst(); + } +} diff --git a/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationHooks.java b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationHooks.java new file mode 100644 index 0000000000..8de55e4611 --- /dev/null +++ b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationHooks.java @@ -0,0 +1,48 @@ +package com.baeldung.cucumberhooks.books; + +import io.cucumber.core.api.Scenario; +import io.cucumber.java.After; +import io.cucumber.java.AfterStep; +import io.cucumber.java.Before; +import io.cucumber.java.BeforeStep; +import io.cucumber.java8.En; + +public class BookStoreWithHooksIntegrationHooks implements En { + + public BookStoreWithHooksIntegrationHooks() { + Before(1, () -> startBrowser()); + } + + @Before(order=2, value="@Screenshots") + public void beforeScenario(Scenario scenario) { + takeScreenshot(); + } + + @After + public void afterScenario(Scenario scenario) { + takeScreenshot(); + } + + @BeforeStep + public void beforeStep(Scenario scenario) { + takeScreenshot(); + } + + @AfterStep + public void afterStep(Scenario scenario) { + takeScreenshot(); + closeBrowser(); + } + + public void takeScreenshot() { + //code to take and save screenshot + } + + public void startBrowser() { + //code to open browser + } + + public void closeBrowser() { + //code to close browser + } +} diff --git a/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationTest.java b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationTest.java new file mode 100644 index 0000000000..79e43bad27 --- /dev/null +++ b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationTest.java @@ -0,0 +1,13 @@ +package com.baeldung.cucumberhooks.books; + +import io.cucumber.junit.Cucumber; +import io.cucumber.junit.CucumberOptions; +import org.junit.runner.RunWith; + +@RunWith(Cucumber.class) +@CucumberOptions(features = "classpath:features/book-store-with-hooks.feature", + glue = "com.baeldung.cucumberhooks.books" +) +public class BookStoreWithHooksIntegrationTest { + +} diff --git a/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksRunSteps.java b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksRunSteps.java new file mode 100644 index 0000000000..8ebda5ffa4 --- /dev/null +++ b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksRunSteps.java @@ -0,0 +1,44 @@ +package com.baeldung.cucumberhooks.books; + +import io.cucumber.datatable.DataTable; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; +import io.cucumber.java8.En; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class BookStoreWithHooksRunSteps implements En { + + private BookStore store; + private List foundBooks; + private Book foundBook; + + public BookStoreWithHooksRunSteps() { + store = new BookStore(); + foundBooks = new ArrayList<>(); + } + + @Given("^The following books are available in the store$") + public void haveBooksInTheStore(DataTable table) { + List> rows = table.asLists(String.class); + + for (List columns: rows) { + store.addBook(new Book(columns.get(0), columns.get(1))); + } + } + + @When("^I ask for a book by the author (.+)$") + public void searchForBooksByAuthor(String author) { + foundBooks = store.booksByAuthor(author); + } + + @Then("^The salesperson says that there are (\\d+) books$") + public void findBooks(int count) { + assertEquals(count, foundBooks.size()); + } + +} diff --git a/testing-modules/testing-libraries/src/test/resources/features/book-store-with-hooks.feature b/testing-modules/testing-libraries/src/test/resources/features/book-store-with-hooks.feature new file mode 100644 index 0000000000..78e136d68d --- /dev/null +++ b/testing-modules/testing-libraries/src/test/resources/features/book-store-with-hooks.feature @@ -0,0 +1,17 @@ +Feature: Book Store With Hooks + Background: The Book Store + Given The following books are available in the store + | The Devil in the White City | Erik Larson | + | The Lion, the Witch and the Wardrobe | C.S. Lewis | + | In the Garden of Beasts | Erik Larson | + + @Screenshots + Scenario: 1 - Find books by author + When I ask for a book by the author Erik Larson + Then The salesperson says that there are 2 books + + Scenario: 2 - Find books by author, but isn't there + When I ask for a book by the author Marcel Proust + Then The salesperson says that there are 0 books + + diff --git a/twitter4j/pom.xml b/twitter4j/pom.xml index 6d98e2fe58..274b5c75c3 100644 --- a/twitter4j/pom.xml +++ b/twitter4j/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - Twitter4J - Twitter4J + twitter4J + twitter4J jar diff --git a/vavr-2/README.md b/vavr-2/README.md new file mode 100644 index 0000000000..71814a08fd --- /dev/null +++ b/vavr-2/README.md @@ -0,0 +1,8 @@ +## Vavr + +This module contains articles about Vavr. + +### Relevant Articles: +- [Introduction to Vavr’s Either](https://www.baeldung.com/vavr-either) +- [Interoperability Between Java and Vavr](https://www.baeldung.com/java-vavr) +- [[<-- prev]](/vavr) diff --git a/vavr-2/pom.xml b/vavr-2/pom.xml new file mode 100644 index 0000000000..d20dd9afef --- /dev/null +++ b/vavr-2/pom.xml @@ -0,0 +1,27 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + vavr-2 + vavr-2 + jar + + + + io.vavr + vavr-test + ${vavr.version} + + + + + 0.9.1 + + \ No newline at end of file diff --git a/vavr/src/main/java/com/baeldung/vavr/either/EitherDemo.java b/vavr-2/src/main/java/com/baeldung/vavr/either/EitherDemo.java similarity index 100% rename from vavr/src/main/java/com/baeldung/vavr/either/EitherDemo.java rename to vavr-2/src/main/java/com/baeldung/vavr/either/EitherDemo.java diff --git a/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java b/vavr-2/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java similarity index 100% rename from vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java rename to vavr-2/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java diff --git a/vavr/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java b/vavr-2/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java similarity index 100% rename from vavr/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java rename to vavr-2/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java diff --git a/vavr/README.md b/vavr/README.md index 2b8bb25356..e04e02069f 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -13,5 +13,4 @@ This module contains articles about Vavr. - [Guide to Collections API in Vavr](https://www.baeldung.com/vavr-collections) - [Collection Factory Methods for Vavr](https://www.baeldung.com/vavr-collection-factory-methods) - [Introduction to Future in Vavr](https://www.baeldung.com/vavr-future) -- [Introduction to Vavr’s Either](https://www.baeldung.com/vavr-either) -- [Interoperability Between Java and Vavr](https://www.baeldung.com/java-vavr) +- [[next -->]](/vavr-2) diff --git a/webrtc/README.md b/webrtc/README.md new file mode 100644 index 0000000000..42c06341b4 --- /dev/null +++ b/webrtc/README.md @@ -0,0 +1,8 @@ +## WebRTC + +This module contains articles about WebRTC + +### Relevant Articles: + +- [Guide to WebRTC](https://www.baeldung.com/webrtc) + diff --git a/webrtc/pom.xml b/webrtc/pom.xml index 2a3b48b2ed..6dc98afb1c 100644 --- a/webrtc/pom.xml +++ b/webrtc/pom.xml @@ -1,5 +1,6 @@ - 4.0.0 diff --git a/wicket/pom.xml b/wicket/pom.xml index 5175eca59c..68bc2f3e6b 100644 --- a/wicket/pom.xml +++ b/wicket/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.wicket.examples wicket diff --git a/wildfly/pom.xml b/wildfly/pom.xml index e81b609206..7b2a474c8d 100644 --- a/wildfly/pom.xml +++ b/wildfly/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 org.springframework wildfly @@ -9,9 +11,10 @@ war - org.springframework.boot - spring-boot-starter-parent - 2.1.6.RELEASE + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 diff --git a/xml/pom.xml b/xml/pom.xml index eb2d567957..8b2df41af6 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 xml 0.1-SNAPSHOT @@ -326,8 +327,7 @@ - + maven-assembly-plugin ${project.basedir} @@ -346,10 +346,8 @@ - make-assembly - package + make-assembly + package attached diff --git a/xstream/pom.xml b/xstream/pom.xml index a703aa3774..618df1a7c2 100644 --- a/xstream/pom.xml +++ b/xstream/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 org.baeldung xstream